diff --git a/scripts/e2e/full-e2e.sh b/scripts/e2e/full-e2e.sh index bbfc77c..03a259f 100755 --- a/scripts/e2e/full-e2e.sh +++ b/scripts/e2e/full-e2e.sh @@ -99,21 +99,30 @@ pass "session $SID" 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" +# 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 -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 '') - 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 - ENTRIES=$(api "$BASE/api/v1/sessions/$REAL/entries?limit=50" 2>/dev/null || echo '') - if echo "$ENTRIES" | grep -qi 'PONG'; then FOUND=1; SID="$REAL"; break; fi + ENTRIES=$(api "$BASE/api/v1/sessions/$REAL/entries?limit=50&workspaceId=$WSID&sessionFile=$FILE" 2>/dev/null || echo '') + TEXT=$(assistant_text "$ENTRIES") + if echo "$TEXT" | grep -qi 'PONG'; then FOUND=1; SID="$REAL"; break; fi fi - if [ $((i % 10)) -eq 0 ]; then - echo " ... waiting (${i}/120) real=${REAL:-?} entries=$(echo "$ENTRIES" | head -c 240)" + if [ $((i % 15)) -eq 0 ]; then + echo " ... waiting (${i}/180) real=${REAL:-?} assistant=${TEXT:-}" fi sleep 1 done -[ "$FOUND" = "1" ] || fail "no assistant answer within 120s" -pass "assistant answered (history endpoint contains PONG)" +[ "$FOUND" = "1" ] || fail "no assistant answer within 180s" +pass "assistant answered PONG (history endpoint, assistant role)" echo "==> session state" api "$BASE/api/v1/workspaces/$WSID/sessions" | jq -c '.' | head -c 800; echo diff --git a/scripts/e2e/visual.sh b/scripts/e2e/visual.sh new file mode 100755 index 0000000..407e3c8 --- /dev/null +++ b/scripts/e2e/visual.sh @@ -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" <"$EMPTY" </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" diff --git a/src/daemon/http.ts b/src/daemon/http.ts index 2ed2791..ad1aeb8 100644 --- a/src/daemon/http.ts +++ b/src/daemon/http.ts @@ -187,10 +187,15 @@ export function createApp(deps: AppDeps): Hono { if (before !== undefined) params.before = before; const limit = Number(c.req.query("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", { - ...params, - kind: "entries", - }); + 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, + kind: "entries", + }); return json(200, ack); }); diff --git a/src/daemon/ws.ts b/src/daemon/ws.ts index 17fc362..3102b61 100644 --- a/src/daemon/ws.ts +++ b/src/daemon/ws.ts @@ -321,12 +321,19 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle { } const type = typeof message.type === "string" ? message.type : ""; if (!state.authenticated) { - if (type !== "auth" || typeof message.token !== "string") { + const payload = message.payload as Record | 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"); state.ws.close(CLOSE_UNAUTHORIZED, "unauthorized"); return; } - if (!authenticate(state, message.token)) { + if (!authenticate(state, authToken)) { sendError(state, ERROR_CODES.UNAUTHORIZED, "invalid device token"); state.ws.close(CLOSE_UNAUTHORIZED, "unauthorized"); } diff --git a/web/src/features/chat/data.ts b/web/src/features/chat/data.ts index 765860b..99e2661 100644 --- a/web/src/features/chat/data.ts +++ b/web/src/features/chat/data.ts @@ -15,6 +15,7 @@ import { normalizeSessionsPayload, normalizeSnapshotState, } from "./session-state"; +import { setSessionMeta } from "./history"; import { useChatStore } from "./store"; export const EMPTY_SESSIONS: SessionState[] = []; @@ -142,6 +143,15 @@ export function useChatSessions(workspaceId: string | undefined, enabled: boolea useEffect(() => { 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 existing = current.byWorkspace[workspaceId] ?? []; const next = normalizeSessionsPayload(query.data, workspaceId, existing); diff --git a/web/src/features/chat/history.ts b/web/src/features/chat/history.ts index f78089b..46b51de 100644 --- a/web/src/features/chat/history.ts +++ b/web/src/features/chat/history.ts @@ -12,7 +12,21 @@ export interface FetchedPage { 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(); + +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( sessionId: string, before?: string, @@ -21,6 +35,9 @@ export async function fetchEntriesPage( ): Promise { const query = new URLSearchParams({ limit: String(limit) }); 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( `/api/v1/sessions/${encodeURIComponent(sessionId)}/entries?${query.toString()}`, { signal }, diff --git a/web/src/lib/ws.ts b/web/src/lib/ws.ts index 5a21ee2..baa1ee1 100644 --- a/web/src/lib/ws.ts +++ b/web/src/lib/ws.ts @@ -216,7 +216,7 @@ export class PiWsClient { socket.onopen = () => { if (this.socket !== socket) return; 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(() => { if (this.state !== "authenticating" || this.socket !== socket) return; this.handlers.onError?.(new Error("WebSocket auth timed out")); diff --git a/web/tests/ws.test.ts b/web/tests/ws.test.ts index 686e53f..0c3025a 100644 --- a/web/tests/ws.test.ts +++ b/web/tests/ws.test.ts @@ -78,7 +78,7 @@ describe("PiWsClient", () => { const socket = sockets[0]!; socket.open(); 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. client.subscribe("s1");