diff --git a/web/src/components/app-shell.tsx b/web/src/components/app-shell.tsx index 980c858..03d5c56 100644 --- a/web/src/components/app-shell.tsx +++ b/web/src/components/app-shell.tsx @@ -1,4 +1,4 @@ -import { useEffect } from "react"; +import { useEffect, useRef } from "react"; import { useTranslation } from "react-i18next"; import { Icon, type IconName } from "@/components/icons"; @@ -6,11 +6,14 @@ import { LangMenu } from "@/components/shared/lang-menu"; import { ServerChip } from "@/components/shared/server-chip"; import { ThemeMenu } from "@/components/shared/theme-menu"; import { SidebarItem } from "@/components/ui/sidebar-item"; -import { api } from "@/lib/api"; +import { clearPairMeta } from "@/features/connect/pairing"; +import { api, getDeviceToken, onUnauthorized } from "@/lib/api"; +import { CONNECT_PATH, safeNext } from "@/lib/routing"; +import { defaultWsUrl, PiWsClient, type WsConnectionState } from "@/lib/ws"; import { useConnectionStore } from "@/stores/connection"; import { useSessionsStore } from "@/stores/sessions"; import { useWorkspacesStore } from "@/stores/workspaces"; -import { Link, Outlet, useRouterState } from "@tanstack/react-router"; +import { Link, Outlet, useNavigate, useRouterState } from "@tanstack/react-router"; import { useQuery } from "@tanstack/react-query"; interface NavItem { @@ -106,11 +109,19 @@ function NavLinks({ pathname }: { pathname: string }) { export function AppShell() { const { t } = useTranslation(); + const navigate = useNavigate(); const pathname = useRouterState({ select: (state) => state.location.pathname }); + const href = useRouterState({ select: (state) => state.location.href }); const paired = useConnectionStore((state) => state.paired); const setServer = useConnectionStore((state) => state.setServer); + const wsState = useConnectionStore((state) => state.wsState); + const setWsState = useConnectionStore((state) => state.setWsState); + const disconnect = useConnectionStore((state) => state.disconnect); const isConnect = pathname.startsWith("/connect"); + // The chat page owns its own socket and already publishes wsState. + const ownsSocket = !pathname.startsWith("/chat"); const page = pageName(pathname); + const redirectingRef = useRef(false); const info = useQuery({ queryKey: ["info"], @@ -128,8 +139,62 @@ export function AppShell() { document.body.dataset.page = page; }, [page]); + // A fresh pairing re-arms the one-shot unauthorized redirect. + useEffect(() => { + if (paired) redirectingRef.current = false; + }, [paired]); + + /** + * The daemon rejected the stored device token: drop the local connection + * (token + paired flags) and bounce once to `/connect` with the current page + * as `next`. The ref keeps a burst of parallel 401s from looping. + */ + useEffect(() => { + return onUnauthorized(() => { + if (redirectingRef.current) return; + redirectingRef.current = true; + disconnect(); + clearPairMeta(); + void navigate({ href: `${CONNECT_PATH}?next=${encodeURIComponent(safeNext(href))}`, replace: true }); + }); + }, [disconnect, href, navigate]); + + /** + * Lightweight socket probe so `wsState` (shell banner, status card) is + * populated on pages that do not open a socket themselves. Chat skips it + * because `useChatSocket` already publishes the same state. + */ + useEffect(() => { + if (!paired || isConnect || !ownsSocket) return; + let active = true; + const client = new PiWsClient({ + url: defaultWsUrl(), + token: getDeviceToken(), + handlers: { + onState: (state: WsConnectionState) => { + if (active) setWsState(state); + }, + onError: (error) => { + if ((error as { code?: string }).code !== "E_UNAUTHORIZED") return; + if (redirectingRef.current) return; + redirectingRef.current = true; + disconnect(); + clearPairMeta(); + void navigate({ href: `${CONNECT_PATH}?next=${encodeURIComponent(safeNext(href))}`, replace: true }); + }, + }, + }); + client.connect(); + return () => { + active = false; + client.close(); + }; + }, [disconnect, href, isConnect, navigate, ownsSocket, paired, setWsState]); + + const connectionLost = paired && !isConnect && (wsState === "reconnecting" || wsState === "closed"); + return ( -
+
+ {connectionLost ? ( +
+ + + + + {t(wsState === "closed" ? "shell.connectionLost" : "shell.reconnecting")} + + + {t("connect.reconnect")} + +
+ ) : null} +
{isConnect ? null : ( <> diff --git a/web/src/components/ui/dialog.tsx b/web/src/components/ui/dialog.tsx index 051612f..f4083c0 100644 --- a/web/src/components/ui/dialog.tsx +++ b/web/src/components/ui/dialog.tsx @@ -38,10 +38,17 @@ export function Modal({ return ( - - + {/* + * The content is a child of the backdrop: the backdrop is + * `position: fixed; z-index: 60`, so a sibling rendered after it + * still paints underneath and swallows every pointer event + * ("modal-backdrop intercepts pointer events"). Nesting keeps the + * flex centering and puts the panel above the scrim. + */} + +

{title} @@ -57,7 +64,8 @@ export function Modal({ ) : null} {children} {footer ?
{footer}
: null} - + + ); diff --git a/web/src/features/chat/attention.tsx b/web/src/features/chat/attention.tsx index 7af8db4..1510ed3 100644 --- a/web/src/features/chat/attention.tsx +++ b/web/src/features/chat/attention.tsx @@ -8,52 +8,59 @@ import { Modal } from "@/components/ui/dialog"; import { Progress } from "@/components/ui/progress"; import { toast } from "@/components/ui/toast"; import { cn } from "@/lib/utils"; +import { + cancelResponse, + confirmResponse, + diffAnswer, + selectResponse, + type AttentionResponse, +} from "./commands"; import { diffFilesFromPayload } from "./diff"; import { DiffView } from "./diff-view"; export interface AttentionDialogProps { session: SessionState; - onRespond: (item: AttentionItem, response: unknown) => void; + onRespond: (item: AttentionItem, response: AttentionResponse | string) => void; /** Fired when the request vanished because another client answered it. */ onRemoteResolved: (requestId: string) => void; } -function diffResponse(result: "Accepted" | "Rejected", path?: string): string { - return JSON.stringify({ result, ...(path ? { path } : {}) }); -} - /** * Blocking extension attention request. * - * One dialog per session: title/options/countdown, or the pre-execution diff - * review variant. A request resolved by another client disappears from - * `session.attention` (reducer) and we close immediately + toast. + * One dialog per session: title/options/countdown from the server (nothing is + * invented locally), or the pre-execution diff review variant. The dialog closes + * when the plugin resolves the request — our own answer + * (`pi2:attention_resolved` echoes the winner), another client's answer, or the + * timeout it advertises. */ export function AttentionDialog({ session, onRespond, onRemoteResolved }: AttentionDialogProps) { const { t } = useTranslation(); const [current, setCurrent] = useState(null); const [remaining, setRemaining] = useState(null); - const responded = useRef(false); - const dismissed = useRef(null); - const timedOut = useRef>(new Set()); + /** Answered here, waiting for the plugin to confirm. */ + const answered = useRef(false); + /** Timed out locally: the plugin cancels it too, so never show it again. */ + const settled = useRef>(new Set()); + /** The request currently on screen, to report a remote resolution once. */ + const shown = useRef(null); useEffect(() => { - const next = session.attention[0] ?? null; - if (next && dismissed.current === next.requestId) return; - if (next) { - if (!current || current.requestId !== next.requestId) { - responded.current = false; - setCurrent(next); - } + const next = session.attention.find((item) => !settled.current.has(item.requestId)) ?? null; + if (!next) { + // `pi2:attention_resolved` (or a cancelled request) removed it. + if (shown.current !== null && !answered.current) onRemoteResolved(shown.current); + shown.current = null; + answered.current = false; + setCurrent(null); return; } - if (current) { - if (!responded.current) onRemoteResolved(current.requestId); - responded.current = false; - dismissed.current = null; - setCurrent(null); + if (shown.current !== next.requestId) { + shown.current = next.requestId; + answered.current = false; } - }, [session.attention, current, onRemoteResolved]); + setCurrent(next); + }, [session.attention, onRemoteResolved]); useEffect(() => { const timeoutSec = current?.timeoutSec; @@ -66,13 +73,12 @@ export function AttentionDialog({ session, onRespond, onRemoteResolved }: Attent const tick = () => { const left = Math.max(0, Math.ceil((deadline - Date.now()) / 1_000)); setRemaining(left); - if (left <= 0 && !timedOut.current.has(item.requestId)) { - timedOut.current.add(item.requestId); - responded.current = true; - dismissed.current = item.requestId; - setCurrent(null); - toast.error(t("chat.attentionTimedOut")); - } + if (left > 0 || settled.current.has(item.requestId)) return; + settled.current.add(item.requestId); + shown.current = null; + answered.current = false; + setCurrent(null); + toast.error(t("chat.attentionTimedOut")); }; tick(); const timer = setInterval(tick, 500); @@ -82,27 +88,35 @@ export function AttentionDialog({ session, onRespond, onRemoteResolved }: Attent const files = useMemo(() => diffFilesFromPayload(current?.payload), [current]); const isDiff = current?.method === "diff" || files.length > 0; - function respond(response: unknown, message: string, kind: "success" | "error" | "info" = "success") { + /** Answer, optionally with a confirmation toast (diff decisions). */ + function respond(answer: AttentionResponse, message?: string, kind: "success" | "error" = "success") { if (!current) return; - responded.current = true; - onRespond(current, response); + answered.current = true; + onRespond(current, answer); + if (!message) return; if (kind === "error") toast.error(message); - else if (kind === "info") toast.info(message); else toast.success(message); } + // `confirm` has no server-side option list; the plugin expects + // `{confirmed}` and expresses a dismissal as `{cancelled}`. + const confirmMode = current?.method === "confirm" && !current.options?.length; const options = current?.options?.length ? current.options - : current?.method === "confirm" + : confirmMode ? [ - { id: "confirm", label: t("chat.allowOnce") }, - { id: "deny", label: t("chat.deny") }, + { id: "confirm", label: t("common.confirm") }, + { id: "cancel", label: t("common.cancel") }, ] - : [ - { id: "allow-once", label: t("chat.allowOnce") }, - { id: "always", label: t("chat.always") }, - { id: "deny", label: t("chat.deny") }, - ]; + : []; + + function choose(id: string) { + if (confirmMode) { + respond(id === "confirm" ? confirmResponse(true) : cancelResponse()); + return; + } + respond(selectResponse(id)); + } return ( respond( - diffResponse(decision === "accept" ? "Accepted" : "Rejected", path), + diffAnswer( + decision === "accept" ? "Accepted" : "Rejected", + path, + ), decision === "accept" ? t("chat.acceptedAll", { n: files.length }) : t("chat.rejected", { path: path ?? "" }), @@ -141,22 +158,21 @@ export function AttentionDialog({ session, onRespond, onRemoteResolved }: Attent ))} + {options.length ? null : ( + + )}

)} {current.timeoutSec ? ( diff --git a/web/src/features/chat/blocks.tsx b/web/src/features/chat/blocks.tsx index 3101032..7a4ff9e 100644 --- a/web/src/features/chat/blocks.tsx +++ b/web/src/features/chat/blocks.tsx @@ -296,7 +296,11 @@ export function EntryBlock({ entry, turnStart }: EntryBlockProps) { -1, ); return ( -
+
{entry.blocks.map((block, index) => { if (block.type === "text") { diff --git a/web/src/features/chat/commands.ts b/web/src/features/chat/commands.ts index a40f7fd..c2a7f57 100644 --- a/web/src/features/chat/commands.ts +++ b/web/src/features/chat/commands.ts @@ -6,6 +6,20 @@ export interface PromptImage { data: string; } +/** + * `prompt.send` mode. The plugin maps it to pi's RPC command + * (`follow_up` → queue, `steer` → interrupt the run); omit it for a plain + * `prompt`. + */ +export type PromptMode = "follow_up" | "steer"; + +/** + * `attention.respond` answer, forwarded verbatim to the plugin + * (`pi.attention.resolve`): `{value}` for select/input/editor, `{confirmed}` + * for confirm, `{cancelled}` for a dismissal. + */ +export type AttentionResponse = { value: unknown } | { confirmed: boolean } | { cancelled: true }; + export interface ChatCommand extends CommandRequest { method: string; } @@ -32,26 +46,30 @@ function command(method: string, sessionId: string | undefined, params?: Record< /** * Command payload builders for `POST /api/v1/cmd`. * - * Parameter names follow the daemon/plugin contract - * (`docs/protocol.md`, design `explore/web-server-round2-contract.md` §4). + * Parameter names follow the plugin handlers + * (`pi2.nvim-web/lua/pi/web/commands.lua`), which are the authority for every + * payload shape here. */ export const chatCommands = { - sendPrompt: (sessionId: string, text: string, images: PromptImage[] = []): ChatCommand => + /** `mode` omitted → a plain prompt; `follow_up` queues, `steer` interrupts. */ + sendPrompt: (sessionId: string, text: string, images: PromptImage[] = [], mode?: PromptMode): ChatCommand => command("prompt.send", sessionId, { text, - mode: "queue", + ...(mode ? { mode } : {}), ...(images.length ? { images } : {}), }), abort: (sessionId: string): ChatCommand => command("prompt.abort", sessionId, {}), - removeQueued: (sessionId: string, queueId: string): ChatCommand => command("queue.remove", sessionId, { queueId }), + /** Queue entries are addressed by pi's queue id (`queue[i].id`). */ + removeQueued: (sessionId: string, id: string): ChatCommand => command("queue.remove", sessionId, { id }), - setQueueSteer: (sessionId: string, queueId: string, steer: boolean): ChatCommand => - command("queue.setSteer", sessionId, { queueId, steer }), + /** Steering is a session-wide mode, not a per-message flag. */ + setQueueSteer: (sessionId: string, steer: boolean): ChatCommand => + command("queue.setSteer", sessionId, { mode: steer ? "all" : "one-at-a-time" }), setModel: (sessionId: string, model: ModelRef): ChatCommand => - command("session.setModel", sessionId, { provider: model.provider, id: model.id }), + command("session.setModel", sessionId, { model: { provider: model.provider, id: model.id } }), setThinking: (sessionId: string, level: ThinkingLevel): ChatCommand => command("session.setThinking", sessionId, { level }), @@ -62,9 +80,10 @@ export const chatCommands = { createSession: (workspaceId: string): ChatCommand => command("session.create", undefined, { workspaceId }), - respondAttention: (sessionId: string, requestIdValue: string, response: unknown): ChatCommand => + respondAttention: (sessionId: string, requestIdValue: string, response: AttentionResponse | string): ChatCommand => command("attention.respond", sessionId, { requestId: requestIdValue, response }), + /** One batch item per dispatch; the plugin's snake_case params are literal. */ dispatchSubagent: ( sessionId: string, input: { @@ -77,14 +96,16 @@ export const chatCommands = { }, ): ChatCommand => command("subagent.dispatch", sessionId, { - task: input.task, - ...(input.name ? { name: input.name } : {}), - ...(input.model ? { model: input.model } : {}), - ...(input.thinking ? { thinking: input.thinking } : {}), - ...(input.wait !== undefined ? { wait: input.wait } : {}), - ...(input.cancelSiblingsOnFail !== undefined - ? { cancelSiblingsOnFail: input.cancelSiblingsOnFail } - : {}), + items: [ + { + task: input.task, + ...(input.name ? { name: input.name } : {}), + ...(input.model ? { model: input.model } : {}), + ...(input.thinking ? { thinking_level: input.thinking } : {}), + }, + ], + wait: input.wait === true, + cancel_siblings_on_fail: input.cancelSiblingsOnFail === true, }), steerSubagent: (sessionId: string, target: string, message: string): ChatCommand => @@ -105,9 +126,32 @@ export async function runCommand(command: ChatCommand, signal?: AbortSignal): Pr return api.command(command, signal) as Promise; } -/** Response value for the diff-review attention variant (matches the plugin's JSON payload). */ -export function diffResponse(result: "Accepted" | "Rejected"): string { - return JSON.stringify({ result }); +/** `select` / `input` / `editor` answer: the chosen option id (or typed value). */ +export function selectResponse(value: string): AttentionResponse { + return { value }; +} + +/** `confirm` answer: an explicit yes/no. */ +export function confirmResponse(confirmed: boolean): AttentionResponse { + return { confirmed }; +} + +/** Dismiss/deny without choosing anything (the plugin's `cancelled` path). */ +export function cancelResponse(): AttentionResponse { + return { cancelled: true }; +} + +/** + * Diff review answer: `pi.ui.diff` decodes the **value** as JSON + * `{result, path?}`, so the caller wraps it in `{value}` before sending. + */ +export function diffResponse(result: "Accepted" | "Rejected", path?: string): string { + return JSON.stringify({ result, ...(path ? { path } : {}) }); +} + +/** `attention.respond` answer for an accept/reject of the diff review. */ +export function diffAnswer(result: "Accepted" | "Rejected", path?: string): AttentionResponse { + return { value: diffResponse(result, path) }; } export function promptImage(file: File): Promise { diff --git a/web/src/features/chat/composer.tsx b/web/src/features/chat/composer.tsx index 3024afa..3a6cd64 100644 --- a/web/src/features/chat/composer.tsx +++ b/web/src/features/chat/composer.tsx @@ -8,7 +8,7 @@ import { Chip } from "@/components/ui/chip"; import { Modal } from "@/components/ui/dialog"; import { toast } from "@/components/ui/toast"; import { cn } from "@/lib/utils"; -import { promptImage, type PromptImage } from "./commands"; +import { promptImage, type PromptImage, type PromptMode } from "./commands"; import type { ModelGroup } from "./data"; import { withCurrentModel } from "./data"; import { THINKING_LEVELS } from "./format"; @@ -20,10 +20,12 @@ export interface ComposerProps { connected: boolean; paired?: boolean; sending?: { text: string } | null; - onSend: (text: string, images: PromptImage[]) => void; + /** `mode` is `follow_up` when the run is busy (queued) and `steer` for an interrupt. */ + onSend: (text: string, images: PromptImage[], mode?: PromptMode) => void; onAbort: () => void; onRemoveQueue: (id: string) => void; - onSetSteer: (id: string, steer: boolean) => void; + /** Steering is a session-wide mode, not a per-message flag. */ + onSetSteer: (steer: boolean) => void; onSetModel: (model: ModelRef) => void; onSetThinking: (level: ThinkingLevel) => void; disabled?: boolean; @@ -80,13 +82,14 @@ export function Composer({ textareaRef.current?.focus({ preventScroll: true }); }, [enabled]); - function submit() { + function submit(mode?: PromptMode) { const trimmed = text.trim(); if (!trimmed || !enabled) return; const images = attachments.map(({ mimeType, data }) => ({ mimeType, data })); setText(""); setAttachments([]); - onSend(trimmed, images); + // A busy session queues the message as a follow-up; idle sends a plain prompt. + onSend(trimmed, images, mode ?? (busy ? "follow_up" : undefined)); } async function addFiles(files: FileList | File[] | null) { @@ -136,7 +139,7 @@ export function Composer({ className="q-steer" checked={item.steer} aria-label={t("chat.steer")} - onChange={(event) => onSetSteer(item.id, event.target.checked)} + onChange={(event) => onSetSteer(event.target.checked)} /> {t("chat.steer")} @@ -185,6 +188,7 @@ export function Composer({ value={text} placeholder={t("chat.composerPlaceholder")} aria-label={t("chat.composerAria")} + data-testid="composer-input" disabled={!enabled} onChange={(event) => setText(event.target.value)} onKeyDown={(event) => { @@ -207,6 +211,7 @@ export function Composer({ onSetThinking(event.target.value as ThinkingLevel)} @@ -246,28 +252,42 @@ export function Composer({
{busy ? ( - - ) : ( - - )} + <> + + + + ) : null} +
{hint ? ( @@ -312,7 +332,6 @@ export function Composer({ >
{t("chat.dropHint")}
-
{t("chat.dropNote")}
) : null} -
{t("chat.attachNote")}
diff --git a/web/src/features/chat/data.ts b/web/src/features/chat/data.ts index 99e2661..2d5c306 100644 --- a/web/src/features/chat/data.ts +++ b/web/src/features/chat/data.ts @@ -16,6 +16,7 @@ import { normalizeSnapshotState, } from "./session-state"; import { setSessionMeta } from "./history"; +import { migrateSessionId } from "./migration"; import { useChatStore } from "./store"; export const EMPTY_SESSIONS: SessionState[] = []; @@ -129,8 +130,26 @@ export function useChatWorkspaces(enabled: boolean): { workspaces: WorkspaceInfo return { workspaces, loading: query.isLoading, error: query.error }; } +/** + * One workspace's session list plus the query state the page must gate on. + * + * `loaded` is the "the list is authoritative" flag: an unknown deep link may + * only be reported as missing once the first REST/WS answer has landed, so the + * page does not flash a not-found state while the list is still in flight. + */ +export interface ChatSessions { + /** Sessions of the workspace, merged into the shared store (live state wins). */ + sessions: SessionState[]; + /** False until the session list has answered once (REST or live store). */ + loaded: boolean; + /** True while a (Re)fetch of the REST list is in flight. */ + fetching: boolean; + /** Refetch the REST session list — the unknown-session Retry button. */ + refetch: () => void; +} + /** Sessions of one workspace, merged into the shared store (live state wins). */ -export function useChatSessions(workspaceId: string | undefined, enabled: boolean): SessionState[] { +export function useChatSessions(workspaceId: string | undefined, enabled: boolean): ChatSessions { const query = useQuery({ queryKey: ["chat-sessions", workspaceId], queryFn: ({ signal }) => @@ -158,7 +177,20 @@ export function useChatSessions(workspaceId: string | undefined, enabled: boolea current.setSessions(workspaceId, next); }, [workspaceId, query.data]); - return useSessionsStore((state) => (workspaceId ? (state.byWorkspace[workspaceId] ?? EMPTY_SESSIONS) : EMPTY_SESSIONS)); + const sessions = useSessionsStore((state) => + workspaceId ? (state.byWorkspace[workspaceId] ?? EMPTY_SESSIONS) : EMPTY_SESSIONS, + ); + + return { + sessions, + // A cached row (WS snapshot, another page) already proves the list is + // known even when this query has not settled yet. + loaded: query.isFetched || sessions.length > 0, + fetching: query.isFetching, + refetch: () => { + void query.refetch(); + }, + }; } /** Model list for the composer and dispatch modal. */ @@ -174,6 +206,24 @@ export function useChatModels(workspaceId: string | undefined, enabled: boolean) return useMemo(() => normalizeModels(query.data), [query.data]); } +/** + * `pi2:session` doubles as the id-migration announcement: it is emitted on the + * **old** id while `event.session.sessionId` carries the new one + * (`pi2.nvim-web` `Instance:_migrate_session`). + */ +export function sessionMigration( + sessionId: string, + event: Record, +): { from: string; to: string } | undefined { + if (event.type !== "pi2:session") return undefined; + const session = rec(event.session); + const to = str(session?.sessionId); + if (!to || to === sessionId) return undefined; + const previous = str(session?.previousSessionId) ?? str(event.previousSessionId); + if (previous && previous !== sessionId) return undefined; + return { from: sessionId, to }; +} + /** * Subscribe to the workspace's sessions and reduce `snapshot` / `event` frames * into the shared sessions store. The canonical reducer is imported from @@ -206,7 +256,15 @@ export function useChatSocket(workspaceId: string | undefined, sessionIds: strin const payload = rec(message.payload); const event = rec(payload?.event) ?? payload; if (!event || typeof event.type !== "string") return; - const sessionId = message.sessionId; + const migration = sessionMigration(message.sessionId, event); + const sessionId = migration?.to ?? message.sessionId; + if (migration) { + // Move the render cache to the real id, then move the + // subscription: the daemon and plugin track the old id. + migrateSessionId(migration.from, migration.to, workspaceId); + client.unsubscribe(migration.from); + client.subscribe(migration.to); + } const store = useSessionsStore.getState(); const current = store.getSession(sessionId) ?? emptySessionState({ sessionId, workspaceId }); const next = applySessionEvent(current, event as unknown as SessionEvent); @@ -215,9 +273,9 @@ export function useChatSocket(workspaceId: string | undefined, sessionIds: strin onResyncRequired: (frame) => { const sessionId = str(frame.sessionId); if (!sessionId) return; + // `PiWsClient` already dropped the cached `(epoch, seq)`; the + // history hook refetches the REST page for this generation. useChatStore.getState().bumpResync(sessionId); - // Drop the seq cache and ask for a fresh snapshot; the history - // hook refetches the REST page for the same session. client.unsubscribe(sessionId); client.subscribe(sessionId); }, @@ -242,18 +300,39 @@ export function useChatSocket(workspaceId: string | undefined, sessionIds: strin }, [idsKey, workspaceId]); } -/** The selected session, falling back to the first session of the workspace. */ -export function useActiveSession( +export interface SessionLookup { + /** The routed session; `undefined` for `/chat` with no sessions at all. */ + session: SessionState | undefined; + /** + * True only once the list has loaded and the route id is still absent. The + * page renders its not-found state then, never another session's entries. + */ + missing: boolean; +} + +/** + * Resolve the session the route addresses. + * + * A non-empty `sessionId` that the loaded list does not contain resolves to + * `undefined` — falling back to `sessions[0]` would silently show a different + * session for an unknown deep link. The first-session fallback stays for the + * `/chat` index (no id), which means "the workspace's most recent session". + * + * @param sessionId Route session id (`undefined` on `/chat`). + * @param sessions Sessions of the active workspace. + * @param loaded Whether `sessions` has answered at least once. + */ +export function useSessionLookup( sessionId: string | null | undefined, sessions: SessionState[], -): SessionState | undefined { + loaded: boolean, +): SessionLookup { return useMemo(() => { - if (sessionId) { - const match = sessions.find((session) => session.sessionId === sessionId); - if (match) return match; - } - return sessions[0]; - }, [sessions, sessionId]); + if (!sessionId) return { session: sessions[0], missing: false }; + const match = sessions.find((session) => session.sessionId === sessionId); + if (match) return { session: match, missing: false }; + return { session: undefined, missing: loaded }; + }, [sessions, sessionId, loaded]); } export function mergeSessionSummaries(existing: SessionState | undefined, raw: unknown, workspaceId: string): SessionState { diff --git a/web/src/features/chat/diff-view.tsx b/web/src/features/chat/diff-view.tsx index 3805623..c62e0a1 100644 --- a/web/src/features/chat/diff-view.tsx +++ b/web/src/features/chat/diff-view.tsx @@ -85,6 +85,8 @@ export function DiffView({ files, onDecision, className }: DiffViewProps) { - diff --git a/web/src/features/chat/history.ts b/web/src/features/chat/history.ts index 46b51de..eda0b01 100644 --- a/web/src/features/chat/history.ts +++ b/web/src/features/chat/history.ts @@ -26,6 +26,14 @@ export function setSessionMeta( sessionMeta.set(sessionId, { ...sessionMeta.get(sessionId), ...meta }); } +/** Carry the paging metadata over to the migrated session id. */ +export function remapSessionMeta(from: string, to: string): void { + if (!from || !to || from === to) return; + const meta = sessionMeta.get(from); + sessionMeta.delete(from); + if (meta) sessionMeta.set(to, { ...sessionMeta.get(to), ...meta }); +} + /** `GET /api/v1/sessions/:sid/entries?before=&limit=&workspaceId=&sessionFile=` → raw pi entries + cursor. */ export async function fetchEntriesPage( sessionId: string, diff --git a/web/src/features/chat/message-stream.tsx b/web/src/features/chat/message-stream.tsx index 4f366aa..e7e0511 100644 --- a/web/src/features/chat/message-stream.tsx +++ b/web/src/features/chat/message-stream.tsx @@ -174,7 +174,12 @@ export function MessageStream({ {t("chat.loadingOlder")} ) : hasMore ? ( - ) : null} diff --git a/web/src/features/chat/migration.ts b/web/src/features/chat/migration.ts new file mode 100644 index 0000000..330b0d3 --- /dev/null +++ b/web/src/features/chat/migration.ts @@ -0,0 +1,88 @@ +/** + * Session-id migration (`tmp-N` → the backend id). + * + * `session.create` answers with a provisional id, so the URL right after + * "New session" is `/chat/tmp-1`. When the pi process starts it assigns the real + * id and the plugin announces it on the **old** id: + * + * pi2:session { session: { sessionId: "", previousSessionId: "tmp-1" } } + * + * Everything the browser keyed by the old id (session row, history page, the + * optimistic `sending` chip, REST paging metadata and the URL) has to move to + * the new id, and the socket has to resubscribe — otherwise the page loses the + * in-flight prompt and streams into a session nobody renders. + */ + +import { useSessionsStore } from "@/stores/sessions"; + +import { remapSessionMeta } from "./history"; +import { useChatStore } from "./store"; + +export interface SessionMigration { + from: string; + to: string; + workspaceId?: string; + /** `/chat/?workspace=` — the URL that should replace the old one. */ + path: string; + /** Fired after the stores were re-keyed. */ + ts: number; +} + +type MigrationListener = (migration: SessionMigration) => void; + +const listeners = new Set(); + +/** Subscribe to session-id migrations (returns the unsubscribe function). */ +export function onSessionMigration(listener: MigrationListener): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +/** `/chat/` plus the workspace query, encoded for the router. */ +export function chatSessionPath(sessionId: string, workspaceId?: string): string { + const encoded = encodeURIComponent(sessionId); + return workspaceId ? `/chat/${encoded}?workspace=${encodeURIComponent(workspaceId)}` : `/chat/${encoded}`; +} + +/** + * Replace the address bar in place (no navigation, no history entry, keeps the + * router's `history.state`). Returns `true` when the current route addressed + * the old session id, i.e. when the caller also has to sync the router. + */ +export function replaceChatUrl(from: string, to: string, workspaceId?: string): boolean { + if (typeof window === "undefined" || !window.history?.replaceState) return false; + const { pathname, search } = window.location; + if (pathname !== `/chat/${from}` && pathname !== `/chat/${encodeURIComponent(from)}`) return false; + const target = chatSessionPath(to, workspaceId) + (workspaceId ? "" : search); + if (pathname + search !== target) { + // `history.state` is the router's location state; dropping it would break + // the next navigation, so pass it through untouched. + window.history.replaceState(window.history.state, "", target); + } + return true; +} + +/** + * Move every render-cache slice from `from` to `to` and notify the page so it + * can fix the URL and resubscribe. Idempotent: a repeat for the same pair is a + * no-op. + */ +export function migrateSessionId(from: string, to: string, workspaceId?: string): SessionMigration | null { + if (!from || !to || from === to) return null; + + useSessionsStore.getState().renameSessionId(from, to); + useChatStore.getState().migrateSession(from, to); + remapSessionMeta(from, to); + + const migration: SessionMigration = { + from, + to, + ...(workspaceId ? { workspaceId } : {}), + path: chatSessionPath(to, workspaceId), + ts: Date.now(), + }; + for (const listener of listeners) listener(migration); + return migration; +} diff --git a/web/src/features/chat/modals.tsx b/web/src/features/chat/modals.tsx index e4dc679..5f2b47f 100644 --- a/web/src/features/chat/modals.tsx +++ b/web/src/features/chat/modals.tsx @@ -1,4 +1,4 @@ -import type { Entry, ModelRef, SessionState, Subagent, TaskItem, ThinkingLevel } from "@protocol/types"; +import type { ModelRef, SessionState, Subagent, TaskItem, ThinkingLevel } from "@protocol/types"; import { useEffect, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; @@ -9,14 +9,32 @@ import { Modal } from "@/components/ui/dialog"; import { KV } from "@/components/ui/kv"; import { Spinner } from "@/components/ui/spinner"; import { toast } from "@/components/ui/toast"; -import { projectEntries } from "@/lib/entry-projection"; -import { EntryBlock } from "./blocks"; +import { ApiError, errorI18nKey } from "@/lib/api"; +import { cn } from "@/lib/utils"; import { chatCommands, runCommand } from "./commands"; import type { ModelGroup } from "./data"; import { withCurrentModel } from "./data"; import { formatDuration, THINKING_LEVELS } from "./format"; import { flattenSubagents } from "./session-state"; +function rec(value: unknown): Record | undefined { + return value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : undefined; +} + +function str(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +function num(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +/** Human-readable text for a failed command (`ApiError.code` → `errors.*`). */ +function commandErrorText(error: unknown, translate: (key: string) => string): string { + if (error instanceof ApiError) return translate(errorI18nKey(error.code)); + return error instanceof Error ? error.message : String(error); +} + /* ------------------------------------------------------------------ */ /* dispatch */ /* ------------------------------------------------------------------ */ @@ -197,21 +215,36 @@ const SUB_DOT: Record = { dormant: "dot--exited", }; -function statusTail(subagent: Subagent, t: (key: string) => string): Entry[] { - const ts = subagent.lastActiveAt ?? subagent.createdAt ?? Date.now(); - if (subagent.status === "failed") { - return [{ id: `preview-${subagent.id}-err`, role: "notice", ts, done: true, blocks: [{ type: "error", text: t("chat.previewFailed") }] }]; - } - if (subagent.status === "interrupted") { - return [{ id: `preview-${subagent.id}-int`, role: "assistant", ts, done: true, blocks: [{ type: "text", text: t("chat.previewInterrupted") }] }]; - } - if (subagent.status === "completed") { - return [{ id: `preview-${subagent.id}-done`, role: "assistant", ts, done: true, blocks: [{ type: "text", text: t("chat.previewCompleted") }] }]; - } - if (subagent.status === "dormant") { - return [{ id: `preview-${subagent.id}-dorm`, role: "assistant", ts, done: true, blocks: [{ type: "text", text: t("chat.previewDormant") }] }]; - } - return []; +/** + * One projected line of a sub-session file. + * + * `subagent.read` returns `{sessionFile, lines}` where each line is the plugin's + * text projection of a raw pi entry (`"[12] user: please fix it"`, see + * `pi.subsessions.read.project_entry`). + */ +export interface SubagentEntry { + id: string; + role: string; + text: string; +} + +const SUB_ROLES = new Set(["user", "assistant", "system", "notice", "toolResult", "toolUse"]); + +/** Parse `[] : ` back into role + text rows. */ +export function parseSubagentLines(lines: unknown): SubagentEntry[] { + if (!Array.isArray(lines)) return []; + const out: SubagentEntry[] = []; + lines.forEach((value, position) => { + const line = typeof value === "string" ? value : JSON.stringify(value); + if (!line) return; + const match = /^\[(\d+)\]\s*([A-Za-z_]+):\s?([\s\S]*)$/.exec(line); + if (match && SUB_ROLES.has(match[2] ?? "")) { + out.push({ id: `sub-${match[1]}`, role: match[2] ?? "system", text: match[3] ?? "" }); + return; + } + out.push({ id: `sub-line-${position}`, role: "system", text: line }); + }); + return out; } export interface SubagentModalProps { @@ -226,48 +259,40 @@ export interface SubagentModalProps { export function SubagentModal({ open, session, subagent, onClose, onBack, onSteer }: SubagentModalProps) { const { t } = useTranslation(); const [steer, setSteer] = useState(""); - const [tail, setTail] = useState(null); + const [feed, setFeed] = useState([]); + const [sessionFile, setSessionFile] = useState(null); + const [error, setError] = useState(null); const [loading, setLoading] = useState(false); const badge = subagent ? (SUB_BADGE[subagent.status] ?? { tone: "default" as const, key: subagent.status }) : null; useEffect(() => { if (!open || !subagent) return; - setTail(null); + let cancelled = false; + setFeed([]); + setSessionFile(null); + setError(null); setLoading(true); const target = subagent.name ?? subagent.id; void runCommand(chatCommands.readSubagent(session.sessionId, target)) .then((response) => { - const raw = response as Record; - const entries = Array.isArray(raw.entries) - ? raw.entries - : Array.isArray(raw.messages) - ? raw.messages - : []; - if (entries.length) setTail(projectEntries(entries)); - else setTail(statusTail(subagent, t)); + if (cancelled) return; + const raw = rec(response) ?? {}; + setSessionFile(str(raw.sessionFile) ?? null); + setFeed(parseSubagentLines(raw.lines ?? raw.entries)); }) - .catch(() => { - if (subagent) setTail(statusTail(subagent, t)); + .catch((cause: unknown) => { + if (cancelled) return; + setError(commandErrorText(cause, t)); }) - .finally(() => setLoading(false)); + .finally(() => { + if (!cancelled) setLoading(false); + }); + return () => { + cancelled = true; + }; }, [open, session.sessionId, subagent, t]); - const feed = useMemo(() => { - if (!subagent) return []; - if (tail && tail.length) return tail; - return [ - { - id: `preview-${subagent.id}-task`, - role: "user" as const, - ts: subagent.createdAt ?? Date.now(), - done: true, - blocks: [{ type: "text" as const, text: subagent.task ?? t("chat.task") }], - }, - ...statusTail(subagent, t), - ]; - }, [subagent, t, tail]); - - const children = subagent ? flattenSubagents(subagent.children) : []; + const children = useMemo(() => (subagent ? flattenSubagents(subagent.children) : []), [subagent]); function sendSteer() { if (!steer.trim()) { @@ -340,10 +365,35 @@ export function SubagentModal({ open, session, subagent, onClose, onBack, onStee
{t("chat.loading")}
+ ) : error ? ( +
+
+ {t("chat.error")} +
+
{error}
+
+ ) : feed.length ? ( + feed.map((entry) => ( +
+
+ + {entry.role} + + {entry.id} +
+
{entry.text}
+
+ )) ) : ( - feed.map((entry) => ) +
{t("chat.noOutput")}
)} + {sessionFile ?
{sessionFile}
: null}
{t("chat.previewNote")}
(null); + const [result, setResult] = useState(null); + const [error, setError] = useState(null); const [loading, setLoading] = useState(false); useEffect(() => { if (!open || !task) return; - setOutput(null); + let cancelled = false; + setResult(null); + setError(null); setLoading(true); void runCommand(chatCommands.taskOutput(session.sessionId, task.id)) .then((response) => { - const record = response as Record; - const text = - typeof record.output === "string" - ? record.output - : typeof record.text === "string" - ? record.text - : typeof record.data === "string" - ? record.data - : null; - setOutput(text); + if (!cancelled) setResult(normalizeTaskOutput(response)); }) - .catch(() => setOutput(null)) - .finally(() => setLoading(false)); - }, [open, session.sessionId, task]); + .catch((cause: unknown) => { + // A real failure (e.g. E_UNSUPPORTED on an older plugin) is shown + // as-is; it must not look like an empty output file. + if (!cancelled) setError(commandErrorText(cause, t)); + }) + .finally(() => { + if (!cancelled) setLoading(false); + }); + return () => { + cancelled = true; + }; + }, [open, session.sessionId, task, t]); if (!task) return null; - const running = task.status === "running"; - const duration = running ? Date.now() - task.startTime : (task.durationMs ?? 0); + const status = result?.status ?? task.status; + const running = status === "running"; + const duration = result?.durationMs ?? (running ? Date.now() - task.startTime : (task.durationMs ?? 0)); + const exitCode = result?.exitCode !== undefined ? result.exitCode : (task.exitCode ?? null); + const outputFile = result?.outputFile ?? task.outputFile; return (
-
{loading ? t("chat.loading") : (output ?? t("chat.noOutput"))}
- {task.outputFile ?
{task.outputFile}
: null} +
+                    {loading
+                        ? t("chat.loading")
+                        : error
+                          ? t("chat.commandFailed", { error })
+                          : (result?.output ?? t("chat.noOutput"))}
+                
+ {outputFile ?
{outputFile}
: null}
- - {fakePid(task)} - - - {t(`state.${task.status}`)} + + {t(`state.${status}`)} {formatDuration(duration)} - {task.exitCode == null ? "—" : task.exitCode} + {exitCode == null ? "—" : exitCode} {task.command} diff --git a/web/src/features/chat/session-state.ts b/web/src/features/chat/session-state.ts index 1094b57..ae01c61 100644 --- a/web/src/features/chat/session-state.ts +++ b/web/src/features/chat/session-state.ts @@ -181,8 +181,39 @@ function applyEntryAppended(state: SessionState, rawEntry: unknown): void { state.entries = [...state.entries, projected]; } +/** + * The assistant entry streaming `message_update` events apply to: the reducer + * tracks it as `ctx.assistantEntryId`, which `reducerForState` rebuilds as the + * newest assistant entry of the current state. + */ +function streamingAssistantEntry(state: SessionState): Entry | undefined { + for (let index = state.entries.length - 1; index >= 0; index -= 1) { + const entry = state.entries[index]; + if (entry?.role === "assistant") return entry; + } + return undefined; +} + +/** + * A streaming update for an assistant message that is already finalized. + * + * The bridge coalesces `text_delta`/`thinking_delta` frames (protocol §2) and + * assigns their `seq` when the frame is finally written, so a coalesced delta + * can reach the browser *after* the `message_end` (or the snapshot) that owns + * the final text. Applying it appends the tail of the message a second time + * (`PONG` → `PONGONG`), and — because the resulting text no longer matches the + * authoritative session entry — the history page then renders as a second, + * duplicate assistant message. `message_end`/snapshots carry the full content, + * so a delta for a `done` entry is always stale. + */ +function isStaleStreamUpdate(state: SessionState, event: SessionEvent): boolean { + if (event.type !== "message_update") return false; + return streamingAssistantEntry(state)?.done === true; +} + /** Apply one live session event to an immutable copy of the render state. */ export function applySessionEvent(state: SessionState, event: SessionEvent): SessionState { + if (isStaleStreamUpdate(state, event)) return state; const next = cloneSessionState(state); const normalized: SessionEvent = { ...event, ts: typeof event.ts === "number" ? event.ts : Date.now() }; diff --git a/web/src/features/chat/session-tree.tsx b/web/src/features/chat/session-tree.tsx index 0255d51..4c7fd42 100644 --- a/web/src/features/chat/session-tree.tsx +++ b/web/src/features/chat/session-tree.tsx @@ -99,6 +99,7 @@ function SubagentRow({ role="button" tabIndex={0} aria-label={name} + data-subagent-id={subagent.id} onClick={() => onOpenSubagent?.(session, subagent)} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { @@ -201,6 +202,7 @@ function SessionRow({ tabIndex={0} aria-label={name} aria-current={selected ? "true" : undefined} + data-session-id={session.sessionId} onClick={() => onSelectSession(session.sessionId)} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { diff --git a/web/src/features/chat/side-panel.tsx b/web/src/features/chat/side-panel.tsx index abe5688..cb23b92 100644 --- a/web/src/features/chat/side-panel.tsx +++ b/web/src/features/chat/side-panel.tsx @@ -75,6 +75,7 @@ export function SidePanel({ role="tab" aria-selected={tab === item.id} className={cn("tab", tab === item.id && "active")} + data-testid={`panel-tab-${item.id}`} onClick={() => onTab(item.id)} > {item.label} @@ -139,8 +140,7 @@ export function SidePanel({ ? "dot--attention" : "dot--exited", )} - /> - + /> {subagent.name ?? subagent.id} @@ -203,6 +203,7 @@ export function SidePanel({ className="task-item" role="button" tabIndex={0} + data-task-id={task.id} onClick={() => onOpenTask(task)} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { diff --git a/web/src/features/chat/store.ts b/web/src/features/chat/store.ts index f691b2f..d506338 100644 --- a/web/src/features/chat/store.ts +++ b/web/src/features/chat/store.ts @@ -83,6 +83,12 @@ export interface ChatStore { historyError: (sessionId: string, error: string) => void; bumpResync: (sessionId: string) => void; clearHistory: (sessionId: string) => void; + /** + * Re-key every per-session slice after the plugin migrates `tmp-N` → the + * real id: history (so an in-flight prompt and its page are not lost), + * the optimistic `sending` chip and the preview target. + */ + migrateSession: (from: string, to: string) => void; } function updateHistory( @@ -187,4 +193,21 @@ export const useChatStore = create((set) => ({ delete history[sessionId]; return { history }; }), + migrateSession: (from, to) => + set((state) => { + if (!from || !to || from === to) return state; + const history = { ...state.history }; + const moved = history[from]; + delete history[from]; + if (moved) { + const existing = history[to]; + // Keep whichever side already rendered more of the transcript. + history[to] = !existing || moved.entries.length >= existing.entries.length ? moved : existing; + } + return { + history, + sending: state.sending?.sessionId === from ? { ...state.sending, sessionId: to } : state.sending, + preview: state.preview?.sessionId === from ? { ...state.preview, sessionId: to } : state.preview, + }; + }), })); diff --git a/web/src/features/connect/manual-form.tsx b/web/src/features/connect/manual-form.tsx index c564225..fac0a7b 100644 --- a/web/src/features/connect/manual-form.tsx +++ b/web/src/features/connect/manual-form.tsx @@ -7,7 +7,7 @@ import { Field, Input } from "@/components/ui/input"; import { toast } from "@/components/ui/toast"; import { ApiError, errorI18nKey } from "@/lib/api"; -import { parseEndpoint } from "./pairing"; +import { PAIR_CODE_LENGTH, isPairCode, normalizePairCode, parseEndpoint } from "./pairing"; export interface ManualConnectInput { endpoint: string; @@ -19,22 +19,27 @@ export interface ManualConnectFormProps { onConnect: (input: ManualConnectInput) => Promise; hostInputRef: RefObject; defaultDeviceName: string; + /** Prefill from `/connect?code=…` or the `/pair/$code` redirect. */ + initialCode?: string; } -function errorMessage(error: unknown, fallback: string): string { - if (error instanceof ApiError) return errorI18nKey(error.code); - return fallback; +/** Wrong/expired codes come back as 401 `E_UNAUTHORIZED`; the code rail is the useful message. */ +export function pairErrorMessage(error: unknown): string { + if (error instanceof ApiError) { + if (error.code === "E_UNAUTHORIZED" || error.status === 401) return "connect.pairCodeRejected"; + return errorI18nKey(error.code); + } + return "connect.pairFailed"; } -/** Inline manual pairing form: host/port, token-or-code, optional device name. */ -export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName }: ManualConnectFormProps) { +/** Inline manual pairing form: host/port, 8-character pairing code, optional device name. */ +export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName, initialCode }: ManualConnectFormProps) { const { t } = useTranslation(); const id = useId(); const [host, setHost] = useState(""); const [port, setPort] = useState("4321"); - const [code, setCode] = useState(""); + const [code, setCode] = useState(() => normalizePairCode(initialCode ?? "")); const [deviceName, setDeviceName] = useState(""); - const [showCode, setShowCode] = useState(false); const [hostError, setHostError] = useState(null); const [portError, setPortError] = useState(null); const [codeError, setCodeError] = useState(null); @@ -66,8 +71,14 @@ export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName } toast.error(message); return; } - if (!code.trim()) { - setCodeError(t("connect.tokenRequired")); + + const normalized = normalizePairCode(code); + if (!normalized) { + setCodeError(t("connect.pairCodeRequired")); + return; + } + if (!isPairCode(normalized)) { + setCodeError(t("connect.pairCodeInvalid")); return; } @@ -76,11 +87,11 @@ export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName } try { await onConnect({ endpoint: parsed.endpoint, - code: code.trim(), + code: normalized, deviceName: deviceName.trim() || defaultDeviceName, }); } catch (error) { - const message = t(errorMessage(error, "connect.failed")); + const message = t(pairErrorMessage(error)); setFormError(message); toast.error(message); } finally { @@ -103,6 +114,7 @@ export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName }
- -
- { - setCode(event.target.value); - setCodeError(null); - }} - /> - -
+ + { + setCode(normalizePairCode(event.target.value).slice(0, PAIR_CODE_LENGTH)); + setCodeError(null); + }} + /> - diff --git a/web/src/features/connect/pairing.ts b/web/src/features/connect/pairing.ts index ac3475b..ab0201d 100644 --- a/web/src/features/connect/pairing.ts +++ b/web/src/features/connect/pairing.ts @@ -1,8 +1,18 @@ import { ApiError, apiRequest, type InfoResponse } from "@/lib/api"; +import { NEXT_FALLBACK, safeNext } from "@/lib/routing"; export const PAIR_META_KEY = "pi2-pair-meta"; export const PAIR_SCOPES = ["read", "steer", "apply"] as const; +/** Public redeem endpoint: no bearer token required (docs/protocol.md §3.2). */ +export const PAIR_REDEEM_PATH = "/api/v1/pair"; +/** The daemon mints 8-character uppercase alphanumeric pairing codes. */ +export const PAIR_CODE_LENGTH = 8; +export const PAIR_CODE_PATTERN = /^[A-Z0-9]{8}$/; +export const DEFAULT_PAIR_PORT = 4321; +/** Scope assumed when a paired device did not report any (older daemons). */ +export const DEFAULT_DEVICE_SCOPES = ["read"] as const; + export type DeviceKind = "phone" | "laptop" | "tablet"; export interface PairMeta { @@ -25,6 +35,8 @@ export interface RedeemResult { token: string; scopes: string[]; deviceId?: string; + deviceName?: string; + kind?: DeviceKind; server?: PairMeta["server"]; raw: unknown; } @@ -51,6 +63,22 @@ function stringList(value: unknown): string[] { return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : []; } +/** + * Uppercase and drop everything that is not `[A-Z0-9]` — pairing codes are + * printed in small groups (`ABCD-1234`) but the daemon only accepts 8 chars. + */ +export function normalizePairCode(value: string | null | undefined): string { + return String(value ?? "") + .replace(/[^a-z0-9]/gi, "") + .toUpperCase() + .slice(0, PAIR_CODE_LENGTH + 8); +} + +/** True when the (normalized) value is a well-formed pairing code. */ +export function isPairCode(value: string | null | undefined): boolean { + return PAIR_CODE_PATTERN.test(normalizePairCode(value)); +} + /** * Accepts `host`, `host:port` and `http(s)://host[:port][/path]`. * A non-http scheme (e.g. a pi2:// pairing link pasted into the host field) @@ -104,68 +132,104 @@ function endpointFrom(value: string | null | undefined): ParsedEndpoint | null { } } +function browserOrigin(): string | null { + if (typeof window === "undefined") return null; + return window.location?.origin ?? null; +} + +function pairTarget(target: ParsedEndpoint, code: string, name?: string | null): PairTarget { + return { + endpoint: target.endpoint, + code, + name: name?.trim() || target.hostname, + hostname: target.hostname, + port: target.port, + }; +} + +/** First non-empty pairing code among the query/hash/path candidates. */ +function extractPairCode(url: URL): string { + const hash = new URLSearchParams(url.hash.replace(/^#/, "")); + const pathCode = /^\/pair\/([^/?#]+)\/?$/i.exec(url.pathname)?.[1]; + const raw = + hash.get("pair") ?? + hash.get("code") ?? + url.searchParams.get("pair") ?? + url.searchParams.get("code") ?? + pathCode; + return normalizePairCode(raw ?? ""); +} + +/** `pi2://pair?host=…&port=…&code=…` (design prototype / QR deep link). */ +function parsePi2PairLink(text: string, fallbackEndpoint?: string | null): PairTarget | null { + let url: URL; + try { + url = new URL(text); + } catch { + return null; + } + if (url.protocol !== "pi2:") return null; + + const params = url.searchParams; + const hash = new URLSearchParams(url.hash.replace(/^#/, "")); + const pathCode = /^\/+([^/]+)$/.exec(url.pathname)?.[1]; + const code = normalizePairCode( + params.get("code") ?? params.get("token") ?? hash.get("code") ?? hash.get("pair") ?? pathCode ?? "", + ); + if (!code) return null; + + const hostParam = firstString(params.get("host"), params.get("hostname"), params.get("endpoint")); + const proto = firstString(params.get("proto"), params.get("protocol"))?.toLowerCase(); + const portParam = firstString(params.get("port")) ?? String(DEFAULT_PAIR_PORT); + + let target: ParsedEndpoint | null = null; + if (hostParam) { + const hostText = + proto === "https" && !/^https?:\/\//i.test(hostParam) ? `https://${hostParam}` : hostParam; + const parsed = parseEndpoint(hostText, portParam); + target = "error" in parsed ? null : parsed; + } + // A pi2:// link without a host only makes sense against a known endpoint + // (the scan dialog passes the stored one); never guess from the browser origin. + target ??= endpointFrom(fallbackEndpoint); + if (!target) return null; + + return pairTarget(target, code, params.get("name") ?? hash.get("name")); +} + /** - * Parse the QR payload. Supported forms: + * Parse a pairing payload. Supported forms: + * `pi2://pair?host=…&port=…&code=…` (also `proto=https` and `host=host:port`) + * `https://host:port/pair/CODE` * `https://host:port/#pair=CODE` - * `#pair=CODE` (resolved against the current/typed endpoint) - * `pi2://pair?host=…&port=…&code=…` (design prototype compatibility) + * `https://host:port/?pair=CODE` / `?code=CODE` + * `#pair=CODE` / `?code=CODE` / `/pair/CODE` (resolved against the current/typed endpoint) */ export function parsePairLink(raw: string, fallbackEndpoint?: string | null): PairTarget | null { const text = String(raw || "").trim(); if (!text) return null; - if (/^pi2:\/\/pair\b/i.test(text)) { - let url: URL; - try { - url = new URL(text); - } catch { - return null; - } - if (url.protocol !== "pi2:") return null; - const params = url.searchParams; - const hostname = (params.get("host") || "").trim(); - if (!hostname) return null; - const portNum = Number(params.get("port")); - const port = Number.isInteger(portNum) && portNum >= 1 && portNum <= 65535 ? portNum : 4321; - const protocol = (params.get("proto") || "").toLowerCase() === "https" ? "https" : "http"; - const code = (params.get("code") || params.get("token") || "").trim(); - if (!code) return null; - return { - endpoint: `${protocol}://${hostname}:${port}`, - code, - name: params.get("name") || hostname, - hostname, - port, - }; - } + if (/^pi2:/i.test(text)) return parsePi2PairLink(text, fallbackEndpoint); let url: URL; try { - const base = - endpointFrom(fallbackEndpoint)?.endpoint || - (typeof window !== "undefined" ? window.location.origin : "http://localhost"); + const base = endpointFrom(fallbackEndpoint)?.endpoint ?? browserOrigin() ?? "http://localhost"; url = new URL(text, base); } catch { return null; } - const hash = new URLSearchParams(url.hash.replace(/^#/, "")); - const code = (hash.get("pair") || hash.get("code") || url.searchParams.get("pair") || "").trim(); + const code = extractPairCode(url); if (!code) return null; - const base = endpointFrom(fallbackEndpoint) ?? endpointFrom(url.origin); - if (!base) return null; const isAbsolute = /^https?:\/\//i.test(text); - const endpoint = isAbsolute ? endpointFrom(url.origin) : base; + const endpoint = isAbsolute + ? (endpointFrom(url.origin) ?? endpointFrom(fallbackEndpoint) ?? endpointFrom(browserOrigin())) + : (endpointFrom(fallbackEndpoint) ?? endpointFrom(url.origin) ?? endpointFrom(browserOrigin())); if (!endpoint) return null; - return { - endpoint: endpoint.endpoint, - code, - name: hash.get("name") || url.searchParams.get("name") || endpoint.hostname, - hostname: endpoint.hostname, - port: endpoint.port, - }; + const hash = new URLSearchParams(url.hash.replace(/^#/, "")); + return pairTarget(endpoint, code, hash.get("name") ?? url.searchParams.get("name")); } export function maskSecret(value: string): string { @@ -184,7 +248,24 @@ export function detectDeviceKind(): DeviceKind { return "laptop"; } -/** POST /api/v1/cmd pair.redeem against the selected origin. */ +/** Origin (scheme + host + port) of a stored endpoint; the redeem path is appended to it. */ +export function pairingOrigin(endpoint: string): string { + const parsed = endpointFrom(String(endpoint || "").trim()); + if (parsed) return parsed.endpoint; + return String(endpoint || "") + .trim() + .replace(/\/+$/, ""); +} + +function normalizeScopes(values: string[]): string[] { + const unique = [...new Set(values.map((value) => value.trim()).filter(Boolean))]; + return unique.length ? unique : [...DEFAULT_DEVICE_SCOPES]; +} + +/** + * Redeem a pairing code against the public `POST /api/v1/pair` + * endpoint: `{code,kind,deviceName}` → `{token,device}`. + */ export async function redeemPairing(input: { endpoint: string; code: string; @@ -192,43 +273,49 @@ export async function redeemPairing(input: { kind?: DeviceKind; signal?: AbortSignal; }): Promise { - const endpoint = input.endpoint.replace(/\/+$/, ""); - const response = await apiRequest>("/api/v1/cmd", { + const origin = pairingOrigin(input.endpoint); + const code = normalizePairCode(input.code); + const deviceName = input.deviceName.trim(); + const kind = input.kind ?? detectDeviceKind(); + + const response = await apiRequest>(PAIR_REDEEM_PATH, { method: "POST", - baseUrl: endpoint, - body: { - method: "pair.redeem", - params: { - code: input.code, - deviceName: input.deviceName, - kind: input.kind ?? detectDeviceKind(), - }, - }, + baseUrl: origin, + body: { code, kind, deviceName }, + skipAuthReset: true, signal: input.signal, }); const payload = asRecord(response.payload); const result = asRecord(response.result); - const device = asRecord(response.device); - const token = firstString(response.token, response.deviceToken, payload?.token, result?.token, device?.token); + const body = asRecord(response) ?? {}; + const device = + asRecord(body.device) ?? asRecord(result?.device) ?? asRecord(payload?.device) ?? asRecord(payload); + // `{token,device}` is the documented shape; keep the older aliases as a fallback. + const token = firstString(body.token, body.deviceToken, device?.token, result?.token, payload?.token); if (!token) { throw new ApiError({ code: "E_UNAUTHORIZED", - message: "pair.redeem returned no device token", + message: "pair redeem returned no device token", status: 401, }); } - const server = asRecord(response.server) as PairMeta["server"] | undefined; + const scopes = normalizeScopes([ + ...stringList(body.scopes), + ...stringList(device?.scopes), + ...stringList(result?.scopes), + ]); + return { token, - scopes: stringList(response.scopes).length - ? stringList(response.scopes) - : stringList(result?.scopes).length - ? stringList(result?.scopes) - : ["read"], - deviceId: firstString(response.deviceId, result?.deviceId, device?.deviceId), - server, + scopes, + deviceId: firstString(device?.id, body.deviceId, device?.deviceId, result?.deviceId), + deviceName: firstString(device?.name, deviceName), + kind: (firstString(device?.kind) as DeviceKind | undefined) ?? kind, + server: + (asRecord(body.server) as PairMeta["server"] | undefined) ?? + (asRecord(result?.server) as PairMeta["server"] | undefined), raw: response, }; } @@ -268,22 +355,23 @@ export function clearPairMeta(): void { } } -/** The connection redirect may target only the three navigation pages. */ +/** + * Post-pairing redirect target. Shares `safeNext`'s allow-list so a paired deep + * link such as `/chat/?workspace=…` survives the round trip. + */ export function safePairNext(raw: string | null | undefined): string { - if (!raw) return "/workspaces"; - try { - const url = new URL(String(raw), "http://pi2.local"); - if (url.pathname === "/workspaces" || url.pathname === "/chat" || url.pathname === "/status") { - return `${url.pathname}${url.search}`; - } - } catch { - /* fall through */ - } - return "/workspaces"; + return safeNext(raw, NEXT_FALLBACK); } -export function scopesForIdentity(meta: PairMeta | null, info: InfoResponse | null | undefined): string[] { +/** Ordered scope list for the paired summary: stored device scopes win over /info capabilities. */ +export function scopesForIdentity( + meta: PairMeta | null, + info: InfoResponse | null | undefined, + storedScopes?: string[] | null, +): string[] { + if (storedScopes?.length) return storedScopes; if (meta?.scopes.length) return meta.scopes; const capabilities = Array.isArray(info?.capabilities) ? info.capabilities : []; - return capabilities.filter((capability) => (PAIR_SCOPES as readonly string[]).includes(capability)); + const derived = capabilities.filter((capability) => (PAIR_SCOPES as readonly string[]).includes(capability)); + return derived.length ? derived : [...DEFAULT_DEVICE_SCOPES]; } diff --git a/web/src/features/status/connection-card.tsx b/web/src/features/status/connection-card.tsx index 4a7eb4f..549f3de 100644 --- a/web/src/features/status/connection-card.tsx +++ b/web/src/features/status/connection-card.tsx @@ -9,6 +9,7 @@ import { Button } from "@/components/ui/button"; import { KV, KVList } from "@/components/ui/kv"; import { toast } from "@/components/ui/toast"; import { drawQr } from "@/features/status/qr"; +import type { PairCodeResponse } from "@/features/status/queries"; import type { ServerIdentity } from "@/features/status/server"; import { ErrorBlock, LoadingBlock, StatusCard } from "./card-parts"; @@ -86,6 +87,64 @@ export interface ConnectionCardProps { error: string | null; onRetry: () => void; onDisconnect: () => void; + /** Fresh pairing code minted by the daemon (`POST /api/v1/pair`). */ + pairCode: PairCodeResponse | undefined; + pairLoading: boolean; + pairError: string | null; + onRetryPair: () => void; +} + +/** Minutes left before the minted code expires (never negative). */ +export function pairMinutesLeft(expiresAt: number | null | undefined, now = Date.now()): number | null { + if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt)) return null; + return Math.max(0, Math.ceil((expiresAt - now) / 60_000)); +} + +/** + * The live pairing code block: code, expiry, pairing URL and the QR drawn from + * that URL. Failures are retried in place instead of showing `—`. + */ +function PairingBlock({ + pairCode, + loading, + error, + fallbackUrl, + onRetry, +}: { + pairCode: PairCodeResponse | undefined; + loading: boolean; + error: string | null; + fallbackUrl: string; + onRetry: () => void; +}) { + const { t } = useTranslation(); + const code = String(pairCode?.code ?? "").trim(); + const url = String(pairCode?.url ?? "").trim() || (code ? `${fallbackUrl}/#pair=${code}` : ""); + const minutes = pairMinutesLeft(pairCode?.expiresAt); + + if (error) return ; + if (loading) return ; + if (!code) return ; + + return ( +
+ +
+ {code} +
+ {minutes != null ?
{t("status.securityExpiry", { n: minutes })}
: null} + {url ? ( +
+ {url} + +
+ ) : null} +
+ + {t("status.pairHint")} +
+
+ ); } /** Card 7 — addresses, mDNS, pairing code/QR, scopes, last connection, actions. */ @@ -98,10 +157,13 @@ export function ConnectionCard({ error, onRetry, onDisconnect, + pairCode, + pairLoading, + pairError, + onRetryPair, }: ConnectionCardProps) { const { t } = useTranslation(); const [confirmOpen, setConfirmOpen] = useState(false); - const qrSeed = `${server.networkAddress}/#pair=${server.pairingCode}`; return ( @@ -141,14 +203,13 @@ export function ConnectionCard({
-
- -
{server.pairingCode}
-
- - {t("status.pairHint")} -
-
+
diff --git a/web/src/features/status/devices-card.tsx b/web/src/features/status/devices-card.tsx index c6d1483..985bd58 100644 --- a/web/src/features/status/devices-card.tsx +++ b/web/src/features/status/devices-card.tsx @@ -27,6 +27,12 @@ export function deviceKey(device: DeviceEntry): string { return device.id || device.deviceId || device.name; } +/** The daemon reports `lastSeenAt`; older builds reported `lastActiveAt`. */ +export function deviceLastActive(device: DeviceEntry): number | null { + const ts = device.lastSeenAt ?? device.lastActiveAt; + return typeof ts === "number" && Number.isFinite(ts) ? ts : null; +} + export interface DevicesCardProps { devices: DeviceEntry[]; loading: boolean; @@ -64,7 +70,7 @@ export function DevicesCard({ devices, loading, error, onRetry, onRevoke }: Devi {visible.map((device) => { const scopes = Array.isArray(device.scopes) ? device.scopes : []; return ( -
+
@@ -79,12 +85,13 @@ export function DevicesCard({ devices, loading, error, onRetry, onRevoke }: Devi
- + + + + {t("connect.backToWorkspaces")} + + + } + /> + + + ) : active ? ( )} - void handleSend(text, images)} - onAbort={() => { - setSending(null); - void exec(chatCommands.abort(active?.sessionId ?? "")); - }} - onRemoveQueue={(id) => - void exec(chatCommands.removeQueued(active?.sessionId ?? "", id), "chat.queueRemoved") - } - onSetSteer={(id, steer) => - void exec( - chatCommands.setQueueSteer(active?.sessionId ?? "", id, steer), - steer ? "chat.steerOn" : "chat.steerOff", - ) - } - onSetModel={(model: ModelRef) => - void exec( - chatCommands.setModel(active?.sessionId ?? "", model), - "chat.modelSwitched", - { model: model.id }, - ) - } - onSetThinking={(level: ThinkingLevel) => - void exec( - chatCommands.setThinking(active?.sessionId ?? "", level), - "chat.thinkingSet", - { level }, - ) - } - /> + {sessionMissing ? null : ( + void handleSend(text, images, mode)} + onAbort={() => { + setSending(null); + void exec(chatCommands.abort(active?.sessionId ?? "")); + }} + onRemoveQueue={(id) => + void exec(chatCommands.removeQueued(active?.sessionId ?? "", id), "chat.queueRemoved") + } + onSetSteer={(steer) => void setSteerMode(steer)} + onSetModel={(model: ModelRef) => + void exec( + chatCommands.setModel(active?.sessionId ?? "", model), + "chat.modelSwitched", + { model: model.id }, + ) + } + onSetThinking={(level: ThinkingLevel) => + void exec( + chatCommands.setThinking(active?.sessionId ?? "", level), + "chat.thinkingSet", + { level }, + ) + } + /> + )} } panel={ @@ -478,7 +551,7 @@ function ChatExperience({ sessionId }: { sessionId?: string }) { onBack={() => { if (preview) { navigateSession(preview.session.sessionId); - toast(t("chat.returnedParent", { name: preview.session.name ?? preview.session.sessionId })); + toast.success(t("chat.returnedParent", { name: preview.session.name ?? preview.session.sessionId })); } setPreview(null); }} diff --git a/web/src/pages/connect.tsx b/web/src/pages/connect.tsx index c45e281..f3d9602 100644 --- a/web/src/pages/connect.tsx +++ b/web/src/pages/connect.tsx @@ -10,10 +10,12 @@ import { Button } from "@/components/ui/button"; import { Modal } from "@/components/ui/dialog"; import { KV } from "@/components/ui/kv"; import { toast } from "@/components/ui/toast"; -import { ManualConnectForm, type ManualConnectInput } from "@/features/connect/manual-form"; +import { ManualConnectForm, pairErrorMessage, type ManualConnectInput } from "@/features/connect/manual-form"; import { clearPairMeta, + isPairCode, maskSecret, + normalizePairCode, readPairMeta, redeemPairing, safePairNext, @@ -23,9 +25,9 @@ import { type PairTarget, } from "@/features/connect/pairing"; import { ScanDialog } from "@/features/connect/scan-dialog"; -import { deriveServerIdentity, type InfoExtras } from "@/features/status/server"; +import { deriveServerIdentity, formatUptime, type InfoExtras } from "@/features/status/server"; import { useInfoQuery } from "@/features/status/queries"; -import { ApiError, errorI18nKey } from "@/lib/api"; +import { setDeviceToken } from "@/lib/api"; import { useConnectionStore } from "@/stores/connection"; import "@/styles/pages/connect.css"; @@ -37,19 +39,16 @@ function scopeTone(scope: string): "default" | "info" | "ok" { return "default"; } -function messageFor(error: unknown, t: (key: string) => string): string { - if (error instanceof ApiError) return t(errorI18nKey(error.code)); - return t("connect.pairFailed"); -} - export function ConnectPage() { const { t } = useTranslation(); const navigate = useNavigate(); const searchStr = useRouterState({ select: (state) => state.location.searchStr }); - const next = useMemo( - () => safePairNext(new URLSearchParams(searchStr).get("next")), - [searchStr], - ); + const search = useMemo(() => new URLSearchParams(searchStr), [searchStr]); + const next = useMemo(() => safePairNext(search.get("next")), [search]); + const codeParam = useMemo(() => { + const raw = normalizePairCode(search.get("code")); + return isPairCode(raw) ? raw : ""; + }, [search]); const refreshFromStorage = useConnectionStore((state) => state.refreshFromStorage); const paired = useConnectionStore((state) => state.paired); @@ -60,6 +59,7 @@ export function ConnectPage() { const connectedAt = useConnectionStore((state) => state.connectedAt); const wsState = useConnectionStore((state) => state.wsState); const storedServer = useConnectionStore((state) => state.server); + const storedScopes = useConnectionStore((state) => state.scopes); const [meta, setMeta] = useState(() => readPairMeta()); const [scanOpen, setScanOpen] = useState(false); @@ -86,9 +86,17 @@ export function ConnectPage() { fetchedAt: info.dataUpdatedAt || null, nameFallback: storedServer?.name || meta?.server?.name, }); - const scopes = scopesForIdentity(meta, info.data); + const scopes = scopesForIdentity(meta, info.data, storedScopes); const defaultDeviceName = t("connect.defaultDeviceName"); + const osLabel = info.data?.os || info.data?.platform || server.os || "—"; + const uptimeSeconds = + typeof info.data?.uptimeMs === "number" ? info.data.uptimeMs / 1000 : server.uptimeSec; + /** + * One pairing path for the scan/confirm dialog and the manual form: + * redeem against the public endpoint, persist token + scopes, then follow + * the allow-listed `next`. + */ const finishPairing = useCallback( async (target: PairTarget, deviceName: string) => { const result = await redeemPairing({ @@ -96,10 +104,12 @@ export function ConnectPage() { code: target.code, deviceName, }); - connect({ endpoint: target.endpoint, deviceName, token: result.token }); + setDeviceToken(result.token); + connect({ endpoint: target.endpoint, deviceName, token: result.token, scopes: result.scopes }); const nextMeta: PairMeta = { scopes: result.scopes, deviceName, + kind: result.kind, server: result.server, pairedAt: Date.now(), }; @@ -112,15 +122,17 @@ export function ConnectPage() { ); async function handleManual(input: ManualConnectInput) { - const url = new URL(input.endpoint); + let hostname = ""; + let port = 4321; + try { + const url = new URL(input.endpoint); + hostname = url.hostname; + port = url.port ? Number(url.port) : url.protocol === "https:" ? 443 : 80; + } catch { + /* validate host/port above guarantees a parseable endpoint */ + } await finishPairing( - { - endpoint: input.endpoint, - code: input.code, - name: url.hostname, - hostname: url.hostname, - port: url.port ? Number(url.port) : url.protocol === "https:" ? 443 : 80, - }, + { endpoint: input.endpoint, code: input.code, name: hostname, hostname, port }, input.deviceName, ); } @@ -138,7 +150,7 @@ export function ConnectPage() { await finishPairing(pending, defaultDeviceName); setPending(null); } catch (error) { - const message = messageFor(error, t); + const message = t(pairErrorMessage(error)); setPairError(message); toast.error(message); } finally { @@ -187,24 +199,30 @@ export function ConnectPage() {
{server.name || "—"} - {server.hostname || "—"} + {info.data?.hostname || server.hostname || "—"} {storedEndpoint || server.endpoint || "—"} + {osLabel} {info.data?.version || meta?.server?.version || "—"} {info.data?.pluginVersion || meta?.server?.pluginVersion || "—"} + {formatUptime(uptimeSeconds)} {storedDeviceName || meta?.deviceName || "—"} {scopes.length ? ( {scopes.map((scope) => ( - - {scope} + + {t(`connect.scope.${scope}`, { defaultValue: scope })} ))} @@ -235,13 +253,19 @@ export function ConnectPage() { ) : ( <>
- - @@ -288,7 +326,7 @@ export function ConnectPage() { {pending.hostname}:{pending.port} - + {maskSecret(pending.code)}
diff --git a/web/src/pages/status.tsx b/web/src/pages/status.tsx index 8c16c2f..000faf2 100644 --- a/web/src/pages/status.tsx +++ b/web/src/pages/status.tsx @@ -16,19 +16,24 @@ import { deviceKey, DevicesCard } from "@/features/status/devices-card"; import { HealthCard } from "@/features/status/health-card"; import { ModelsCard } from "@/features/status/models-card"; import { + mergeTasks, + sessionTasks, useDevicesQuery, useHealthQuery, useInfoQuery, useModelsQuery, + usePairCodeQuery, useResourcesQuery, + useWorkspaceSessionsQueries, useWorkspacesQuery, type DeviceEntry, type DevicesResponse, + type StatusTask, } from "@/features/status/queries"; import { ResourcesCard } from "@/features/status/resources-card"; import { deriveServerIdentity, type InfoExtras } from "@/features/status/server"; import { ServerInfoCard } from "@/features/status/server-info-card"; -import { TasksCard, type StatusTask } from "@/features/status/tasks-card"; +import { TasksCard } from "@/features/status/tasks-card"; import { ApiError, api, errorI18nKey } from "@/lib/api"; import { useConnectionStore } from "@/stores/connection"; import { useSessionsStore } from "@/stores/sessions"; @@ -50,6 +55,7 @@ export function StatusPage() { const navigate = useNavigate(); const queryClient = useQueryClient(); + const paired = useConnectionStore((state) => state.paired); const endpoint = useConnectionStore((state) => state.endpoint); const wsState = useConnectionStore((state) => state.wsState); const storedServer = useConnectionStore((state) => state.server); @@ -62,6 +68,8 @@ export function StatusPage() { const resources = useResourcesQuery(); const workspacesQuery = useWorkspacesQuery(); const devices = useDevicesQuery(); + // The card shows the daemon's live code, not a cached one: mint on mount. + const pairCode = usePairCodeQuery(paired); const workspaces = workspacesQuery.data ?? []; const visibleWorkspaces = workspaces.filter((workspace) => !workspace.hidden); @@ -83,8 +91,12 @@ export function StatusPage() { status: info.isError ? "offline" : healthOk === false ? "degraded" : undefined, }); + // Background tasks: the live store covers open sessions, the REST session + // lists cover everything else (a hard reload empties the store). Only + // workspaces with a live instance are asked: `/sessions` relays through + // `instances.ensure()`, which would spawn a Neovim for every idle workspace. const byWorkspace = useSessionsStore((state) => state.byWorkspace); - const tasks = useMemo( + const liveTasks = useMemo( () => Object.values(byWorkspace).flatMap((sessions) => sessions.flatMap((session) => @@ -94,10 +106,25 @@ export function StatusPage() { [byWorkspace], ); + const workspaceIds = visibleWorkspaces + .filter((workspace) => workspace.instance != null) + .map((workspace) => workspace.workspaceId); + const sessionQueries = useWorkspaceSessionsQueries(workspaceIds); + const fetchedTasks = sessionQueries.flatMap((query) => (query.data ? sessionTasks(query.data) : [])); + const tasks = mergeTasks(liveTasks, fetchedTasks); + const tasksLoading = tasks.length === 0 && sessionQueries.some((query) => query.isPending); + const tasksFailed = sessionQueries.find((query) => query.isError); + const tasksError = tasksFailed ? translatedError(tasksFailed.error, "status.tasksError", t) : null; + + function retryTasks() { + for (const query of sessionQueries) void query.refetch(); + } + async function revokeDevice(device: DeviceEntry) { const key = deviceKey(device); try { - await api.command({ method: "device.revoke", params: { deviceId: key } }); + // DELETE /api/v1/devices/:id — the daemon marks the token revoked. + await api.revokeDevice(key); queryClient.setQueryData(["devices"], (previous) => previous ? { ...previous, devices: previous.devices.filter((item) => deviceKey(item) !== key) } @@ -137,6 +164,7 @@ export function StatusPage() {
void info.refetch()} @@ -167,7 +195,12 @@ export function StatusPage() { onRetry={() => void models.refetch()} /> - + void info.refetch()} onDisconnect={handleDisconnect} + pairCode={pairCode.data} + pairLoading={pairCode.isPending} + pairError={pairCode.isError ? translatedError(pairCode.error, "connect.pairFailed", t) : null} + onRetryPair={() => void pairCode.refetch()} />
diff --git a/web/src/router.tsx b/web/src/router.tsx index c3cff58..a4a30bf 100644 --- a/web/src/router.tsx +++ b/web/src/router.tsx @@ -2,6 +2,7 @@ import { Link, createRootRoute, createRoute, createRouter, redirect } from "@tan import { useTranslation } from "react-i18next"; import { AppShell } from "@/components/app-shell"; +import { isPairCode, normalizePairCode } from "@/features/connect/pairing"; import { CONNECT_PATH, safeNext } from "@/lib/routing"; import { useConnectionStore } from "@/stores/connection"; @@ -81,10 +82,33 @@ const statusRoute = createRoute({ const connectRoute = createRoute({ getParentRoute: () => rootRoute, path: "/connect", + validateSearch: (search: Record): { next?: string; code?: string } => ({ + next: typeof search.next === "string" ? safeNext(search.next) : undefined, + // `?code=` prefills the manual pairing field (used by the /pair/$code redirect). + code: typeof search.code === "string" ? normalizePairCode(search.code) : undefined, + }), + component: ConnectPage, +}); + +/** + * `/#/pair/` deep link → the connect page with the pairing code prefilled. + * Relative pairing links (`/pair/CODE`) can be pasted into the browser as-is. + */ +const pairRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/pair/$code", validateSearch: (search: Record): { next?: string } => ({ next: typeof search.next === "string" ? safeNext(search.next) : undefined, }), - component: ConnectPage, + beforeLoad: ({ params, search }) => { + const code = normalizePairCode(params.code); + const query = new URLSearchParams(); + if (isPairCode(code)) query.set("code", code); + if (search.next) query.set("next", safeNext(search.next)); + const suffix = query.size ? `?${query.toString()}` : ""; + throw redirect({ href: `${CONNECT_PATH}${suffix}` }); + }, + component: () => null, }); const routeTree = rootRoute.addChildren([ @@ -95,6 +119,7 @@ const routeTree = rootRoute.addChildren([ chatRoute, statusRoute, connectRoute, + pairRoute, ]); export const router = createRouter({ diff --git a/web/src/stores/connection.ts b/web/src/stores/connection.ts index 04a547c..d2eb011 100644 --- a/web/src/stores/connection.ts +++ b/web/src/stores/connection.ts @@ -8,6 +8,9 @@ export const CONNECTION_KEY = "pi2-connection"; export const ENDPOINT_KEY = "pi2-endpoint"; export const DEVICE_KEY = "pi2-device"; export const CONNECTED_AT_KEY = "pi2-connected-at"; +export const SCOPES_KEY = "pi2-device-scopes"; +/** Scope assumed for devices paired before scopes were persisted. */ +export const DEFAULT_CONNECTION_SCOPES = ["read"] as const; function read(key: string): string | null { try { @@ -33,6 +36,26 @@ function drop(key: string): void { } } +/** Persisted device scopes; defaults to `["read"]` when absent or unreadable. */ +function readScopes(): string[] { + const raw = read(SCOPES_KEY); + if (!raw) return [...DEFAULT_CONNECTION_SCOPES]; + try { + const parsed: unknown = JSON.parse(raw); + if (Array.isArray(parsed)) { + const scopes = parsed.filter((item): item is string => typeof item === "string" && item.trim() !== ""); + return scopes.length ? scopes : [...DEFAULT_CONNECTION_SCOPES]; + } + } catch { + /* fall through to the default */ + } + return [...DEFAULT_CONNECTION_SCOPES]; +} + +function writeScopes(scopes: string[]): void { + write(SCOPES_KEY, JSON.stringify(scopes.length ? scopes : DEFAULT_CONNECTION_SCOPES)); +} + export type PairingState = "paired" | "unpaired"; export interface ConnectionStore { @@ -42,12 +65,14 @@ export interface ConnectionStore { deviceName: string; connectedAt: number; token: string | null; + /** Device scopes granted by the daemon when this browser was paired. */ + scopes: string[]; server: InfoResponse | null; wsState: WsConnectionState; isPaired: () => boolean; refreshFromStorage: () => void; - connect: (options?: { endpoint?: string; deviceName?: string; token?: string | null }) => void; + connect: (options?: { endpoint?: string; deviceName?: string; token?: string | null; scopes?: string[] }) => void; disconnect: () => void; setServer: (server: InfoResponse | null) => void; setWsState: (state: WsConnectionState) => void; @@ -61,6 +86,7 @@ function initialState() { deviceName: read(DEVICE_KEY) ?? "", connectedAt: Number(read(CONNECTED_AT_KEY)) || 0, token: getDeviceToken(), + scopes: readScopes(), server: null as InfoResponse | null, wsState: "idle" as WsConnectionState, }; @@ -73,11 +99,12 @@ export const useConnectionStore = create((set, get) => ({ refreshFromStorage: () => set(initialState()), - connect: ({ endpoint, deviceName, token } = {}) => { + connect: ({ endpoint, deviceName, token, scopes } = {}) => { const now = Date.now(); if (endpoint) write(ENDPOINT_KEY, endpoint); if (deviceName) write(DEVICE_KEY, deviceName); if (token !== undefined) setDeviceToken(token); + if (scopes !== undefined) writeScopes(scopes); write(CONNECTED_AT_KEY, String(now)); write(CONNECTION_KEY, "paired"); set({ @@ -86,6 +113,7 @@ export const useConnectionStore = create((set, get) => ({ deviceName: deviceName ?? get().deviceName, connectedAt: now, token: getDeviceToken(), + scopes: scopes !== undefined ? readScopes() : get().scopes, }); }, @@ -93,6 +121,7 @@ export const useConnectionStore = create((set, get) => ({ drop(ENDPOINT_KEY); drop(DEVICE_KEY); drop(CONNECTED_AT_KEY); + drop(SCOPES_KEY); setDeviceToken(null); write(CONNECTION_KEY, "unpaired"); set({ @@ -101,6 +130,7 @@ export const useConnectionStore = create((set, get) => ({ deviceName: "", connectedAt: 0, token: null, + scopes: [...DEFAULT_CONNECTION_SCOPES], server: null, wsState: "idle", }); diff --git a/web/src/stores/sessions.ts b/web/src/stores/sessions.ts index 7f6d421..f006b94 100644 --- a/web/src/stores/sessions.ts +++ b/web/src/stores/sessions.ts @@ -11,6 +11,8 @@ export interface SessionsStore { setSessions: (workspaceId: string, sessions: SessionState[]) => void; upsertSession: (session: SessionState) => void; + /** Re-key a session after the plugin migrates `tmp-N` → the real id. */ + renameSessionId: (from: string, to: string) => void; removeSession: (sessionId: string) => void; selectSession: (sessionId: string | null) => void; listFor: (workspaceId: string) => SessionState[]; @@ -44,6 +46,33 @@ export const useSessionsStore = create((set, get) => ({ return { byWorkspace: { ...state.byWorkspace, [session.workspaceId]: next } }; }), + renameSessionId: (from, to) => + set((state) => { + if (!from || !to || from === to) return state; + const byWorkspace: Record = {}; + let moved = false; + for (const [workspaceId, list] of Object.entries(state.byWorkspace)) { + const index = list.findIndex((session) => session.sessionId === from); + if (index === -1) { + byWorkspace[workspaceId] = list; + continue; + } + moved = true; + byWorkspace[workspaceId] = list + .map((session, position) => + position === index ? { ...session, sessionId: to } : session, + ) + // A row already cached under the new id would now duplicate the + // migrated one (the REST list can be ahead of the event). + .filter((session, position) => position === index || session.sessionId !== to); + } + if (!moved) return state; + return { + byWorkspace, + selectedSessionId: state.selectedSessionId === from ? to : state.selectedSessionId, + }; + }), + removeSession: (sessionId) => set((state) => { const byWorkspace: Record = {}; diff --git a/web/src/styles/app.css b/web/src/styles/app.css index d2bcb27..0152805 100644 --- a/web/src/styles/app.css +++ b/web/src/styles/app.css @@ -129,6 +129,22 @@ code, pre, .mono { font-family: var(--font-mono); font-size: .8125em; } .tabbar .nav-item.active { color: var(--primary); background: none; } .main { flex: 1; min-width: 0; padding: var(--space-6); padding-bottom: calc(var(--tabbar-h) + var(--space-6)); } + +/* ---------- connection banner (paired but the socket is down) ---------- */ +.reconnect-banner { + display: flex; align-items: center; gap: var(--space-3); + padding: var(--space-2) var(--space-4); + background: color-mix(in oklch, var(--warn) 12%, var(--card)); + border-bottom: 1px solid color-mix(in oklch, var(--warn) 45%, var(--border)); + color: var(--foreground); + font-size: .8125rem; +} +.reconnect-banner .ico { color: var(--warn); flex: none; } +.reconnect-banner__text { flex: 1; min-width: 0; } +.reconnect-banner .btn { flex: none; } +@media (max-width: 599px) { + .reconnect-banner { padding: var(--space-2) var(--space-3); font-size: .75rem; } +} @media (min-width: 840px) { .sidebar { display: block; } } @media (min-width: 600px) and (max-width: 839px) { .rail { display: flex; } } @media (min-width: 600px) { .main { padding-bottom: var(--space-6); } } @@ -367,12 +383,16 @@ code, pre, .mono { font-family: var(--font-mono); font-size: .8125em; } .modal-backdrop.open { opacity: 1; pointer-events: auto; } .modal-backdrop[data-state="open"] { opacity: 1; pointer-events: auto; } .modal { + /* Sits above the .modal-backdrop scrim (z-index 60) so its buttons are clickable. */ + position: relative; z-index: 61; width: min(26rem, 100%); max-height: 88dvh; overflow: auto; background: var(--popover); color: var(--popover-foreground); border-radius: var(--radius-xl); box-shadow: var(--shadow-lg); padding: var(--space-6); transform: translateY(10px); transition: transform .18s ease; } +/* pointer-events is reset on the scrim when closed; keep the panel interactive when it is nested. */ +.modal-content { pointer-events: auto; } .modal--wide { width: max(60vw, 26rem); max-width: 100%; } .modal-backdrop.open .modal, .modal-backdrop[data-state="open"] .modal, @@ -400,8 +420,7 @@ code, pre, .mono { font-family: var(--font-mono); font-size: .8125em; } } .sheet-handle { width: 2.5rem; height: .3125rem; border-radius: 999px; background: var(--border); margin: 0 auto var(--space-4); flex: none; } -.toasts { position: fixed; right: var(--space-4); bottom: calc(var(--space-4) + var(--tabbar-h)); z-index: 80; display: flex; flex-direction: column; gap: var(--space-2); } -@media (min-width: 600px) { .toasts { bottom: var(--space-4); } } +.toasts { position: fixed; right: var(--space-4); bottom: calc(var(--space-4) + var(--tabbar-h)); z-index: 80; display: flex; flex-direction: column; gap: var(--space-2); }@media (min-width: 600px) { .toasts { bottom: var(--space-4); } } .toast { display: flex; align-items: center; gap: var(--space-2); background: var(--popover); color: var(--popover-foreground); diff --git a/web/src/styles/pages/connect.css b/web/src/styles/pages/connect.css index 1737b86..b4508fe 100644 --- a/web/src/styles/pages/connect.css +++ b/web/src/styles/pages/connect.css @@ -48,17 +48,13 @@ .cn .input { min-height: 2.5rem; } .cn-field .input { transition: border-color .15s ease, box-shadow .15s ease; } -/* token: password + reveal toggle */ -.cn-token { position: relative; display: flex; align-items: center; } -.cn-token .input { padding-right: 2.875rem; } -.cn-token .cn-eye { - position: absolute; - right: var(--space-1); - color: var(--muted-foreground); - min-width: 2.5rem; - min-height: 2.5rem; +/* pairing code: 8 uppercase alphanumerics, monospace + tracked so it reads like the server */ +.cn-code { + font-family: var(--font-mono); + letter-spacing: .18em; + text-transform: uppercase; + font-variant-numeric: tabular-nums; } -.cn-token .cn-eye.is-on { color: var(--foreground); } /* error rail — the only structural color block allowed by the design */ .cn-error { diff --git a/web/src/styles/pages/status.css b/web/src/styles/pages/status.css index 4f7f20c..f1a6b45 100644 --- a/web/src/styles/pages/status.css +++ b/web/src/styles/pages/status.css @@ -159,6 +159,12 @@ text-align: center; font-variant-numeric: tabular-nums; } +.pair-expiry { + font-size: .75rem; + font-variant-numeric: tabular-nums; + color: var(--muted-foreground); + text-align: center; +} .pair-hint { display: flex; align-items: center; gap: var(--space-1); font-size: .75rem; text-align: center; diff --git a/web/tests/chat-fixtures.ts b/web/tests/chat-fixtures.ts index a8f7053..cbe8f49 100644 --- a/web/tests/chat-fixtures.ts +++ b/web/tests/chat-fixtures.ts @@ -1,4 +1,4 @@ -import type { Batch, Entry, SessionState, Subagent, TodoItem } from "@protocol/types"; +import type { Batch, Entry, SessionState, Subagent, TaskItem, TodoItem } from "@protocol/types"; import { emptySessionState } from "@/features/chat/session-state"; @@ -27,6 +27,31 @@ export function subagentFixture(overrides: Partial = {}): Subagent { }; } +export function taskFixture(overrides: Partial = {}): TaskItem { + return { + id: "t1", + command: "pnpm test", + status: "completed", + startTime: Date.now() - 5_000, + durationMs: 4_200, + exitCode: 0, + outputFile: "/tmp/pi2-task-t1.log", + ...overrides, + }; +} + +/** `task.output` ack for `taskFixture()`. */ +export function taskOutputFixture(overrides: Record = {}): Record { + return { + output: "$ pnpm test\n42 passed", + outputFile: "/tmp/pi2-task-t1.log", + status: "completed", + exitCode: 0, + durationMs: 4_200, + ...overrides, + }; +} + export function todoFixture(): TodoItem[] { return [ { content: "Inspect callers", status: "completed" }, diff --git a/web/tests/chat.attention.test.tsx b/web/tests/chat.attention.test.tsx index 801a497..8ac6123 100644 --- a/web/tests/chat.attention.test.tsx +++ b/web/tests/chat.attention.test.tsx @@ -28,7 +28,7 @@ function attention(overrides: Partial = {}): AttentionItem { } describe("attention dialog", () => { - it("renders the request and responds with the chosen option", async () => { + it("renders the server title/options and answers `select` with the option id", async () => { const item = attention(); const onRespond = vi.fn(); render( @@ -40,8 +40,31 @@ describe("attention dialog", () => { ); expect(await screen.findByText("Run this command?")).toBeInTheDocument(); - fireEvent.click(screen.getByRole("button", { name: "Allow once" })); - expect(onRespond).toHaveBeenCalledWith(item, "allow-once"); + const option = screen.getByRole("button", { name: "Allow once" }); + expect(option).toHaveAttribute("data-option-id", "allow-once"); + + fireEvent.click(option); + // `pi.attention.resolve` expects `{value: