fix(web): connect the chat to the daemon end-to-end
- ws auth frame now carries the token top-level (docs §3.3); daemon accepts payload.token too - entries route accepts workspaceId/sessionFile so disk-only sessions page history - chat registers session metadata and pages history for non-live sessions - e2e asserts a real ASSISTANT reply (PONG) and waits up to 180s - visual.sh: real daemon + pairing + Playwright screenshots of the four pages
This commit is contained in:
1 parent
721661177c
commit
854d6d2997
8 files changed
+145
-14
No files matched your search
+17
-8
@@ -99,21 +99,30 @@ pass "session $SID"
|
|||||||
echo "==> sending prompt (real model call)"
|
echo "==> sending prompt (real model call)"
|
||||||
cmd "{\"method\":\"prompt.send\",\"sessionId\":\"$SID\",\"params\":{\"text\":\"Reply with exactly the word PONG and nothing else.\"}}" >/dev/null || fail "prompt.send"
|
cmd "{\"method\":\"prompt.send\",\"sessionId\":\"$SID\",\"params\":{\"text\":\"Reply with exactly the word PONG and nothing else.\"}}" >/dev/null || fail "prompt.send"
|
||||||
|
|
||||||
|
# Require an ASSISTANT message containing PONG (the user prompt also contains it).
|
||||||
|
assistant_text() {
|
||||||
|
echo "$1" | jq -r '[.entries[]? | select(.type == "message" and .message.role == "assistant")
|
||||||
|
| (.message.content | if type == "string" then . else ([.[]? | select(.type == "text") | .text] | join(" ")) end)]
|
||||||
|
| join(" ")' 2>/dev/null || true
|
||||||
|
}
|
||||||
|
|
||||||
FOUND=0
|
FOUND=0
|
||||||
for i in $(seq 1 120); do
|
for i in $(seq 1 180); do
|
||||||
SESS=$(api "$BASE/api/v1/workspaces/$WSID/sessions" 2>/dev/null || echo '')
|
SESS=$(api "$BASE/api/v1/workspaces/$WSID/sessions" 2>/dev/null || echo '')
|
||||||
REAL=$(echo "$SESS" | jq -r '.sessions[0].sessionId // empty' 2>/dev/null || true)
|
REAL=$(echo "$SESS" | jq -r '.sessions[]? | select(.live == true) | .sessionId' 2>/dev/null | head -1)
|
||||||
|
FILE=$(echo "$SESS" | jq -r '.sessions[]? | select(.live == true) | .sessionFile' 2>/dev/null | head -1)
|
||||||
if [ -n "$REAL" ]; then
|
if [ -n "$REAL" ]; then
|
||||||
ENTRIES=$(api "$BASE/api/v1/sessions/$REAL/entries?limit=50" 2>/dev/null || echo '')
|
ENTRIES=$(api "$BASE/api/v1/sessions/$REAL/entries?limit=50&workspaceId=$WSID&sessionFile=$FILE" 2>/dev/null || echo '')
|
||||||
if echo "$ENTRIES" | grep -qi 'PONG'; then FOUND=1; SID="$REAL"; break; fi
|
TEXT=$(assistant_text "$ENTRIES")
|
||||||
|
if echo "$TEXT" | grep -qi 'PONG'; then FOUND=1; SID="$REAL"; break; fi
|
||||||
fi
|
fi
|
||||||
if [ $((i % 10)) -eq 0 ]; then
|
if [ $((i % 15)) -eq 0 ]; then
|
||||||
echo " ... waiting (${i}/120) real=${REAL:-?} entries=$(echo "$ENTRIES" | head -c 240)"
|
echo " ... waiting (${i}/180) real=${REAL:-?} assistant=${TEXT:-<none>}"
|
||||||
fi
|
fi
|
||||||
sleep 1
|
sleep 1
|
||||||
done
|
done
|
||||||
[ "$FOUND" = "1" ] || fail "no assistant answer within 120s"
|
[ "$FOUND" = "1" ] || fail "no assistant answer within 180s"
|
||||||
pass "assistant answered (history endpoint contains PONG)"
|
pass "assistant answered PONG (history endpoint, assistant role)"
|
||||||
|
|
||||||
echo "==> session state"
|
echo "==> session state"
|
||||||
api "$BASE/api/v1/workspaces/$WSID/sessions" | jq -c '.' | head -c 800; echo
|
api "$BASE/api/v1/workspaces/$WSID/sessions" | jq -c '.' | head -c 800; echo
|
||||||
|
|||||||
Executable
+83
@@ -0,0 +1,83 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Visual acceptance: boot the real daemon + plugin, pair a browser, and capture
|
||||||
|
# the four pages at desktop and mobile widths for design-parity review.
|
||||||
|
#
|
||||||
|
# bash scripts/e2e/visual.sh [output-dir]
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
REPO="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||||
|
OUT="${1:-/tmp/pi2-visual}"
|
||||||
|
PW="${PLAYWRIGHT_BIN:-/home/yuez/.local/share/mise/installs/npm-playwright/latest/bin/playwright}"
|
||||||
|
WS="${PI2_VISUAL_WS:-/tmp/pi2-e2e-ws.MDdJQT}"
|
||||||
|
[ -d "$WS" ] || WS="$(mktemp -d /tmp/pi2-visual-ws.XXXXXX)"
|
||||||
|
|
||||||
|
RUN="$(mktemp -d /tmp/pi2-visual-run.XXXXXX)"
|
||||||
|
DATA="$(mktemp -d /tmp/pi2-visual-data.XXXXXX)"
|
||||||
|
STATE="$(mktemp -d /tmp/pi2-visual-state.XXXXXX)"
|
||||||
|
LOG="$STATE/visual.log"
|
||||||
|
mkdir -p "$OUT" "$STATE/instances"
|
||||||
|
|
||||||
|
export PI2_RUNTIME_DIR="$RUN" PI2_DATA_DIR="$DATA" PI2_STATE_DIR="$STATE"
|
||||||
|
export XDG_STATE_HOME="$STATE" XDG_DATA_HOME="$DATA"
|
||||||
|
export PI2_WORKSPACE_ROOTS="$(dirname "$WS")"
|
||||||
|
export PI2_NVIM_BIN="${PI2_NVIM_BIN:-$(command -v nvim)}"
|
||||||
|
export PI2_NVIM_INIT="$REPO/scripts/e2e/host-init.lua"
|
||||||
|
export PI2_E2E_PLUGIN="${PI2_E2E_PLUGIN:-/home/yuez/Workspace/Neovim/pi2.nvim-web}"
|
||||||
|
|
||||||
|
node "$REPO/dist/cli/pi2d.js" --foreground --port 0 >"$LOG" 2>&1 &
|
||||||
|
DPID=$!
|
||||||
|
cleanup() { kill "$DPID" 2>/dev/null || true; wait "$DPID" 2>/dev/null || true; }
|
||||||
|
trap cleanup EXIT
|
||||||
|
|
||||||
|
for _ in $(seq 1 100); do [ -f "$RUN/daemon.json" ] && break; sleep 0.1; done
|
||||||
|
PORT=$(sed -n 's/.*"port": *\([0-9]*\).*/\1/p' "$RUN/daemon.json")
|
||||||
|
BASE="http://127.0.0.1:$PORT"
|
||||||
|
TOKEN=$(cat "$RUN/cli.token")
|
||||||
|
api() { curl -fsS -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' "$@"; }
|
||||||
|
cmd() { api -X POST "$BASE/api/v1/cmd" -d "$1"; }
|
||||||
|
|
||||||
|
WSID=$(cmd "{\"method\":\"workspace.add\",\"params\":{\"cwd\":\"$WS\",\"trust\":true}}" | jq -r '.workspace.workspaceId')
|
||||||
|
cmd "{\"method\":\"instance.ensure\",\"params\":{\"workspaceId\":\"$WSID\"}}" >/dev/null
|
||||||
|
for _ in $(seq 1 150); do
|
||||||
|
ST=$(api "$BASE/api/v1/workspaces" | jq -r --arg id "$WSID" '(if type=="array" then . else .workspaces end)[]|select(.workspaceId==$id)|.instance.status')
|
||||||
|
[ "$ST" = "ready" ] && break
|
||||||
|
sleep 0.2
|
||||||
|
done
|
||||||
|
echo "instance: $ST workspace: $WSID"
|
||||||
|
|
||||||
|
CODE=$(cmd '{"method":"pair.create","params":{}}' | jq -r '.code')
|
||||||
|
DEVTOKEN=$(curl -fsS -X POST "$BASE/api/v1/pair" -H 'Content-Type: application/json' \
|
||||||
|
-d "{\"code\":\"$CODE\",\"deviceName\":\"Playwright\",\"kind\":\"laptop\"}" | jq -r '.token')
|
||||||
|
echo "paired device token: ${DEVTOKEN:0:8}…"
|
||||||
|
|
||||||
|
STORAGE="$STATE/storage.json"
|
||||||
|
cat >"$STORAGE" <<JSON
|
||||||
|
{"cookies":[],"origins":[{"origin":"$BASE","localStorage":[
|
||||||
|
{"name":"pi2-connection","value":"paired"},
|
||||||
|
{"name":"pi2-endpoint","value":"$BASE"},
|
||||||
|
{"name":"pi2-device-token","value":"$DEVTOKEN"},
|
||||||
|
{"name":"pi2-device","value":"Playwright"},
|
||||||
|
{"name":"pi2-connected-at","value":"$(date +%s000)"}
|
||||||
|
]}]}
|
||||||
|
JSON
|
||||||
|
|
||||||
|
EMPTY="$STATE/empty.json"
|
||||||
|
cat >"$EMPTY" <<JSON
|
||||||
|
{"cookies":[],"origins":[]}
|
||||||
|
JSON
|
||||||
|
|
||||||
|
shot() { # name url width height [storage]
|
||||||
|
local name="$1" url="$2" w="$3" h="$4" storage="${5:-$STORAGE}"
|
||||||
|
"$PW" screenshot --browser chromium --channel chromium --color-scheme dark --viewport-size "$w,$h" \
|
||||||
|
--load-storage "$storage" --wait-for-timeout 2500 "$url" "$OUT/$name.png" >/dev/null 2>&1 \
|
||||||
|
&& echo "PASS $name.png ($w×$h)" || echo "FAIL $name.png"
|
||||||
|
}
|
||||||
|
|
||||||
|
shot workspaces-desktop "$BASE/workspaces" 1280 900
|
||||||
|
shot workspaces-mobile "$BASE/workspaces" 380 780
|
||||||
|
shot chat-desktop "$BASE/chat?workspace=$WSID" 1280 900
|
||||||
|
shot chat-mobile "$BASE/chat?workspace=$WSID" 380 780
|
||||||
|
shot status-desktop "$BASE/status" 1280 900
|
||||||
|
shot connect-mobile "$BASE/connect" 380 780 "$EMPTY"
|
||||||
|
|
||||||
|
echo "screenshots in $OUT"
|
||||||
+6
-1
@@ -187,7 +187,12 @@ export function createApp(deps: AppDeps): Hono<Env> {
|
|||||||
if (before !== undefined) params.before = before;
|
if (before !== undefined) params.before = before;
|
||||||
const limit = Number(c.req.query("limit"));
|
const limit = Number(c.req.query("limit"));
|
||||||
if (Number.isFinite(limit) && limit > 0) params.limit = Math.min(500, Math.floor(limit));
|
if (Number.isFinite(limit) && limit > 0) params.limit = Math.min(500, Math.floor(limit));
|
||||||
const ack = await router.relaySessionQuery(c.req.param("sid"), "workspace.query", {
|
const workspaceId = c.req.query("workspaceId");
|
||||||
|
const sessionFile = c.req.query("sessionFile");
|
||||||
|
if (sessionFile) params.sessionFile = sessionFile;
|
||||||
|
const ack = workspaceId
|
||||||
|
? await router.relayWorkspaceQuery(workspaceId, "entries", params)
|
||||||
|
: await router.relaySessionQuery(c.req.param("sid"), "workspace.query", {
|
||||||
...params,
|
...params,
|
||||||
kind: "entries",
|
kind: "entries",
|
||||||
});
|
});
|
||||||
|
|||||||
+9
-2
@@ -321,12 +321,19 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle {
|
|||||||
}
|
}
|
||||||
const type = typeof message.type === "string" ? message.type : "";
|
const type = typeof message.type === "string" ? message.type : "";
|
||||||
if (!state.authenticated) {
|
if (!state.authenticated) {
|
||||||
if (type !== "auth" || typeof message.token !== "string") {
|
const payload = message.payload as Record<string, unknown> | undefined;
|
||||||
|
const authToken =
|
||||||
|
typeof message.token === "string"
|
||||||
|
? message.token
|
||||||
|
: payload && typeof payload.token === "string"
|
||||||
|
? payload.token
|
||||||
|
: undefined;
|
||||||
|
if (type !== "auth" || typeof authToken !== "string") {
|
||||||
sendError(state, ERROR_CODES.UNAUTHORIZED, "authenticate first");
|
sendError(state, ERROR_CODES.UNAUTHORIZED, "authenticate first");
|
||||||
state.ws.close(CLOSE_UNAUTHORIZED, "unauthorized");
|
state.ws.close(CLOSE_UNAUTHORIZED, "unauthorized");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!authenticate(state, message.token)) {
|
if (!authenticate(state, authToken)) {
|
||||||
sendError(state, ERROR_CODES.UNAUTHORIZED, "invalid device token");
|
sendError(state, ERROR_CODES.UNAUTHORIZED, "invalid device token");
|
||||||
state.ws.close(CLOSE_UNAUTHORIZED, "unauthorized");
|
state.ws.close(CLOSE_UNAUTHORIZED, "unauthorized");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
normalizeSessionsPayload,
|
normalizeSessionsPayload,
|
||||||
normalizeSnapshotState,
|
normalizeSnapshotState,
|
||||||
} from "./session-state";
|
} from "./session-state";
|
||||||
|
import { setSessionMeta } from "./history";
|
||||||
import { useChatStore } from "./store";
|
import { useChatStore } from "./store";
|
||||||
|
|
||||||
export const EMPTY_SESSIONS: SessionState[] = [];
|
export const EMPTY_SESSIONS: SessionState[] = [];
|
||||||
@@ -142,6 +143,15 @@ export function useChatSessions(workspaceId: string | undefined, enabled: boolea
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!workspaceId || !query.data) return;
|
if (!workspaceId || !query.data) return;
|
||||||
|
const raw = query.data as { sessions?: Array<{ sessionId?: unknown; sessionFile?: unknown }> } | undefined;
|
||||||
|
for (const row of raw?.sessions ?? []) {
|
||||||
|
if (typeof row?.sessionId === "string") {
|
||||||
|
setSessionMeta(row.sessionId, {
|
||||||
|
workspaceId,
|
||||||
|
sessionFile: typeof row.sessionFile === "string" ? row.sessionFile : undefined,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
const current = useSessionsStore.getState();
|
const current = useSessionsStore.getState();
|
||||||
const existing = current.byWorkspace[workspaceId] ?? [];
|
const existing = current.byWorkspace[workspaceId] ?? [];
|
||||||
const next = normalizeSessionsPayload(query.data, workspaceId, existing);
|
const next = normalizeSessionsPayload(query.data, workspaceId, existing);
|
||||||
|
|||||||
@@ -12,7 +12,21 @@ export interface FetchedPage {
|
|||||||
cursor: { before?: string; hasMore: boolean };
|
cursor: { before?: string; hasMore: boolean };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** `GET /api/v1/sessions/:sid/entries?before=&limit=` → raw pi entries + cursor. */
|
/**
|
||||||
|
* Session metadata needed to page a session that is not live in an instance
|
||||||
|
* (disk-only rows): the daemon routes by workspace and the plugin reads the file.
|
||||||
|
* Populated from the sessions list, keyed by session id.
|
||||||
|
*/
|
||||||
|
const sessionMeta = new Map<string, { workspaceId?: string; sessionFile?: string }>();
|
||||||
|
|
||||||
|
export function setSessionMeta(
|
||||||
|
sessionId: string,
|
||||||
|
meta: { workspaceId?: string; sessionFile?: string },
|
||||||
|
): void {
|
||||||
|
sessionMeta.set(sessionId, { ...sessionMeta.get(sessionId), ...meta });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `GET /api/v1/sessions/:sid/entries?before=&limit=&workspaceId=&sessionFile=` → raw pi entries + cursor. */
|
||||||
export async function fetchEntriesPage(
|
export async function fetchEntriesPage(
|
||||||
sessionId: string,
|
sessionId: string,
|
||||||
before?: string,
|
before?: string,
|
||||||
@@ -21,6 +35,9 @@ export async function fetchEntriesPage(
|
|||||||
): Promise<FetchedPage> {
|
): Promise<FetchedPage> {
|
||||||
const query = new URLSearchParams({ limit: String(limit) });
|
const query = new URLSearchParams({ limit: String(limit) });
|
||||||
if (before) query.set("before", before);
|
if (before) query.set("before", before);
|
||||||
|
const meta = sessionMeta.get(sessionId);
|
||||||
|
if (meta?.workspaceId) query.set("workspaceId", meta.workspaceId);
|
||||||
|
if (meta?.sessionFile) query.set("sessionFile", meta.sessionFile);
|
||||||
const raw = await apiRequest<unknown>(
|
const raw = await apiRequest<unknown>(
|
||||||
`/api/v1/sessions/${encodeURIComponent(sessionId)}/entries?${query.toString()}`,
|
`/api/v1/sessions/${encodeURIComponent(sessionId)}/entries?${query.toString()}`,
|
||||||
{ signal },
|
{ signal },
|
||||||
|
|||||||
+1
-1
@@ -216,7 +216,7 @@ export class PiWsClient {
|
|||||||
socket.onopen = () => {
|
socket.onopen = () => {
|
||||||
if (this.socket !== socket) return;
|
if (this.socket !== socket) return;
|
||||||
this.setState("authenticating");
|
this.setState("authenticating");
|
||||||
this.send({ v: 1, type: AUTH_FRAME_TYPE, payload: { token: this.token ?? undefined } });
|
this.send({ v: 1, type: AUTH_FRAME_TYPE, token: this.token ?? undefined });
|
||||||
this.authTimer = setTimeout(() => {
|
this.authTimer = setTimeout(() => {
|
||||||
if (this.state !== "authenticating" || this.socket !== socket) return;
|
if (this.state !== "authenticating" || this.socket !== socket) return;
|
||||||
this.handlers.onError?.(new Error("WebSocket auth timed out"));
|
this.handlers.onError?.(new Error("WebSocket auth timed out"));
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ describe("PiWsClient", () => {
|
|||||||
const socket = sockets[0]!;
|
const socket = sockets[0]!;
|
||||||
socket.open();
|
socket.open();
|
||||||
expect(states).toEqual(["connecting", "authenticating"]);
|
expect(states).toEqual(["connecting", "authenticating"]);
|
||||||
expect(socket.sent[0]).toEqual({ v: 1, type: "auth", payload: { token: "pkt_test" } });
|
expect(socket.sent[0]).toEqual({ v: 1, type: "auth", token: "pkt_test" });
|
||||||
|
|
||||||
// Queued before authentication.
|
// Queued before authentication.
|
||||||
client.subscribe("s1");
|
client.subscribe("s1");
|
||||||
|
|||||||
Reference in new issue
Block a user