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:
1 parent
5572ac0d84
commit
0ef019f58d
57 files changed
+3549
-684
No files matched your search
@@ -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 ? (
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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}
|
||||
|
||||
@@ -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() };
|
||||
|
||||
|
||||
@@ -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 === " ") {
|
||||
|
||||
@@ -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 === " ") {
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
Reference in new issue
Block a user