fix(web): make the web console work end-to-end

- Pair through the public POST /api/v1/pair and persist the device scopes;
  keep the allow-listed next deep link. Rename the manual field to pairing code.
- Authenticate the WebSocket with the raw device token (strip Bearer) and
  recover from a 401 by clearing the connection once.
- Fix chat payloads: setModel/setThinking, attention/diff responses, subagent
  dispatch items, queue ids/mode, task output and WS resume since.
- Render exactly one assistant message per turn: one-to-one snapshot/history
  merge plus a stale-delta guard after message_end (fixes PONGONG).
- Fix dialogs (content above the overlay), unknown-session deep links
  (error + retry, no silent fallback), device list/revoke, status identity and
  live pairing code, reconnect banner and Playwright selectors.
This commit is contained in:
yuez committed 2026-10-21 20:42:19 +08:00
1 parent 5572ac0d84
commit 0ef019f58d
57 files changed
+3549 -684

No files matched your search

+72 -56
View File
@@ -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<AttentionItem | null>(null);
const [remaining, setRemaining] = useState<number | null>(null);
const responded = useRef(false);
const dismissed = useRef<string | null>(null);
const timedOut = useRef<Set<string>>(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<Set<string>>(new Set());
/** The request currently on screen, to report a remote resolution once. */
const shown = useRef<string | null>(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 (
<Modal
@@ -123,7 +137,10 @@ export function AttentionDialog({ session, onRespond, onRemoteResolved }: Attent
files={files}
onDecision={(decision, path) =>
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
<Button
key={option.id}
variant={index === 0 ? "primary" : option.id === "deny" ? "danger" : "ghost"}
onClick={() => {
const ok = option.id !== "deny";
respond(
option.id,
option.id === "deny"
? t("chat.denied")
: option.id === "always"
? t("chat.alwaysAllowed")
: t("chat.allowedOnce"),
ok ? "success" : "error",
);
}}
data-option-id={option.id}
onClick={() => choose(option.id)}
>
{option.label}
</Button>
))}
{options.length ? null : (
<Button
variant="ghost"
data-option-id="cancel"
onClick={() => respond(cancelResponse())}
>
{t("common.cancel")}
</Button>
)}
</div>
)}
{current.timeoutSec ? (
+5 -1
View File
@@ -296,7 +296,11 @@ export function EntryBlock({ entry, turnStart }: EntryBlockProps) {
-1,
);
return (
<article className={cn("msg", `msg--${entry.role}`, turnStart && "turn-start")}>
<article
className={cn("msg", `msg--${entry.role}`, turnStart && "turn-start")}
data-entry-id={entry.id}
data-role={entry.role}
>
<MessageMeta entry={entry} />
{entry.blocks.map((block, index) => {
if (block.type === "text") {
+64 -20
View File
@@ -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<CommandResult>;
}
/** 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<PromptImage> {
+48 -30
View File
@@ -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)}
/>
<span>{t("chat.steer")}</span>
</label>
@@ -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({
<select
className="select composer__sel"
aria-label={t("chat.model")}
data-testid="composer-model"
value={model ? `${model.provider}/${model.id}` : ""}
disabled={!enabled || !groups.length}
onChange={(event) => {
@@ -234,6 +239,7 @@ export function Composer({
<select
className="select composer__sel"
aria-label={t("chat.thinkingAria")}
data-testid="composer-thinking"
value={thinking}
disabled={!enabled}
onChange={(event) => onSetThinking(event.target.value as ThinkingLevel)}
@@ -246,28 +252,42 @@ export function Composer({
</select>
<div className="spacer" />
{busy ? (
<Button
variant="danger"
className="composer__send"
title={t("chat.abortTitle")}
disabled={!connected}
onClick={onAbort}
>
<Icon name="stop" />
{t("chat.abort")}
</Button>
) : (
<Button
variant="primary"
className="composer__send"
title={t("chat.sendTitle")}
disabled={!enabled || !text.trim()}
onClick={submit}
>
<Icon name="send" />
{t("chat.send")}
</Button>
)}
<>
<Button
variant="ghost"
className="composer__steer"
title={t("chat.steer")}
data-testid="composer-steer"
disabled={!enabled || !text.trim()}
onClick={() => submit("steer")}
>
<Icon name="alert" />
{t("chat.steer")}
</Button>
<Button
variant="danger"
className="composer__abort"
title={t("chat.abortTitle")}
data-testid="composer-abort"
disabled={!connected}
onClick={onAbort}
>
<Icon name="stop" />
{t("chat.abort")}
</Button>
</>
) : null}
<Button
variant="primary"
className="composer__send"
title={t("chat.sendTitle")}
data-testid="composer-send"
disabled={!enabled || !text.trim()}
onClick={() => submit()}
>
<Icon name="send" />
{t("chat.send")}
</Button>
</div>
</div>
{hint ? (
@@ -312,7 +332,6 @@ export function Composer({
>
<Icon name="plus" />
<div>{t("chat.dropHint")}</div>
<div className="muted">{t("chat.dropNote")}</div>
</div>
<input
ref={fileRef}
@@ -348,7 +367,6 @@ export function Composer({
))}
</div>
) : null}
<div className="muted composer__note">{t("chat.attachNote")}</div>
</div>
</Modal>
</div>
+93 -14
View File
@@ -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<string, unknown>,
): { 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 {
+16 -2
View File
@@ -85,6 +85,8 @@ export function DiffView({ files, onDecision, className }: DiffViewProps) {
<Button
size="sm"
variant="primary"
data-decision="accept"
data-path={file.path}
onClick={() => onDecision("accept", file.path)}
>
{t("chat.accept")}
@@ -92,6 +94,8 @@ export function DiffView({ files, onDecision, className }: DiffViewProps) {
<Button
size="sm"
variant="danger"
data-decision="reject"
data-path={file.path}
onClick={() => onDecision("reject", file.path)}
>
{t("chat.reject")}
@@ -106,10 +110,20 @@ export function DiffView({ files, onDecision, className }: DiffViewProps) {
{onDecision ? (
<div className="diff__foot diff__foot--all">
<span className="muted grow">{t("chat.diffReview")}</span>
<Button size="sm" variant="ghost" onClick={() => onDecision("reject")}>
<Button
size="sm"
variant="ghost"
data-decision="reject"
onClick={() => onDecision("reject")}
>
{t("chat.rejectAll")}
</Button>
<Button size="sm" variant="primary" onClick={() => onDecision("accept")}>
<Button
size="sm"
variant="primary"
data-decision="accept"
onClick={() => onDecision("accept")}
>
{t("chat.acceptAll")}
</Button>
</div>
+8
View File
@@ -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,
+6 -1
View File
@@ -174,7 +174,12 @@ export function MessageStream({
<Spinner /> {t("chat.loadingOlder")}
</span>
) : hasMore ? (
<button type="button" className="stream-older muted" onClick={onLoadOlder}>
<button
type="button"
className="stream-older muted"
data-testid="load-older"
onClick={onLoadOlder}
>
{t("chat.loadOlder")}
</button>
) : null}
+88
View File
@@ -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: "<new>", 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/<to>?workspace=<ws>` — 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<MigrationListener>();
/** Subscribe to session-id migrations (returns the unsubscribe function). */
export function onSessionMigration(listener: MigrationListener): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
/** `/chat/<sessionId>` 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;
}
+154 -77
View File
@@ -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<string, unknown> | undefined {
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : 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<Subagent["status"], string> = {
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 `[<index>] <role>: <text>` 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<Entry[] | null>(null);
const [feed, setFeed] = useState<SubagentEntry[]>([]);
const [sessionFile, setSessionFile] = useState<string | null>(null);
const [error, setError] = useState<string | null>(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<string, unknown>;
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
<div className="row muted">
<Spinner /> {t("chat.loading")}
</div>
) : error ? (
<div className="msg__error" role="alert">
<div className="msg__error-meta">
<span className="who who--err">{t("chat.error")}</span>
</div>
<div className="msg__text">{error}</div>
</div>
) : feed.length ? (
feed.map((entry) => (
<article
key={entry.id}
className={cn("msg", `msg--${entry.role === "user" ? "user" : "assistant"}`)}
data-entry-id={entry.id}
data-role={entry.role}
>
<div className="msg__meta">
<span className={cn("who", entry.role === "user" ? "who--user" : "who--agent")}>
{entry.role}
</span>
<span className="muted msg__time mono">{entry.id}</span>
</div>
<div className="msg__text">{entry.text}</div>
</article>
))
) : (
feed.map((entry) => <EntryBlock key={entry.id} entry={entry} />)
<div className="muted">{t("chat.noOutput")}</div>
)}
</div>
{sessionFile ? <div className="muted mono truncate">{sessionFile}</div> : null}
<div className="muted sub-preview__note">{t("chat.previewNote")}</div>
<div className="row sub-steer">
<input
@@ -373,10 +423,28 @@ export function SubagentModal({ open, session, subagent, onClose, onBack, onStee
/* task output */
/* ------------------------------------------------------------------ */
function fakePid(task: TaskItem): number {
let hash = 0;
for (const char of task.id) hash = (hash * 31 + char.charCodeAt(0)) % 100_000;
return 10_000 + (hash % 8_000);
/** `task.output` response payload (plugin handler, `docs/protocol.md` §3.2). */
export interface TaskOutputResult {
output?: string;
outputFile?: string;
status?: TaskItem["status"];
exitCode?: number | null;
durationMs?: number;
}
/** Read the fields the modal renders, ignoring anything the daemon added. */
export function normalizeTaskOutput(raw: unknown): TaskOutputResult {
const record = rec(raw) ?? {};
const status = str(record.status);
return {
...(str(record.output) !== undefined ? { output: str(record.output) } : {}),
...(str(record.outputFile) !== undefined ? { outputFile: str(record.outputFile) } : {}),
...(status ? { status: status as TaskItem["status"] } : {}),
...(record.exitCode === null || num(record.exitCode) !== undefined
? { exitCode: record.exitCode === null ? null : num(record.exitCode) }
: {}),
...(num(record.durationMs) !== undefined ? { durationMs: num(record.durationMs) } : {}),
};
}
export interface TaskOutputModalProps {
@@ -389,33 +457,39 @@ export interface TaskOutputModalProps {
export function TaskOutputModal({ open, session, task, onClose, onStop }: TaskOutputModalProps) {
const { t } = useTranslation();
const [output, setOutput] = useState<string | null>(null);
const [result, setResult] = useState<TaskOutputResult | null>(null);
const [error, setError] = useState<string | null>(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<string, unknown>;
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 (
<Modal
@@ -438,21 +512,24 @@ export function TaskOutputModal({ open, session, task, onClose, onStop }: TaskOu
}
>
<div className="stack">
<pre className="mono tool__pre">{loading ? t("chat.loading") : (output ?? t("chat.noOutput"))}</pre>
{task.outputFile ? <div className="muted mono truncate">{task.outputFile}</div> : null}
<pre className="mono tool__pre" data-testid="task-output">
{loading
? t("chat.loading")
: error
? t("chat.commandFailed", { error })
: (result?.output ?? t("chat.noOutput"))}
</pre>
{outputFile ? <div className="muted mono truncate">{outputFile}</div> : null}
<div>
<KV label="pid" mono>
{fakePid(task)}
</KV>
<KV label={t("chat.status")}>
<span className="row">
<span className={`dot ${running ? "dot--busy" : task.status === "completed" ? "dot--ok" : task.status === "failed" ? "dot--err" : "dot--idle"}`} />
{t(`state.${task.status}`)}
<span className={`dot ${running ? "dot--busy" : status === "completed" ? "dot--ok" : status === "failed" ? "dot--err" : "dot--idle"}`} />
{t(`state.${status}`)}
</span>
</KV>
<KV label={t("chat.duration")}>{formatDuration(duration)}</KV>
<KV label="exit code" mono>
{task.exitCode == null ? "—" : task.exitCode}
{exitCode == null ? "—" : exitCode}
</KV>
<KV label={t("chat.command")} mono>
{task.command}
+31
View File
@@ -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() };
+2
View File
@@ -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 === " ") {
+3 -2
View File
@@ -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",
)}
/>
<span className="sub-item__main">
/> <span className="sub-item__main">
<span className="sub-item__name truncate">
{subagent.name ?? subagent.id}
</span>
@@ -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 === " ") {
+23
View File
@@ -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<ChatStore>((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,
};
}),
}));
+57 -38
View File
@@ -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<void>;
hostInputRef: RefObject<HTMLInputElement | null>;
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<string | null>(null);
const [portError, setPortError] = useState<string | null>(null);
const [codeError, setCodeError] = useState<string | null>(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 }
<Input
ref={hostInputRef}
id={`${id}-host`}
data-testid="connect-host"
type="text"
inputMode="url"
autoCapitalize="off"
@@ -119,6 +131,7 @@ export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName }
<Field label={t("connect.port")} htmlFor={`${id}-port`} error={portError}>
<Input
id={`${id}-port`}
data-testid="connect-port"
type="text"
inputMode="numeric"
autoComplete="off"
@@ -132,36 +145,36 @@ export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName }
</Field>
</div>
<Field label={t("connect.token")} htmlFor={`${id}-token`} hint={t("connect.tokenHint")} error={codeError}>
<div className="cn-token">
<Input
id={`${id}-token`}
type={showCode ? "text" : "password"}
autoComplete="current-password"
placeholder={t("connect.tokenPlaceholder")}
value={code}
onChange={(event) => {
setCode(event.target.value);
setCodeError(null);
}}
/>
<Button
variant="ghost"
size="icon"
className={showCode ? "cn-eye is-on" : "cn-eye"}
aria-pressed={showCode}
aria-label={t("connect.token")}
title={t("connect.token")}
onClick={() => setShowCode((value) => !value)}
>
<Icon name="eye" />
</Button>
</div>
<Field
label={t("connect.pairCode")}
htmlFor={`${id}-pair-code`}
hint={t("connect.pairCodeHint")}
error={codeError}
>
<Input
id={`${id}-pair-code`}
data-testid="connect-pair-code"
className="cn-code"
type="text"
inputMode="text"
autoCapitalize="characters"
autoComplete="off"
autoCorrect="off"
spellCheck={false}
maxLength={PAIR_CODE_LENGTH}
placeholder={t("connect.pairCodePlaceholder")}
value={code}
onChange={(event) => {
setCode(normalizePairCode(event.target.value).slice(0, PAIR_CODE_LENGTH));
setCodeError(null);
}}
/>
</Field>
<Field label={t("connect.deviceName")} htmlFor={`${id}-device`} hint={t("common.optional")}>
<Input
id={`${id}-device`}
data-testid="connect-device"
type="text"
autoComplete="nickname"
placeholder={t("connect.deviceNamePlaceholder")}
@@ -180,7 +193,13 @@ export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName }
) : null}
<div className="cn-form__foot">
<Button variant="primary" type="submit" className="cn-submit" disabled={busy}>
<Button
variant="primary"
type="submit"
className="cn-submit"
disabled={busy}
data-testid="connect-submit"
>
<Icon name={busy ? "refresh" : "chevron-right"} />
{busy ? t("connect.connecting") : t("connect.connect")}
</Button>
+166 -78
View File
@@ -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 <origin>/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<RedeemResult> {
const endpoint = input.endpoint.replace(/\/+$/, "");
const response = await apiRequest<Record<string, unknown>>("/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<Record<string, unknown>>(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/<sid>?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];
}
+70 -9
View File
@@ -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 <ErrorBlock message={error} onRetry={onRetry} />;
if (loading) return <LoadingBlock rows={3} />;
if (!code) return <ErrorBlock message={t("connect.pairFailed")} onRetry={onRetry} />;
return (
<div className="qr-wrap">
<QrCanvas seed={url || code} label={t("status.qrAria")} />
<div className="pair-code" data-testid="pairing-code">
{code}
</div>
{minutes != null ? <div className="pair-expiry muted">{t("status.securityExpiry", { n: minutes })}</div> : null}
{url ? (
<div className="addr-row" data-testid="pairing-url">
<code className="mono truncate grow">{url}</code>
<CopyButton value={url} label={t("connect.pairingLink")} />
</div>
) : null}
<div className="pair-hint muted">
<Icon name="phone" />
<span>{t("status.pairHint")}</span>
</div>
</div>
);
}
/** 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 (
<StatusCard title={t("status.connection")} icon="qr">
@@ -141,14 +203,13 @@ export function ConnectionCard({
</KV>
</div>
<div className="qr-wrap">
<QrCanvas seed={qrSeed} label={t("status.qrAria")} />
<div className="pair-code">{server.pairingCode}</div>
<div className="pair-hint muted">
<Icon name="phone" />
<span>{t("status.pairHint")}</span>
</div>
</div>
<PairingBlock
pairCode={pairCode}
loading={pairLoading}
error={pairError}
fallbackUrl={server.networkAddress}
onRetry={onRetryPair}
/>
</div>
<KVList className="security-note">
+9 -2
View File
@@ -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 (
<div className="device-row" key={deviceKey(device)}>
<div className="device-row" key={deviceKey(device)} data-device-id={deviceKey(device)}>
<span className="device-icon">
<Icon name={KIND_ICON[device.kind] ?? "phone"} />
</span>
@@ -79,12 +85,13 @@ export function DevicesCard({ devices, loading, error, onRetry, onRevoke }: Devi
</div>
</div>
<span className="device-time muted">
<RelativeTime ts={device.lastActiveAt} />
<RelativeTime ts={deviceLastActive(device)} />
</span>
<Button
variant="ghost"
size="sm"
className="status-revoke"
aria-label={`${t("status.revoke")} ${device.name}`}
onClick={() => setTarget(device)}
>
<Icon name="revoke" />
+133 -7
View File
@@ -1,16 +1,30 @@
import { useQuery } from "@tanstack/react-query";
import { useQueries, useQuery } from "@tanstack/react-query";
import { api, apiRequest, type HealthResponse, type InfoResponse, type ModelInfo, type ResourcesResponse } from "@/lib/api";
import type { WorkspaceInfo } from "@/lib/protocol";
import {
api,
apiRequest,
type HealthResponse,
type InfoResponse,
type ModelInfo,
type ResourcesResponse,
} from "@/lib/api";
import type { SessionState, TaskItem, WorkspaceInfo } from "@/lib/protocol";
/** GET /api/v1/devices uses `id` on the wire; older builds exposed `deviceId`. */
/**
* `GET /api/v1/devices` answers a **bare array** (`auth.listDevices()`); older
* builds wrapped it as `{devices:[…]}`. `id` is the daemon's device id, while
* `deviceId` is what pairing responses call it.
*/
export interface DeviceEntry {
id?: string;
deviceId?: string;
name: string;
kind: string;
scopes: string[];
lastActiveAt: number | null;
/** `lastSeenAt` is the daemon field; `lastActiveAt` came from older builds. */
lastActiveAt?: number | null;
lastSeenAt?: number | null;
createdAt?: number | null;
revokedAt?: number | null;
}
@@ -22,14 +36,81 @@ export interface ModelsResponse {
providers: ModelInfo[];
}
/** Accept the daemon's bare device array and the legacy `{devices:[…]}` envelope. */
export function normalizeDevices(payload: unknown): DeviceEntry[] {
if (Array.isArray(payload)) return payload as DeviceEntry[];
const record = payload as { devices?: unknown } | null | undefined;
return Array.isArray(record?.devices) ? (record.devices as DeviceEntry[]) : [];
}
export async function fetchDevices(signal?: AbortSignal): Promise<DevicesResponse> {
return apiRequest<DevicesResponse>("/api/v1/devices", { signal });
return { devices: normalizeDevices(await apiRequest<unknown>("/api/v1/devices", { signal })) };
}
export async function fetchModels(workspaceId: string, signal?: AbortSignal): Promise<ModelsResponse> {
return apiRequest<ModelsResponse>(`/api/v1/models?workspaceId=${encodeURIComponent(workspaceId)}`, { signal });
}
/**
* `/api/v1/pair` is public for redemption (`{code,…}`) and *authenticated* for
* minting: an authenticated `POST` with no `code` returns
* `{accepted,code,url,expiresAt,nonce}` (docs/protocol.md §3.2).
*/
export interface PairCodeResponse {
accepted?: boolean;
code?: string;
url?: string;
expiresAt?: number;
nonce?: string;
}
/** Pairing codes are short-lived; 10 minutes matches `auth.pairCreate`'s default. */
export const PAIR_CODE_TTL_SEC = 600;
export async function createPairCode(signal?: AbortSignal): Promise<PairCodeResponse> {
return apiRequest<PairCodeResponse>("/api/v1/pair", {
method: "POST",
body: { ttlSec: PAIR_CODE_TTL_SEC },
signal,
});
}
/** A background task plus the session it belongs to (the card shows both). */
export interface StatusTask extends TaskItem {
sessionId: string;
}
/** `/sessions` relays a `workspace.query` ack: `{sessions}`, `{result:{sessions}}` or a bare array. */
export function normalizeSessions(payload: unknown, workspaceId: string): SessionState[] {
if (Array.isArray(payload)) return (payload as SessionState[]).map((row) => ({ ...row, workspaceId }));
const record = payload as { sessions?: unknown; result?: { sessions?: unknown } } | null | undefined;
const rows = record?.sessions ?? record?.result?.sessions;
if (!Array.isArray(rows)) return [];
return (rows as SessionState[]).map((row) => ({ ...row, workspaceId: row.workspaceId || workspaceId }));
}
/** Every `sessions[].task` of a `/sessions` payload, tagged with its session id. */
export function sessionTasks(sessions: SessionState[]): StatusTask[] {
return sessions.flatMap((session) =>
(Array.isArray(session.tasks) ? session.tasks : []).map((task) => ({
...task,
sessionId: session.sessionId || "",
})),
);
}
/** Merge task lists, keeping the first entry per task id (live state wins). */
export function mergeTasks(...lists: StatusTask[][]): StatusTask[] {
const byId = new Map<string, StatusTask>();
for (const list of lists) {
for (const task of list) {
const key = task.id || `${task.sessionId}:${task.command}`;
if (!byId.has(key)) byId.set(key, task);
}
}
return [...byId.values()];
}
export function useInfoQuery(enabled = true) {
return useQuery<InfoResponse>({
queryKey: ["info"],
@@ -58,10 +139,17 @@ export function useResourcesQuery() {
});
}
/** `GET /api/v1/workspaces` answers an array; the envelope shape is only a fallback. */
export function normalizeWorkspaces(payload: unknown): WorkspaceInfo[] {
if (Array.isArray(payload)) return payload as WorkspaceInfo[];
const record = payload as { workspaces?: unknown } | null | undefined;
return Array.isArray(record?.workspaces) ? (record.workspaces as WorkspaceInfo[]) : [];
}
export function useWorkspacesQuery() {
return useQuery<WorkspaceInfo[]>({
queryKey: ["workspaces"],
queryFn: ({ signal }) => api.workspaces(signal),
queryFn: async ({ signal }) => normalizeWorkspaces(await apiRequest<unknown>("/api/v1/workspaces", { signal })),
staleTime: 10_000,
});
}
@@ -74,6 +162,44 @@ export function useDevicesQuery() {
});
}
/**
* A fresh pairing code for the connection card. A code is single-use and short
* lived, so each mount mints its own (`gcTime: 0` drops it when the card goes
* away) and `refetch()` is the retry button.
*/
export function usePairCodeQuery(enabled = true) {
return useQuery<PairCodeResponse>({
queryKey: ["pair-code"],
queryFn: ({ signal }) => createPairCode(signal),
enabled,
staleTime: Number.POSITIVE_INFINITY,
gcTime: 0,
retry: false,
});
}
/**
* Sessions (and therefore background tasks) of every registered workspace, so
* the tasks card works after a hard reload instead of only from the chat store.
*/
export function useWorkspaceSessionsQueries(workspaceIds: string[], enabled = true) {
return useQueries({
queries: workspaceIds.map((workspaceId) => ({
queryKey: ["status-sessions", workspaceId],
queryFn: async ({ signal }: { signal: AbortSignal }) =>
normalizeSessions(
await apiRequest<unknown>(`/api/v1/workspaces/${encodeURIComponent(workspaceId)}/sessions`, {
signal,
}),
workspaceId,
),
enabled,
staleTime: 10_000,
retry: false,
})),
});
}
export function useModelsQuery(workspaceId: string | null | undefined) {
return useQuery<ModelsResponse>({
queryKey: ["models", workspaceId ?? ""],
+33 -10
View File
@@ -3,21 +3,33 @@ import { useTranslation } from "react-i18next";
import { RelativeTime } from "@/components/shared/relative-time";
import { StatusDot } from "@/components/ui/status-dot";
import { KV, KVList } from "@/components/ui/kv";
import type { ResourcesResponse } from "@/lib/api";
import type { ServerIdentity } from "@/features/status/server";
import { formatUptime } from "@/features/status/server";
import { formatBytes, formatUptime } from "@/features/status/server";
import { ErrorBlock, LoadingBlock, StatusCard } from "./card-parts";
export interface ServerInfoCardProps {
server: ServerIdentity;
/** `/resources` summary: instance count and the daemon's own RSS total. */
resources: ResourcesResponse | undefined;
loading: boolean;
error: string | null;
onRetry: () => void;
}
/** Card 1 — daemon identity, versions, uptime, bind/port, WS heartbeat. */
export function ServerInfoCard({ server, loading, error, onRetry }: ServerInfoCardProps) {
/**
* Card 1 — the daemon's own identity from `/info` (`daemonId`, `machineId`,
* `platform`, `hostname`, `os`, `version`, `uptimeMs`) plus the `/resources`
* instance and RSS figures. Rows whose field the daemon does not send (kernel,
* plugin version) are omitted rather than rendered as `—`.
*/
export function ServerInfoCard({ server, resources, loading, error, onRetry }: ServerInfoCardProps) {
const { t } = useTranslation();
const instanceCount = resources ? resources.instances.length : null;
const rssBytes = resources && Number.isFinite(resources.totalRssBytes) ? resources.totalRssBytes : null;
const wsLabel = t(server.wsConnected ? "status.connected" : "status.disconnected");
return (
<StatusCard title={t("status.serverInfo")} icon="server">
{error ? (
@@ -26,29 +38,40 @@ export function ServerInfoCard({ server, loading, error, onRetry }: ServerInfoCa
<LoadingBlock rows={8} />
) : (
<KVList>
<KV label={t("connect.name")}>{server.name}</KV>
{server.name && server.name !== server.hostname ? (
<KV label={t("connect.name")}>{server.name}</KV>
) : null}
<KV label="hostname" mono>
{server.hostname}
</KV>
<KV label={t("status.os")}>{server.os}</KV>
<KV label={t("status.piVersion")}>{server.piVersion}</KV>
<KV label={t("status.pluginVersion")}>{server.pluginVersion}</KV>
<KV label={t("status.kernel")} mono>
{server.kernel}
<KV label="platform" mono>
{server.platform}
</KV>
<KV label={t("status.piVersion")}>{server.piVersion}</KV>
<KV label={t("status.uptime")}>{formatUptime(server.uptimeSec)}</KV>
<KV label="daemonId" mono>
{server.daemonId}
</KV>
<KV label="machineId" mono>
{server.machineId}
</KV>
<KV label={t("status.bindAddress")} mono>
{server.bindAddress}
</KV>
<KV label={t("status.port")} mono>
{server.port ?? "—"}
</KV>
<KV label={t("status.instances")}>{instanceCount ?? "—"}</KV>
<KV label="RSS" mono>
{formatBytes(rssBytes)}
</KV>
<KV label={t("status.wsStatus")} valueClassName="status-ws">
<StatusDot
status={server.wsConnected ? "ok" : "err"}
title={t(server.wsConnected ? "status.connected" : "status.disconnected")}
title={wsLabel}
/>
<span>{t(server.wsConnected ? "status.connected" : "status.disconnected")}</span>
<span data-testid="ws-status">{wsLabel}</span>
<span className="muted">{server.wsProto}</span>
</KV>
<KV label={t("status.lastHeartbeat")}>
+35 -13
View File
@@ -3,11 +3,11 @@ import type { WsConnectionState } from "@/lib/ws";
/**
* Optional identity fields the daemon may expose beyond the minimal /info
* contract. The status page degrades to `—` when they are missing: the wire
* contract only guarantees `{v,daemonId,machineId,platform,capabilities,limits}`.
* contract (`{v,daemonId,machineId,platform,hostname,os,version,uptimeMs,
* capabilities,limits}`). The status page degrades to `—` when they are missing.
*/
export interface InfoExtras extends InfoResponse {
os?: string;
pid?: number;
kernel?: string;
uptimeSec?: number;
lastHeartbeat?: number;
@@ -23,6 +23,9 @@ export interface InfoExtras extends InfoResponse {
export interface ServerIdentity {
name: string;
hostname: string;
daemonId: string;
machineId: string;
platform: string;
port: number | null;
endpoint: string;
bindAddress: string;
@@ -31,6 +34,8 @@ export interface ServerIdentity {
pluginVersion: string;
kernel: string;
uptimeSec: number | null;
uptimeMs: number | null;
pid: number | null;
status: "online" | "degraded" | "offline";
wsConnected: boolean;
wsProto: string;
@@ -44,6 +49,15 @@ export interface ServerIdentity {
disk: number | null;
}
function text(value: string | null | undefined, fallback = "—"): string {
const trimmed = String(value ?? "").trim();
return trimmed || fallback;
}
function finite(value: number | null | undefined): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function parseUrl(value: string | null | undefined): URL | null {
if (!value) return null;
try {
@@ -97,29 +111,37 @@ export function deriveServerIdentity({
const localAddress = extras.addresses?.local || `http://127.0.0.1:${port}`;
const networkAddress = extras.addresses?.network || endpointOrigin;
const resolvedStatus = status ?? extras.status ?? (info ? "online" : "offline");
const uptimeMs = finite(extras.uptimeMs);
const uptimeSec =
uptimeMs != null ? Math.floor(uptimeMs / 1000) : typeof extras.uptimeSec === "number" ? extras.uptimeSec : null;
return {
name,
hostname,
daemonId: text(extras.daemonId),
machineId: text(extras.machineId),
platform: text(extras.platform),
port,
endpoint: endpointOrigin,
bindAddress: extras.host?.trim() || hostname,
os: extras.os || extras.platform || "—",
piVersion: extras.version || "—",
pluginVersion: extras.pluginVersion || "—",
kernel: extras.kernel || "—",
uptimeSec: typeof extras.uptimeSec === "number" ? extras.uptimeSec : null,
bindAddress: text(extras.host, hostname),
os: text(extras.os || extras.platform),
piVersion: text(extras.version),
pluginVersion: text(extras.pluginVersion),
kernel: text(extras.kernel),
uptimeSec,
uptimeMs,
pid: finite(extras.pid),
status: resolvedStatus,
wsConnected: wsState === "open",
wsProto: info?.v ? `v${info.v}` : "v1",
lastHeartbeatAt: extras.lastHeartbeat ?? fetchedAt ?? null,
localAddress,
networkAddress,
mdns: extras.mdns || `${hostname}.local`,
mdns: text(extras.mdns, `${hostname}.local`),
pairingCode: extras.pairingCode || extras.pairing?.code || "—",
cpu: typeof extras.cpu === "number" ? extras.cpu : null,
mem: typeof extras.mem === "number" ? extras.mem : null,
disk: typeof extras.disk === "number" ? extras.disk : null,
cpu: finite(extras.cpu),
mem: finite(extras.mem),
disk: finite(extras.disk),
};
}
+13 -8
View File
@@ -1,14 +1,12 @@
import { useTranslation } from "react-i18next";
import { StatusDot, type DotStatus } from "@/components/ui/status-dot";
import type { TaskItem } from "@/lib/protocol";
import type { StatusTask } from "@/features/status/queries";
import { formatDuration } from "@/features/status/server";
import { StatusCard, StatusEmpty } from "./card-parts";
import { ErrorBlock, LoadingBlock, StatusCard, StatusEmpty } from "./card-parts";
export interface StatusTask extends TaskItem {
sessionId: string;
}
export type { StatusTask };
const TASK_DOT: Record<string, DotStatus> = {
running: "busy",
@@ -19,10 +17,13 @@ const TASK_DOT: Record<string, DotStatus> = {
export interface TasksCardProps {
tasks: StatusTask[];
loading?: boolean;
error?: string | null;
onRetry?: () => void;
}
/** Card 5 — background task summary from the live session store. */
export function TasksCard({ tasks }: TasksCardProps) {
/** Card 5 — background tasks from the live session store plus every workspace's sessions. */
export function TasksCard({ tasks, loading = false, error = null, onRetry }: TasksCardProps) {
const { t } = useTranslation();
return (
<StatusCard
@@ -30,7 +31,11 @@ export function TasksCard({ tasks }: TasksCardProps) {
icon="terminal"
headExtra={<span className="card__sub">{t("status.taskCount", { n: tasks.length })}</span>}
>
{tasks.length === 0 ? (
{error ? (
<ErrorBlock message={error} onRetry={onRetry} />
) : loading ? (
<LoadingBlock rows={3} />
) : tasks.length === 0 ? (
<StatusEmpty icon="terminal" title={t("status.noTasksTitle")} text={t("status.noTasksText")} />
) : (
<div className="task-list">
@@ -80,7 +80,7 @@ export function WorkspaceRow({ workspace }: WorkspaceRowProps) {
const count = Math.max(workspace.liveCount || 0, workspace.sessionCount || 0);
return (
<div className="list-row" data-workspace-id={workspace.workspaceId}>
<div className="list-row" data-workspace-id={workspace.workspaceId} data-testid="workspace-row">
<span className="ico list-row__icon">
<Icon name="folder" />
</span>
@@ -95,6 +95,7 @@ export function WorkspaceRow({ workspace }: WorkspaceRowProps) {
<StatusDot status={dot.status} title={t(dot.labelKey)} />
<a
className="btn btn--sm btn--primary list-row__go"
data-testid="workspace-enter"
href={`/chat?workspace=${encodeURIComponent(workspace.workspaceId)}`}
>
{t("workspaces.enter")}