feat(web): workspaces, connect and status pages plus the full chat experience
- workspaces list + new-workspace flow (add -> ensure -> navigate), server context bar - connect: manual/pair-code redeem, QR scan with paste fallback, paired summary, disconnect - status: info/health/resources/models/devices/connection cards with 3s visible-only polling - chat: 3/2/1-column layout, session tree, virtualized stream, tool/thinking/todo/batch blocks, composer with queue chips and abort, subagents/todo/tasks panel, attention + diff review modals, history pagination merged with live entries - canonical reducer reused via @protocol alias (no duplicated types) - 63 vitest tests, typecheck + build green, zh/en parity at 411 keys
This commit is contained in:
1 parent
2e5d6d5006
commit
721661177c
61 files changed
+10931
-355
No files matched your search
@@ -0,0 +1,188 @@
|
||||
import type { AttentionItem, SessionState } from "@protocol/types";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { toast } from "@/components/ui/toast";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { diffFilesFromPayload } from "./diff";
|
||||
import { DiffView } from "./diff-view";
|
||||
|
||||
export interface AttentionDialogProps {
|
||||
session: SessionState;
|
||||
onRespond: (item: AttentionItem, response: unknown) => 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.
|
||||
*/
|
||||
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());
|
||||
|
||||
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);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (current) {
|
||||
if (!responded.current) onRemoteResolved(current.requestId);
|
||||
responded.current = false;
|
||||
dismissed.current = null;
|
||||
setCurrent(null);
|
||||
}
|
||||
}, [session.attention, current, onRemoteResolved]);
|
||||
|
||||
useEffect(() => {
|
||||
const timeoutSec = current?.timeoutSec;
|
||||
if (!current || !timeoutSec) {
|
||||
setRemaining(null);
|
||||
return;
|
||||
}
|
||||
const item = current;
|
||||
const deadline = item.receivedAt + timeoutSec * 1_000;
|
||||
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"));
|
||||
}
|
||||
};
|
||||
tick();
|
||||
const timer = setInterval(tick, 500);
|
||||
return () => clearInterval(timer);
|
||||
}, [current, t]);
|
||||
|
||||
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") {
|
||||
if (!current) return;
|
||||
responded.current = true;
|
||||
onRespond(current, response);
|
||||
if (kind === "error") toast.error(message);
|
||||
else if (kind === "info") toast.info(message);
|
||||
else toast.success(message);
|
||||
}
|
||||
|
||||
const options = current?.options?.length
|
||||
? current.options
|
||||
: current?.method === "confirm"
|
||||
? [
|
||||
{ id: "confirm", label: t("chat.allowOnce") },
|
||||
{ id: "deny", label: t("chat.deny") },
|
||||
]
|
||||
: [
|
||||
{ id: "allow-once", label: t("chat.allowOnce") },
|
||||
{ id: "always", label: t("chat.always") },
|
||||
{ id: "deny", label: t("chat.deny") },
|
||||
];
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={Boolean(current)}
|
||||
onOpenChange={() => {
|
||||
/* blocking: answer (or let it time out) before closing */
|
||||
}}
|
||||
title={current?.title ?? t("chat.attentionTitle")}
|
||||
>
|
||||
{current ? (
|
||||
<div className="attn">
|
||||
{current.message ? <p className="attn__q">{current.message}</p> : null}
|
||||
{isDiff ? (
|
||||
<>
|
||||
<div className="muted">{t("chat.diffReview")}</div>
|
||||
{files.length ? (
|
||||
<DiffView
|
||||
files={files}
|
||||
onDecision={(decision, path) =>
|
||||
respond(
|
||||
diffResponse(decision === "accept" ? "Accepted" : "Rejected", path),
|
||||
decision === "accept"
|
||||
? t("chat.acceptedAll", { n: files.length })
|
||||
: t("chat.rejected", { path: path ?? "" }),
|
||||
decision === "accept" ? "success" : "error",
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<div className="muted">{t("chat.noChanges")}</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="attn__options">
|
||||
{options.map((option, index) => (
|
||||
<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",
|
||||
);
|
||||
}}
|
||||
>
|
||||
{option.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{current.timeoutSec ? (
|
||||
<>
|
||||
<Progress
|
||||
value={remaining ?? current.timeoutSec}
|
||||
max={current.timeoutSec}
|
||||
tone="warn"
|
||||
/>
|
||||
<div className="row attn__meta">
|
||||
<span className="muted">{t("chat.attentionTimeout")}</span>
|
||||
<span className={cn("mono", remaining !== null && remaining <= 5 && "attn__countdown--urgent")}>
|
||||
{remaining ?? current.timeoutSec}s
|
||||
</span>
|
||||
<div className="spacer" />
|
||||
<Badge tone="warn">{current.method}</Badge>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="row attn__meta">
|
||||
<div className="spacer" />
|
||||
<Badge tone="warn">{current.method}</Badge>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
import type { Batch, Block, Entry, TodoItem } from "@protocol/types";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { RelativeTime } from "@/components/shared/relative-time";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { fileDiff } from "./diff";
|
||||
import { DiffView } from "./diff-view";
|
||||
import {
|
||||
formatClock,
|
||||
formatDuration,
|
||||
toolArgsText,
|
||||
toolDiffSource,
|
||||
toolOutputText,
|
||||
toolSummary,
|
||||
} from "./format";
|
||||
|
||||
export interface EntryBlockProps {
|
||||
entry: Entry;
|
||||
turnStart?: boolean;
|
||||
}
|
||||
|
||||
function MessageMeta({ entry }: { entry: Entry }) {
|
||||
const { t } = useTranslation();
|
||||
const user = entry.role === "user";
|
||||
return (
|
||||
<div className="msg__meta">
|
||||
<span className={cn("who", user ? "who--user" : "who--agent")}>
|
||||
{user ? t("chat.you") : entry.role === "notice" ? t("chat.subReport") : "pi2"}
|
||||
</span>
|
||||
{user ? (
|
||||
<RelativeTime ts={entry.ts} className="muted msg__time" />
|
||||
) : (
|
||||
<span className="muted msg__time">{formatClock(entry.ts)}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ThinkingBlock({ text }: { text: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={cn("thinking", open && "open")}
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
>
|
||||
<span className="thinking__tag">
|
||||
<Icon name="clock" />
|
||||
{t("chat.thinking")}
|
||||
</span>
|
||||
<span className="thinking__text">{text}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function ToolBody({ block }: { block: Extract<Block, { type: "tool" }> }) {
|
||||
const { t } = useTranslation();
|
||||
const args = toolArgsText(block);
|
||||
const output = toolOutputText(block);
|
||||
const source = toolDiffSource(block);
|
||||
const diff = source ? [fileDiff(source.path, source.before, source.after)] : [];
|
||||
return (
|
||||
<div className="tool__body">
|
||||
{args ? (
|
||||
<div className="tool__section">
|
||||
<div className="tool__label muted">{t("chat.details")}</div>
|
||||
<pre className="mono tool__pre">{args}</pre>
|
||||
</div>
|
||||
) : null}
|
||||
{output ? (
|
||||
<div className="tool__section">
|
||||
<div className="tool__label muted">{t("chat.output")}</div>
|
||||
<pre className="mono tool__pre">{output}</pre>
|
||||
</div>
|
||||
) : null}
|
||||
{!args && !output ? <pre className="mono tool__pre muted">{t("chat.noOutput")}</pre> : null}
|
||||
{diff.length ? <DiffView files={diff} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ToolBlock({ block }: { block: Extract<Block, { type: "tool" }> }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const running = block.state === "pending" || block.state === "running";
|
||||
const done = block.state === "done";
|
||||
const error = block.state === "error";
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"tool card",
|
||||
done && "tool--done",
|
||||
error && "tool--error",
|
||||
open && "open",
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="tool__head"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
>
|
||||
<span className={cn("tool__ico", running && "tool__ico--running")}>
|
||||
{running ? <Spinner /> : <Icon name={error ? "alert" : done ? "check" : "dot"} />}
|
||||
</span>
|
||||
<span className="tool__name mono">{block.name}</span>
|
||||
<span className="tool__sum muted truncate">{toolSummary(block)}</span>
|
||||
{block.durationMs != null ? (
|
||||
<span className="tool__dur muted">· {formatDuration(block.durationMs)}</span>
|
||||
) : null}
|
||||
<span className="tool__caret">
|
||||
<Icon name="chevron-down" />
|
||||
</span>
|
||||
</button>
|
||||
{open ? <ToolBody block={block} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TodoRow({ item }: { item: TodoItem }) {
|
||||
const completed = item.status === "completed";
|
||||
const active = item.status === "in_progress";
|
||||
return (
|
||||
<div className={cn("todo__row", active && "is-active", completed && "is-done")}>
|
||||
<span
|
||||
className={cn(
|
||||
"todo__ico",
|
||||
completed && "todo__ico--done",
|
||||
active && "todo__ico--progress",
|
||||
!completed && !active && "todo__ico--pending",
|
||||
)}
|
||||
aria-hidden="true"
|
||||
>
|
||||
{completed ? "✓" : active ? "◐" : "○"}
|
||||
</span>
|
||||
<span className="todo__txt">
|
||||
<span className="todo__content">{item.content}</span>
|
||||
{active && item.activeForm ? <span className="todo__active">{item.activeForm}</span> : null}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export interface TodoListProps {
|
||||
items: TodoItem[];
|
||||
limit?: number;
|
||||
idPrefix: string;
|
||||
}
|
||||
|
||||
export function TodoList({ items, limit = 5, idPrefix }: TodoListProps) {
|
||||
const { t } = useTranslation();
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const shown = expanded ? items : items.slice(0, limit);
|
||||
return (
|
||||
<div className="todo__list">
|
||||
{shown.map((item, index) => (
|
||||
<TodoRow key={`${idPrefix}-${index}`} item={item} />
|
||||
))}
|
||||
{items.length > limit ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--sm btn--ghost todo__more"
|
||||
onClick={() => setExpanded((value) => !value)}
|
||||
>
|
||||
{expanded ? t("chat.collapse") : t("chat.moreItems", { n: items.length - limit })}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TodoBlock({ items }: { items: TodoItem[] }) {
|
||||
const { t } = useTranslation();
|
||||
const completed = items.filter((item) => item.status === "completed").length;
|
||||
return (
|
||||
<div className="todo card">
|
||||
<div className="todo__head">
|
||||
<Icon name="todo" />
|
||||
<span>{`${t("chat.tabTodo")} · ${completed}/${items.length}`}</span>
|
||||
<div className="spacer" />
|
||||
<span className="muted todo__readonly">{t("common.readonly")}</span>
|
||||
</div>
|
||||
<Progress value={completed} max={items.length || 1} />
|
||||
<TodoList items={items} idPrefix="stream-todo" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const BATCH_GLYPH: Record<string, [string, string]> = {
|
||||
ok: ["✓", "batch__ico--ok"],
|
||||
failed: ["✗", "batch__ico--err"],
|
||||
cancelled: ["⊘", "batch__ico--muted"],
|
||||
running: ["◐", "batch__ico--warn"],
|
||||
spawning: ["◐", "batch__ico--warn"],
|
||||
queued: ["·", "batch__ico--muted"],
|
||||
};
|
||||
|
||||
function batchSummary(batch: Batch) {
|
||||
const items = batch.items ?? [];
|
||||
if (batch.summary) return batch.summary;
|
||||
const counts = { total: items.length, done: 0, ok: 0, failed: 0, cancelled: 0, running: 0 };
|
||||
for (const item of items) {
|
||||
if (item.status === "ok") {
|
||||
counts.ok += 1;
|
||||
counts.done += 1;
|
||||
} else if (item.status === "failed") {
|
||||
counts.failed += 1;
|
||||
counts.done += 1;
|
||||
} else if (item.status === "cancelled") {
|
||||
counts.cancelled += 1;
|
||||
counts.done += 1;
|
||||
} else {
|
||||
counts.running += 1;
|
||||
}
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
export interface BatchBlockProps {
|
||||
batch: Batch;
|
||||
onOpenSubagent?: (name: string) => void;
|
||||
canOpen?: (name: string) => boolean;
|
||||
}
|
||||
|
||||
export function BatchBlock({ batch, onOpenSubagent, canOpen }: BatchBlockProps) {
|
||||
const { t } = useTranslation();
|
||||
const summary = batchSummary(batch);
|
||||
const items = batch.items ?? [];
|
||||
return (
|
||||
<div className="batch card">
|
||||
<div className="batch__head row">
|
||||
<Icon name="branch" />
|
||||
<span>{t("chat.batchDispatch", { done: summary.done, total: summary.total })}</span>
|
||||
<div className="spacer" />
|
||||
{summary.running ? <Badge tone="info">{t("chat.batchRunning", { n: summary.running })}</Badge> : null}
|
||||
{summary.failed ? <Badge tone="err">{t("chat.batchFailed", { n: summary.failed })}</Badge> : null}
|
||||
</div>
|
||||
<div className="batch__list">
|
||||
{items.map((item, index) => {
|
||||
const name = item.name ?? item.ref ?? String(index);
|
||||
const target = Boolean(canOpen?.(name));
|
||||
const [glyph, cls] = BATCH_GLYPH[item.status] ?? ["·", "batch__ico--muted"];
|
||||
return (
|
||||
<div
|
||||
key={`${item.ref}-${index}`}
|
||||
className={cn("batch__row", target && "is-link")}
|
||||
role={target ? "button" : undefined}
|
||||
tabIndex={target ? 0 : undefined}
|
||||
title={target ? t("chat.viewSubagent", { name }) : undefined}
|
||||
onClick={() => {
|
||||
if (target) onOpenSubagent?.(name);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (target && (event.key === "Enter" || event.key === " ")) {
|
||||
event.preventDefault();
|
||||
onOpenSubagent?.(name);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span className="batch__tree muted">├─</span>
|
||||
<span className={cn("batch__ico", cls)}>{glyph}</span>
|
||||
<span className="batch__name truncate">{name}</span>
|
||||
{item.error ? <span className="muted truncate">{item.error}</span> : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ErrorBlock({ text }: { text: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="msg__error">
|
||||
<div className="msg__error-meta">
|
||||
<span className="who who--err">
|
||||
<Icon name="alert" />
|
||||
{t("chat.error")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="msg__text">{text}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function EntryBlock({ entry, turnStart }: EntryBlockProps) {
|
||||
const lastTextIndex = entry.blocks.reduce(
|
||||
(last, block, index) => (block.type === "text" ? index : last),
|
||||
-1,
|
||||
);
|
||||
return (
|
||||
<article className={cn("msg", `msg--${entry.role}`, turnStart && "turn-start")}>
|
||||
<MessageMeta entry={entry} />
|
||||
{entry.blocks.map((block, index) => {
|
||||
if (block.type === "text") {
|
||||
return (
|
||||
<div
|
||||
key={`${entry.id}-t-${index}`}
|
||||
className={cn("msg__text", !entry.done && index === lastTextIndex && "streaming")}
|
||||
>
|
||||
{block.text}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (block.type === "thinking") {
|
||||
return <ThinkingBlock key={`${entry.id}-k-${index}`} text={block.text} />;
|
||||
}
|
||||
if (block.type === "tool") {
|
||||
return <ToolBlock key={`${entry.id}-x-${index}`} block={block} />;
|
||||
}
|
||||
return <ErrorBlock key={`${entry.id}-e-${index}`} text={block.text} />;
|
||||
})}
|
||||
{entry.images?.length ? (
|
||||
<div className="msg__images">
|
||||
{entry.images.map((image, index) => (
|
||||
<img
|
||||
key={`${entry.id}-img-${index}`}
|
||||
className="msg__img"
|
||||
src={`data:${image.mimeType};base64,${image.data}`}
|
||||
alt=""
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import type { CommandRequest, ModelRef, ThinkingLevel } from "@protocol/types";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
export interface PromptImage {
|
||||
mimeType: string;
|
||||
data: string;
|
||||
}
|
||||
|
||||
export interface ChatCommand extends CommandRequest {
|
||||
method: string;
|
||||
}
|
||||
|
||||
function requestId(): string | undefined {
|
||||
try {
|
||||
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
|
||||
} catch {
|
||||
/* older browsers */
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function command(method: string, sessionId: string | undefined, params?: Record<string, unknown>): ChatCommand {
|
||||
const clientRequestId = requestId();
|
||||
return {
|
||||
method,
|
||||
...(sessionId ? { sessionId } : {}),
|
||||
...(params ? { params } : {}),
|
||||
...(clientRequestId ? { clientRequestId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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).
|
||||
*/
|
||||
export const chatCommands = {
|
||||
sendPrompt: (sessionId: string, text: string, images: PromptImage[] = []): ChatCommand =>
|
||||
command("prompt.send", sessionId, {
|
||||
text,
|
||||
mode: "queue",
|
||||
...(images.length ? { images } : {}),
|
||||
}),
|
||||
|
||||
abort: (sessionId: string): ChatCommand => command("prompt.abort", sessionId, {}),
|
||||
|
||||
removeQueued: (sessionId: string, queueId: string): ChatCommand => command("queue.remove", sessionId, { queueId }),
|
||||
|
||||
setQueueSteer: (sessionId: string, queueId: string, steer: boolean): ChatCommand =>
|
||||
command("queue.setSteer", sessionId, { queueId, steer }),
|
||||
|
||||
setModel: (sessionId: string, model: ModelRef): ChatCommand =>
|
||||
command("session.setModel", sessionId, { provider: model.provider, id: model.id }),
|
||||
|
||||
setThinking: (sessionId: string, level: ThinkingLevel): ChatCommand =>
|
||||
command("session.setThinking", sessionId, { level }),
|
||||
|
||||
renameSession: (sessionId: string, name: string): ChatCommand => command("session.rename", sessionId, { name }),
|
||||
|
||||
closeSession: (sessionId: string): ChatCommand => command("session.close", sessionId, { mode: "close" }),
|
||||
|
||||
createSession: (workspaceId: string): ChatCommand => command("session.create", undefined, { workspaceId }),
|
||||
|
||||
respondAttention: (sessionId: string, requestIdValue: string, response: unknown): ChatCommand =>
|
||||
command("attention.respond", sessionId, { requestId: requestIdValue, response }),
|
||||
|
||||
dispatchSubagent: (
|
||||
sessionId: string,
|
||||
input: {
|
||||
task: string;
|
||||
name?: string;
|
||||
model?: ModelRef;
|
||||
thinking?: ThinkingLevel;
|
||||
wait?: boolean;
|
||||
cancelSiblingsOnFail?: boolean;
|
||||
},
|
||||
): 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 }
|
||||
: {}),
|
||||
}),
|
||||
|
||||
steerSubagent: (sessionId: string, target: string, message: string): ChatCommand =>
|
||||
command("subagent.steer", sessionId, { target, message }),
|
||||
|
||||
readSubagent: (sessionId: string, target: string): ChatCommand =>
|
||||
command("subagent.read", sessionId, { target }),
|
||||
|
||||
stopTask: (sessionId: string, taskId: string): ChatCommand => command("task.stop", sessionId, { taskId }),
|
||||
|
||||
taskOutput: (sessionId: string, taskId: string): ChatCommand => command("task.output", sessionId, { taskId }),
|
||||
};
|
||||
|
||||
export type CommandResult = { accepted?: boolean; disposition?: string; [key: string]: unknown };
|
||||
|
||||
/** Execute one command; errors surface as `ApiError` with a stable code. */
|
||||
export async function runCommand(command: ChatCommand, signal?: AbortSignal): Promise<CommandResult> {
|
||||
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 });
|
||||
}
|
||||
|
||||
export function promptImage(file: File): Promise<PromptImage> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onerror = () => reject(reader.error ?? new Error("cannot read file"));
|
||||
reader.onload = () => {
|
||||
const result = String(reader.result ?? "");
|
||||
const comma = result.indexOf(",");
|
||||
if (comma < 0) {
|
||||
reject(new Error("cannot read file"));
|
||||
return;
|
||||
}
|
||||
resolve({ mimeType: file.type || "image/png", data: result.slice(comma + 1) });
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
import type { ModelRef, SessionState, ThinkingLevel } from "@protocol/types";
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Button } from "@/components/ui/button";
|
||||
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 type { ModelGroup } from "./data";
|
||||
import { withCurrentModel } from "./data";
|
||||
import { THINKING_LEVELS } from "./format";
|
||||
import type { Attachment } from "./store";
|
||||
|
||||
export interface ComposerProps {
|
||||
session: SessionState | null;
|
||||
models: ModelGroup[];
|
||||
connected: boolean;
|
||||
paired?: boolean;
|
||||
sending?: { text: string } | null;
|
||||
onSend: (text: string, images: PromptImage[]) => void;
|
||||
onAbort: () => void;
|
||||
onRemoveQueue: (id: string) => void;
|
||||
onSetSteer: (id: string, steer: boolean) => void;
|
||||
onSetModel: (model: ModelRef) => void;
|
||||
onSetThinking: (level: ThinkingLevel) => void;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function attachmentId(file: File): string {
|
||||
return `${file.name}-${file.size}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
|
||||
}
|
||||
|
||||
/** Bottom composer: auto-growing textarea, queue chips, model/thinking, send/abort. */
|
||||
export function Composer({
|
||||
session,
|
||||
models,
|
||||
connected,
|
||||
paired = true,
|
||||
sending,
|
||||
onSend,
|
||||
onAbort,
|
||||
onRemoveQueue,
|
||||
onSetSteer,
|
||||
onSetModel,
|
||||
onSetThinking,
|
||||
disabled = false,
|
||||
className,
|
||||
}: ComposerProps) {
|
||||
const { t } = useTranslation();
|
||||
const [text, setText] = useState("");
|
||||
const [attachments, setAttachments] = useState<Attachment[]>([]);
|
||||
const [attachOpen, setAttachOpen] = useState(false);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
const fileRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
const enabled = Boolean(session) && connected && !disabled;
|
||||
const busy = session ? session.status === "busy" || session.status === "compacting" : false;
|
||||
const queue = session?.queue ?? [];
|
||||
const model = session?.model ?? null;
|
||||
const thinking = session?.thinking ?? "off";
|
||||
const groups = withCurrentModel(models, model);
|
||||
const hint = !paired ? t("chat.unpairedHint") : !connected ? t("chat.offlineHint") : null;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const element = textareaRef.current;
|
||||
if (!element) return;
|
||||
element.style.height = "auto";
|
||||
const max = 5 * 24;
|
||||
element.style.height = `${Math.min(element.scrollHeight, max)}px`;
|
||||
element.style.overflowY = element.scrollHeight > max ? "auto" : "hidden";
|
||||
}, [text]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
textareaRef.current?.focus({ preventScroll: true });
|
||||
}, [enabled]);
|
||||
|
||||
function submit() {
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed || !enabled) return;
|
||||
const images = attachments.map(({ mimeType, data }) => ({ mimeType, data }));
|
||||
setText("");
|
||||
setAttachments([]);
|
||||
onSend(trimmed, images);
|
||||
}
|
||||
|
||||
async function addFiles(files: FileList | File[] | null) {
|
||||
if (!files) return;
|
||||
for (const file of Array.from(files)) {
|
||||
if (!file.type.startsWith("image/")) continue;
|
||||
try {
|
||||
const image = await promptImage(file);
|
||||
setAttachments((current) => [
|
||||
...current,
|
||||
{
|
||||
id: attachmentId(file),
|
||||
name: file.name,
|
||||
mimeType: image.mimeType,
|
||||
data: image.data,
|
||||
preview: `data:${image.mimeType};base64,${image.data}`,
|
||||
},
|
||||
]);
|
||||
toast(t("chat.attachmentAdded", { name: file.name }));
|
||||
} catch {
|
||||
toast.error(t("chat.attachmentFailed", { name: file.name }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("composer", className)}>
|
||||
{queue.length || sending ? (
|
||||
<div className="composer__queue">
|
||||
{sending ? (
|
||||
<Chip className="chip--queue chip--sending">
|
||||
<Icon name="clock" />
|
||||
<span>{t("chat.sending")}</span>
|
||||
{sending.text ? <span className="truncate">{sending.text}</span> : null}
|
||||
</Chip>
|
||||
) : null}
|
||||
{queue.map((item) => (
|
||||
<Chip key={item.id} className="chip--queue">
|
||||
<Icon name="clock" />
|
||||
<span>{t("state.queued")}</span>
|
||||
<span className="truncate" title={item.text}>
|
||||
{item.text}
|
||||
</span>
|
||||
<label className="q-steer-wrap">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="q-steer"
|
||||
checked={item.steer}
|
||||
aria-label={t("chat.steer")}
|
||||
onChange={(event) => onSetSteer(item.id, event.target.checked)}
|
||||
/>
|
||||
<span>{t("chat.steer")}</span>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
title={t("chat.removeQueued")}
|
||||
aria-label={t("chat.removeQueued")}
|
||||
onClick={() => onRemoveQueue(item.id)}
|
||||
>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
</Chip>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className={cn("composer__box", !enabled && "is-disabled")}>
|
||||
{attachments.length ? (
|
||||
<div className="composer__attachments">
|
||||
{attachments.map((attachment) => (
|
||||
<span key={attachment.id} className="composer__att">
|
||||
<img src={attachment.preview} alt="" className="composer__att-img" />
|
||||
<span className="truncate">{attachment.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
aria-label={t("chat.removeAttachment")}
|
||||
title={t("chat.removeAttachment")}
|
||||
onClick={() =>
|
||||
setAttachments((current) =>
|
||||
current.filter((item) => item.id !== attachment.id),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
className="textarea composer__ta"
|
||||
rows={1}
|
||||
value={text}
|
||||
placeholder={t("chat.composerPlaceholder")}
|
||||
aria-label={t("chat.composerAria")}
|
||||
disabled={!enabled}
|
||||
onChange={(event) => setText(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return;
|
||||
event.preventDefault();
|
||||
submit();
|
||||
}}
|
||||
/>
|
||||
<div className="composer__bar">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--icon btn--ghost"
|
||||
title={t("chat.addAttachment")}
|
||||
aria-label={t("chat.addAttachment")}
|
||||
disabled={!enabled}
|
||||
onClick={() => setAttachOpen(true)}
|
||||
>
|
||||
<Icon name="plus" />
|
||||
</button>
|
||||
<select
|
||||
className="select composer__sel"
|
||||
aria-label={t("chat.model")}
|
||||
value={model ? `${model.provider}/${model.id}` : ""}
|
||||
disabled={!enabled || !groups.length}
|
||||
onChange={(event) => {
|
||||
const slash = event.target.value.indexOf("/");
|
||||
if (slash <= 0) return;
|
||||
onSetModel({
|
||||
provider: event.target.value.slice(0, slash),
|
||||
id: event.target.value.slice(slash + 1),
|
||||
});
|
||||
}}
|
||||
>
|
||||
{groups.length ? null : (
|
||||
<option value="">{model ? `${model.provider}/${model.id}` : t("chat.model")}</option>
|
||||
)}
|
||||
{groups.map((group) => (
|
||||
<optgroup key={group.provider} label={group.provider}>
|
||||
{group.models.map((item) => (
|
||||
<option key={`${group.provider}/${item.id}`} value={`${group.provider}/${item.id}`}>
|
||||
{item.id}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
className="select composer__sel"
|
||||
aria-label={t("chat.thinkingAria")}
|
||||
value={thinking}
|
||||
disabled={!enabled}
|
||||
onChange={(event) => onSetThinking(event.target.value as ThinkingLevel)}
|
||||
>
|
||||
{THINKING_LEVELS.map((level) => (
|
||||
<option key={level} value={level}>
|
||||
{level}
|
||||
</option>
|
||||
))}
|
||||
</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>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{hint ? (
|
||||
<div className="composer__hint" role="status">
|
||||
<Icon name="alert" />
|
||||
{hint}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<Modal
|
||||
open={attachOpen}
|
||||
onOpenChange={setAttachOpen}
|
||||
title={t("chat.attachTitle")}
|
||||
footer={
|
||||
<Button variant="primary" onClick={() => setAttachOpen(false)}>
|
||||
{t("common.close")}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div className="stack">
|
||||
<div
|
||||
className={cn("drop-zone", dragging && "dragover")}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => fileRef.current?.click()}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
fileRef.current?.click();
|
||||
}
|
||||
}}
|
||||
onDragOver={(event) => {
|
||||
event.preventDefault();
|
||||
setDragging(true);
|
||||
}}
|
||||
onDragLeave={() => setDragging(false)}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault();
|
||||
setDragging(false);
|
||||
void addFiles(event.dataTransfer.files);
|
||||
}}
|
||||
>
|
||||
<Icon name="plus" />
|
||||
<div>{t("chat.dropHint")}</div>
|
||||
<div className="muted">{t("chat.dropNote")}</div>
|
||||
</div>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
hidden
|
||||
onChange={(event) => {
|
||||
void addFiles(event.target.files);
|
||||
event.target.value = "";
|
||||
}}
|
||||
/>
|
||||
{attachments.length ? (
|
||||
<div className="att-list">
|
||||
{attachments.map((attachment) => (
|
||||
<div className="att-file" key={attachment.id}>
|
||||
<img src={attachment.preview} alt="" className="att-thumb" />
|
||||
<span className="grow truncate">{attachment.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
title={t("chat.removeAttachment")}
|
||||
aria-label={t("chat.removeAttachment")}
|
||||
onClick={() =>
|
||||
setAttachments((current) =>
|
||||
current.filter((item) => item.id !== attachment.id),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="muted composer__note">{t("chat.attachNote")}</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
import type { ModelRef, SessionEvent, SessionState, WorkspaceInfo } from "@protocol/types";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
|
||||
import { api, apiRequest, getDeviceToken } from "@/lib/api";
|
||||
import { projectEntries, snapshotEntries } from "@/lib/entry-projection";
|
||||
import { defaultWsUrl, PiWsClient, type WsConnectionState } from "@/lib/ws";
|
||||
import { useConnectionStore } from "@/stores/connection";
|
||||
import { useSessionsStore } from "@/stores/sessions";
|
||||
import { useWorkspacesStore } from "@/stores/workspaces";
|
||||
import {
|
||||
applySessionEvent,
|
||||
emptySessionState,
|
||||
normalizeSessionSummary,
|
||||
normalizeSessionsPayload,
|
||||
normalizeSnapshotState,
|
||||
} from "./session-state";
|
||||
import { useChatStore } from "./store";
|
||||
|
||||
export const EMPTY_SESSIONS: SessionState[] = [];
|
||||
|
||||
export interface ModelChoice {
|
||||
id: string;
|
||||
contextWindow?: number;
|
||||
reasoning?: boolean;
|
||||
}
|
||||
|
||||
export interface ModelGroup {
|
||||
provider: string;
|
||||
models: ModelChoice[];
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** Accepts the several shapes `workspace.query{kind:"models"}` has used. */
|
||||
export function normalizeModels(raw: unknown): ModelGroup[] {
|
||||
const record = rec(raw);
|
||||
const list = Array.isArray(raw)
|
||||
? raw
|
||||
: Array.isArray(record?.providers)
|
||||
? record.providers
|
||||
: Array.isArray(record?.models)
|
||||
? record.models
|
||||
: Array.isArray(record?.groups)
|
||||
? record.groups
|
||||
: [];
|
||||
|
||||
const groups = new Map<string, ModelChoice[]>();
|
||||
const add = (provider: string, model: unknown) => {
|
||||
const item = rec(model);
|
||||
const id = str(item?.id ?? item?.model ?? item?.modelId) ?? str(model);
|
||||
if (!id) return;
|
||||
const choices = groups.get(provider) ?? [];
|
||||
if (!choices.some((choice) => choice.id === id)) {
|
||||
choices.push({
|
||||
id,
|
||||
...(num(item?.contextWindow) !== undefined ? { contextWindow: num(item?.contextWindow) } : {}),
|
||||
...(item?.reasoning === true ? { reasoning: true } : {}),
|
||||
});
|
||||
}
|
||||
groups.set(provider, choices);
|
||||
};
|
||||
|
||||
for (const entry of list) {
|
||||
const item = rec(entry);
|
||||
if (!item) {
|
||||
if (typeof entry === "string") add("pi", entry);
|
||||
continue;
|
||||
}
|
||||
const provider = str(item.provider ?? item.name ?? item.id) ?? "pi";
|
||||
const models = Array.isArray(item.models) ? item.models : [];
|
||||
if (models.length) {
|
||||
for (const model of models) add(provider, model);
|
||||
} else if (str(item.id ?? item.model ?? item.modelId)) {
|
||||
// Flat list: `{provider, id, contextWindow}`.
|
||||
add(str(item.provider) ?? "pi", item);
|
||||
}
|
||||
}
|
||||
|
||||
return [...groups.entries()]
|
||||
.filter(([, models]) => models.length > 0)
|
||||
.map(([provider, models]) => ({
|
||||
provider,
|
||||
models: models.sort((a, b) => a.id.localeCompare(b.id)),
|
||||
}))
|
||||
.sort((a, b) => a.provider.localeCompare(b.provider));
|
||||
}
|
||||
|
||||
/** Ensure the active session's model is selectable even when the list is stale. */
|
||||
export function withCurrentModel(groups: ModelGroup[], model: ModelRef | null): ModelGroup[] {
|
||||
if (!model) return groups;
|
||||
if (groups.some((group) => group.provider === model.provider && group.models.some((item) => item.id === model.id))) {
|
||||
return groups;
|
||||
}
|
||||
const next = groups.map((group) => ({ ...group, models: [...group.models] }));
|
||||
const existing = next.find((group) => group.provider === model.provider);
|
||||
if (existing) existing.models.unshift({ id: model.id });
|
||||
else next.unshift({ provider: model.provider, models: [{ id: model.id }] });
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Workspaces for the chat sidebar; refreshes the shared store. */
|
||||
export function useChatWorkspaces(enabled: boolean): { workspaces: WorkspaceInfo[]; loading: boolean; error: unknown } {
|
||||
const setWorkspaces = useWorkspacesStore((state) => state.setWorkspaces);
|
||||
const query = useQuery({
|
||||
queryKey: ["chat-workspaces"],
|
||||
queryFn: ({ signal }) => api.workspaces(signal),
|
||||
enabled,
|
||||
staleTime: 30_000,
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (query.data) setWorkspaces(query.data);
|
||||
}, [query.data, setWorkspaces]);
|
||||
|
||||
const workspaces = useWorkspacesStore((state) => state.items);
|
||||
return { workspaces, loading: query.isLoading, error: query.error };
|
||||
}
|
||||
|
||||
/** Sessions of one workspace, merged into the shared store (live state wins). */
|
||||
export function useChatSessions(workspaceId: string | undefined, enabled: boolean): SessionState[] {
|
||||
const query = useQuery({
|
||||
queryKey: ["chat-sessions", workspaceId],
|
||||
queryFn: ({ signal }) =>
|
||||
apiRequest<unknown>(`/api/v1/workspaces/${encodeURIComponent(workspaceId ?? "")}/sessions`, { signal }),
|
||||
enabled: enabled && Boolean(workspaceId),
|
||||
staleTime: 5_000,
|
||||
refetchInterval: 15_000,
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!workspaceId || !query.data) return;
|
||||
const current = useSessionsStore.getState();
|
||||
const existing = current.byWorkspace[workspaceId] ?? [];
|
||||
const next = normalizeSessionsPayload(query.data, workspaceId, existing);
|
||||
current.setSessions(workspaceId, next);
|
||||
}, [workspaceId, query.data]);
|
||||
|
||||
return useSessionsStore((state) => (workspaceId ? (state.byWorkspace[workspaceId] ?? EMPTY_SESSIONS) : EMPTY_SESSIONS));
|
||||
}
|
||||
|
||||
/** Model list for the composer and dispatch modal. */
|
||||
export function useChatModels(workspaceId: string | undefined, enabled: boolean): ModelGroup[] {
|
||||
const query = useQuery({
|
||||
queryKey: ["chat-models", workspaceId],
|
||||
queryFn: ({ signal }) =>
|
||||
apiRequest<unknown>(`/api/v1/models?workspaceId=${encodeURIComponent(workspaceId ?? "")}`, { signal }),
|
||||
enabled: enabled && Boolean(workspaceId),
|
||||
staleTime: 60_000,
|
||||
retry: 1,
|
||||
});
|
||||
return useMemo(() => normalizeModels(query.data), [query.data]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to the workspace's sessions and reduce `snapshot` / `event` frames
|
||||
* into the shared sessions store. The canonical reducer is imported from
|
||||
* `@protocol/reducer`; nothing state-related is reimplemented here.
|
||||
*/
|
||||
export function useChatSocket(workspaceId: string | undefined, sessionIds: string[], enabled: boolean): void {
|
||||
const clientRef = useRef<PiWsClient | null>(null);
|
||||
const setWsState = useConnectionStore((state) => state.setWsState);
|
||||
const idsKey = sessionIds.join("|");
|
||||
|
||||
useEffect(() => {
|
||||
if (!workspaceId || !enabled) return;
|
||||
const client = new PiWsClient({
|
||||
url: defaultWsUrl(),
|
||||
token: getDeviceToken(),
|
||||
handlers: {
|
||||
onState: (state: WsConnectionState) => {
|
||||
setWsState(state);
|
||||
},
|
||||
onSnapshot: (message) => {
|
||||
const state = normalizeSnapshotState(message.sessionId, workspaceId, message.payload);
|
||||
if (!state.entries.length) {
|
||||
const raw = snapshotEntries(message.payload);
|
||||
if (raw.length) state.entries = projectEntries(raw);
|
||||
}
|
||||
const store = useSessionsStore.getState();
|
||||
store.upsertSession(state);
|
||||
},
|
||||
onEvent: (message) => {
|
||||
const payload = rec(message.payload);
|
||||
const event = rec(payload?.event) ?? payload;
|
||||
if (!event || typeof event.type !== "string") return;
|
||||
const sessionId = message.sessionId;
|
||||
const store = useSessionsStore.getState();
|
||||
const current = store.getSession(sessionId) ?? emptySessionState({ sessionId, workspaceId });
|
||||
const next = applySessionEvent(current, event as unknown as SessionEvent);
|
||||
store.upsertSession(next);
|
||||
},
|
||||
onResyncRequired: (frame) => {
|
||||
const sessionId = str(frame.sessionId);
|
||||
if (!sessionId) return;
|
||||
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);
|
||||
},
|
||||
onError: () => {
|
||||
// Reconnect/backoff state is surfaced through `onState`.
|
||||
},
|
||||
},
|
||||
});
|
||||
clientRef.current = client;
|
||||
client.connect();
|
||||
return () => {
|
||||
clientRef.current = null;
|
||||
client.close();
|
||||
};
|
||||
}, [workspaceId, enabled, setWsState]);
|
||||
|
||||
useEffect(() => {
|
||||
const client = clientRef.current;
|
||||
if (!client) return;
|
||||
const ids = idsKey ? idsKey.split("|").filter(Boolean) : [];
|
||||
if (ids.length) client.subscribe(ids);
|
||||
}, [idsKey, workspaceId]);
|
||||
}
|
||||
|
||||
/** The selected session, falling back to the first session of the workspace. */
|
||||
export function useActiveSession(
|
||||
sessionId: string | null | undefined,
|
||||
sessions: SessionState[],
|
||||
): SessionState | undefined {
|
||||
return useMemo(() => {
|
||||
if (sessionId) {
|
||||
const match = sessions.find((session) => session.sessionId === sessionId);
|
||||
if (match) return match;
|
||||
}
|
||||
return sessions[0];
|
||||
}, [sessions, sessionId]);
|
||||
}
|
||||
|
||||
export function mergeSessionSummaries(existing: SessionState | undefined, raw: unknown, workspaceId: string): SessionState {
|
||||
return normalizeSessionSummary(raw, workspaceId, existing);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { DiffFile } from "./diff";
|
||||
|
||||
export interface DiffViewProps {
|
||||
files: DiffFile[];
|
||||
/** When provided, render per-file + accept-all/reject-all actions. */
|
||||
onDecision?: (decision: "accept" | "reject", path?: string) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** Unified diff accordion (tool cards + pre-execution attention review). */
|
||||
export function DiffView({ files, onDecision, className }: DiffViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState<Record<string, boolean>>(() => {
|
||||
const initial: Record<string, boolean> = {};
|
||||
files.forEach((file, index) => {
|
||||
initial[file.path] = index === 0;
|
||||
});
|
||||
return initial;
|
||||
});
|
||||
|
||||
if (!files.length) return null;
|
||||
|
||||
return (
|
||||
<div className={cn("diff", className)}>
|
||||
{files.map((file) => {
|
||||
const expanded = open[file.path] ?? false;
|
||||
return (
|
||||
<div key={file.path} className={cn("diff__file", expanded && "open")}>
|
||||
<button
|
||||
type="button"
|
||||
className="diff__head"
|
||||
aria-expanded={expanded}
|
||||
onClick={() => setOpen((current) => ({ ...current, [file.path]: !expanded }))}
|
||||
>
|
||||
<span className="diff__caret">
|
||||
<Icon name="chevron-right" />
|
||||
</span>
|
||||
<Icon name="file" />
|
||||
<span className="truncate grow mono">{file.path}</span>
|
||||
<span className="diff__stat">
|
||||
{`+${file.add} −${file.del}`}
|
||||
</span>
|
||||
</button>
|
||||
{expanded ? (
|
||||
<div className="diff__body">
|
||||
{file.hunks.length ? (
|
||||
file.hunks.map((hunk, hunkIndex) => (
|
||||
<div className="diff__hunk" key={`${file.path}-${hunkIndex}`}>
|
||||
{hunk.header ? <div className="diff__hunkhead">{hunk.header}</div> : null}
|
||||
{hunk.lines.map((line, lineIndex) => {
|
||||
const kind = line.startsWith("+")
|
||||
? "add"
|
||||
: line.startsWith("-")
|
||||
? "del"
|
||||
: "ctx";
|
||||
return (
|
||||
<span
|
||||
key={`${hunkIndex}-${lineIndex}`}
|
||||
className={cn(
|
||||
"diff__line",
|
||||
kind === "add" && "diff__line--add",
|
||||
kind === "del" && "diff__line--del",
|
||||
)}
|
||||
>
|
||||
{line}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="diff__empty muted">{t("chat.noChanges")}</div>
|
||||
)}
|
||||
{onDecision ? (
|
||||
<div className="diff__foot">
|
||||
<span className="muted grow">
|
||||
{t("chat.source", { name: file.source ?? t("chat.parentSession") })}
|
||||
</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="primary"
|
||||
onClick={() => onDecision("accept", file.path)}
|
||||
>
|
||||
{t("chat.accept")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="danger"
|
||||
onClick={() => onDecision("reject", file.path)}
|
||||
>
|
||||
{t("chat.reject")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{onDecision ? (
|
||||
<div className="diff__foot diff__foot--all">
|
||||
<span className="muted grow">{t("chat.diffReview")}</span>
|
||||
<Button size="sm" variant="ghost" onClick={() => onDecision("reject")}>
|
||||
{t("chat.rejectAll")}
|
||||
</Button>
|
||||
<Button size="sm" variant="primary" onClick={() => onDecision("accept")}>
|
||||
{t("chat.acceptAll")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
/** Unified-diff helpers shared by tool cards and the attention diff review. */
|
||||
|
||||
export interface DiffHunk {
|
||||
header: string;
|
||||
/** Lines prefixed with `+`, `-` or a space. */
|
||||
lines: string[];
|
||||
}
|
||||
|
||||
export interface DiffFile {
|
||||
path: string;
|
||||
hunks: DiffHunk[];
|
||||
add: number;
|
||||
del: number;
|
||||
source?: string;
|
||||
}
|
||||
|
||||
interface Op {
|
||||
type: "ctx" | "add" | "del";
|
||||
line: string;
|
||||
}
|
||||
|
||||
const MAX_LCS_LINES = 900;
|
||||
|
||||
function splitLines(text: string): string[] {
|
||||
if (!text) return [];
|
||||
// Keep a trailing newline visible in the diff without producing a bogus
|
||||
// empty trailing line for files that do not have one.
|
||||
const lines = text.replace(/\r\n?/g, "\n").split("\n");
|
||||
if (lines.length && lines[lines.length - 1] === "") lines.pop();
|
||||
return lines;
|
||||
}
|
||||
|
||||
function naiveOps(before: string[], after: string[]): Op[] {
|
||||
return [
|
||||
...before.map<Op>((line) => ({ type: "del", line })),
|
||||
...after.map<Op>((line) => ({ type: "add", line })),
|
||||
];
|
||||
}
|
||||
|
||||
/** Line-level LCS diff, with a size guard that degrades to del-all/add-all. */
|
||||
export function diffOps(before: string[], after: string[]): Op[] {
|
||||
const n = before.length;
|
||||
const m = after.length;
|
||||
if (n === 0 && m === 0) return [];
|
||||
if (n * m > MAX_LCS_LINES * MAX_LCS_LINES) return naiveOps(before, after);
|
||||
|
||||
const width = m + 1;
|
||||
const table = new Uint32Array((n + 1) * width);
|
||||
for (let i = n - 1; i >= 0; i -= 1) {
|
||||
for (let j = m - 1; j >= 0; j -= 1) {
|
||||
table[i * width + j] =
|
||||
before[i] === after[j]
|
||||
? (table[(i + 1) * width + j + 1] ?? 0) + 1
|
||||
: Math.max(table[(i + 1) * width + j] ?? 0, table[i * width + j + 1] ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
const ops: Op[] = [];
|
||||
let i = 0;
|
||||
let j = 0;
|
||||
while (i < n && j < m) {
|
||||
if (before[i] === after[j]) {
|
||||
ops.push({ type: "ctx", line: before[i] ?? "" });
|
||||
i += 1;
|
||||
j += 1;
|
||||
} else if ((table[(i + 1) * width + j] ?? 0) >= (table[i * width + j + 1] ?? 0)) {
|
||||
ops.push({ type: "del", line: before[i] ?? "" });
|
||||
i += 1;
|
||||
} else {
|
||||
ops.push({ type: "add", line: after[j] ?? "" });
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
while (i < n) {
|
||||
ops.push({ type: "del", line: before[i] ?? "" });
|
||||
i += 1;
|
||||
}
|
||||
while (j < m) {
|
||||
ops.push({ type: "add", line: after[j] ?? "" });
|
||||
j += 1;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
interface PositionedOp extends Op {
|
||||
oldLine: number;
|
||||
newLine: number;
|
||||
}
|
||||
|
||||
/** Group a flat op list into `@@` hunks with `context` unchanged lines. */
|
||||
export function toHunks(ops: Op[], context = 3): DiffHunk[] {
|
||||
if (!ops.some((op) => op.type !== "ctx")) return [];
|
||||
|
||||
const positioned: PositionedOp[] = [];
|
||||
let oldLine = 0;
|
||||
let newLine = 0;
|
||||
for (const op of ops) {
|
||||
positioned.push({ ...op, oldLine, newLine });
|
||||
if (op.type !== "add") oldLine += 1;
|
||||
if (op.type !== "del") newLine += 1;
|
||||
}
|
||||
|
||||
const changed = positioned
|
||||
.map((op, index) => (op.type === "ctx" ? -1 : index))
|
||||
.filter((index) => index >= 0);
|
||||
if (!changed.length) return [];
|
||||
|
||||
const groups: { start: number; end: number }[] = [];
|
||||
for (const index of changed) {
|
||||
const start = Math.max(0, index - context);
|
||||
const end = Math.min(positioned.length - 1, index + context);
|
||||
const last = groups[groups.length - 1];
|
||||
if (last && start <= last.end + 1) last.end = Math.max(last.end, end);
|
||||
else groups.push({ start, end });
|
||||
}
|
||||
|
||||
return groups.map(({ start, end }) => {
|
||||
const slice = positioned.slice(start, end + 1);
|
||||
const first = slice[0];
|
||||
const oldStart = (first?.oldLine ?? 0) + 1;
|
||||
const newStart = (first?.newLine ?? 0) + 1;
|
||||
const oldCount = slice.filter((op) => op.type !== "add").length;
|
||||
const newCount = slice.filter((op) => op.type !== "del").length;
|
||||
return {
|
||||
header: `@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`,
|
||||
lines: slice.map((op) => `${op.type === "add" ? "+" : op.type === "del" ? "-" : " "}${op.line}`),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function unifiedDiff(before: string, after: string, context = 3): DiffHunk[] {
|
||||
return toHunks(diffOps(splitLines(before), splitLines(after)), context);
|
||||
}
|
||||
|
||||
export function statsOf(hunks: DiffHunk[]): { add: number; del: number } {
|
||||
let add = 0;
|
||||
let del = 0;
|
||||
for (const hunk of hunks) {
|
||||
for (const line of hunk.lines) {
|
||||
if (line.startsWith("+")) add += 1;
|
||||
else if (line.startsWith("-")) del += 1;
|
||||
}
|
||||
}
|
||||
return { add, del };
|
||||
}
|
||||
|
||||
export function fileDiff(path: string, before: string, after: string, source?: string): DiffFile {
|
||||
const hunks = unifiedDiff(before, after);
|
||||
const stats = statsOf(hunks);
|
||||
return { path, hunks, add: stats.add, del: stats.del, ...(source ? { source } : {}) };
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** `attention_request{method:"diff"}` payload → files (also accepts `hunks`). */
|
||||
export function diffFilesFromPayload(payload: unknown): DiffFile[] {
|
||||
const record = rec(payload);
|
||||
const list = Array.isArray(payload) ? payload : Array.isArray(record?.files) ? record.files : [];
|
||||
const files: DiffFile[] = [];
|
||||
for (const raw of list) {
|
||||
const file = rec(raw);
|
||||
if (!file) continue;
|
||||
const path = str(file.path ?? file.file) ?? "file";
|
||||
const rawHunks = Array.isArray(file.hunks) ? file.hunks : [];
|
||||
let hunks: DiffHunk[] = [];
|
||||
if (rawHunks.length) {
|
||||
hunks = rawHunks.map((value) => {
|
||||
const hunk = rec(value) ?? {};
|
||||
const lines = Array.isArray(hunk.lines) ? hunk.lines.map((line) => String(line)) : [];
|
||||
return { header: str(hunk.header) ?? "", lines };
|
||||
});
|
||||
} else if (typeof file.before === "string" || typeof file.after === "string") {
|
||||
hunks = unifiedDiff(str(file.before) ?? "", str(file.after) ?? "");
|
||||
} else if (typeof file.diff === "string") {
|
||||
hunks = [
|
||||
{
|
||||
header: "",
|
||||
lines: file.diff.split("\n").filter((line) => line !== ""),
|
||||
},
|
||||
];
|
||||
}
|
||||
const stats = statsOf(hunks);
|
||||
files.push({
|
||||
path,
|
||||
hunks,
|
||||
add: num(file.add) ?? stats.add,
|
||||
del: num(file.del) ?? stats.del,
|
||||
...(str(file.source ?? file.agent) ? { source: str(file.source ?? file.agent) } : {}),
|
||||
});
|
||||
}
|
||||
return files;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { Block, ThinkingLevel } from "@protocol/types";
|
||||
|
||||
export const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
||||
|
||||
const clockFormatters = new Map<string, Intl.DateTimeFormat>();
|
||||
|
||||
/** Wall-clock label used in message metadata (`HH:MM`). */
|
||||
export function formatClock(ts: number): string {
|
||||
if (!Number.isFinite(ts) || ts <= 0) return "—";
|
||||
const locale = typeof document !== "undefined" && document.documentElement.lang ? document.documentElement.lang : "en-US";
|
||||
let formatter = clockFormatters.get(locale);
|
||||
if (!formatter) {
|
||||
formatter = new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit" });
|
||||
clockFormatters.set(locale, formatter);
|
||||
}
|
||||
return formatter.format(new Date(ts));
|
||||
}
|
||||
|
||||
/** Compact duration (`350ms`, `1.2s`, `2m 05s`) matching `App.fmt.dur`. */
|
||||
export function formatDuration(ms: number | null | undefined): string {
|
||||
if (ms == null || !Number.isFinite(ms) || ms < 0) return "—";
|
||||
if (ms < 1_000) return `${Math.round(ms)}ms`;
|
||||
if (ms < 60_000) {
|
||||
const seconds = ms / 1_000;
|
||||
return `${seconds < 10 ? seconds.toFixed(1) : Math.round(seconds)}s`;
|
||||
}
|
||||
const minutes = Math.floor(ms / 60_000);
|
||||
const seconds = Math.round((ms % 60_000) / 1_000);
|
||||
return `${minutes}m ${String(seconds).padStart(2, "0")}s`;
|
||||
}
|
||||
|
||||
export function truncate(value: string, max = 120): string {
|
||||
const clean = value.replace(/\s+/g, " ").trim();
|
||||
if (clean.length <= max) return clean;
|
||||
return `${clean.slice(0, Math.max(0, max - 1))}…`;
|
||||
}
|
||||
|
||||
function argsOf(block: Block): Record<string, unknown> {
|
||||
if (block.type !== "tool" || !block.args || typeof block.args !== "object") return {};
|
||||
return block.args as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function firstString(args: Record<string, unknown>, keys: string[]): string | undefined {
|
||||
for (const key of keys) {
|
||||
const value = args[key];
|
||||
if (typeof value === "string" && value.trim()) return value;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** One-line tool summary (path/command/pattern) for the collapsed card. */
|
||||
export function toolSummary(block: Extract<Block, { type: "tool" }>): string {
|
||||
const args = argsOf(block);
|
||||
const named =
|
||||
firstString(args, ["command", "cmd", "path", "file_path", "filePath", "pattern", "query", "url", "task"]) ??
|
||||
firstString(args, ["description", "prompt"]);
|
||||
if (named) return truncate(named);
|
||||
const output = block.output?.text;
|
||||
if (output) return truncate(output);
|
||||
return "";
|
||||
}
|
||||
|
||||
export function toolArgsText(block: Extract<Block, { type: "tool" }>): string {
|
||||
if (!block.args || typeof block.args !== "object") return "";
|
||||
try {
|
||||
return JSON.stringify(block.args, null, 2);
|
||||
} catch {
|
||||
return String(block.args);
|
||||
}
|
||||
}
|
||||
|
||||
export function toolOutputText(block: Extract<Block, { type: "tool" }>): string {
|
||||
const output = block.output;
|
||||
if (!output) return "";
|
||||
if (typeof output.text === "string" && output.text.trim()) return output.text;
|
||||
if (output.details !== undefined) {
|
||||
try {
|
||||
return JSON.stringify(output.details, null, 2);
|
||||
} catch {
|
||||
return String(output.details);
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export interface ToolDiffSource {
|
||||
path: string;
|
||||
before: string;
|
||||
after: string;
|
||||
}
|
||||
|
||||
/** Best-effort before/after extraction for edit-style tool arguments. */
|
||||
export function toolDiffSource(block: Extract<Block, { type: "tool" }>): ToolDiffSource | null {
|
||||
const args = argsOf(block);
|
||||
const details = block.output?.details;
|
||||
const path =
|
||||
firstString(args, ["path", "file_path", "filePath", "file", "filename"]) ??
|
||||
(details && typeof details === "object"
|
||||
? firstString(details as Record<string, unknown>, ["path", "file_path", "file"])
|
||||
: undefined);
|
||||
if (!path) return null;
|
||||
const before = firstString(args, ["oldText", "old_string", "oldString", "before", "original"]);
|
||||
const after = firstString(args, ["newText", "new_string", "newString", "after", "content", "replacement"]);
|
||||
if (before === undefined && after === undefined) return null;
|
||||
return { path, before: before ?? "", after: after ?? "" };
|
||||
}
|
||||
|
||||
export function blocksText(blocks: Block[]): string {
|
||||
return blocks
|
||||
.map((block) => {
|
||||
if (block.type === "text" || block.type === "error") return block.text;
|
||||
if (block.type === "thinking") return block.text;
|
||||
return "";
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import type { Entry } from "@protocol/types";
|
||||
import { useCallback, useEffect } from "react";
|
||||
|
||||
import { apiRequest, ApiError } from "@/lib/api";
|
||||
import { mergeEntries, normalizeEntriesPage, projectEntries } from "@/lib/entry-projection";
|
||||
import { EMPTY_HISTORY, useChatStore, type HistoryState } from "./store";
|
||||
|
||||
export const HISTORY_PAGE_SIZE = 50;
|
||||
|
||||
export interface FetchedPage {
|
||||
entries: ReturnType<typeof projectEntries>;
|
||||
cursor: { before?: string; hasMore: boolean };
|
||||
}
|
||||
|
||||
/** `GET /api/v1/sessions/:sid/entries?before=&limit=` → raw pi entries + cursor. */
|
||||
export async function fetchEntriesPage(
|
||||
sessionId: string,
|
||||
before?: string,
|
||||
limit = HISTORY_PAGE_SIZE,
|
||||
signal?: AbortSignal,
|
||||
): Promise<FetchedPage> {
|
||||
const query = new URLSearchParams({ limit: String(limit) });
|
||||
if (before) query.set("before", before);
|
||||
const raw = await apiRequest<unknown>(
|
||||
`/api/v1/sessions/${encodeURIComponent(sessionId)}/entries?${query.toString()}`,
|
||||
{ signal },
|
||||
);
|
||||
const page = normalizeEntriesPage(raw);
|
||||
return { entries: projectEntries(page.entries), cursor: page.cursor };
|
||||
}
|
||||
|
||||
/** Monotonic guard so a stale page (session switch / resync) cannot win. */
|
||||
let requestCounter = 0;
|
||||
const latestRequest = new Map<string, number>();
|
||||
|
||||
function nextRequest(sessionId: string): number {
|
||||
const seq = ++requestCounter;
|
||||
latestRequest.set(sessionId, seq);
|
||||
return seq;
|
||||
}
|
||||
|
||||
function isCurrent(sessionId: string, seq: number): boolean {
|
||||
return latestRequest.get(sessionId) === seq;
|
||||
}
|
||||
|
||||
export interface SessionHistory {
|
||||
entries: Entry[];
|
||||
history: HistoryState;
|
||||
hasMore: boolean;
|
||||
loadingOlder: boolean;
|
||||
loadingInitial: boolean;
|
||||
error: string | null;
|
||||
loadOlder: () => void;
|
||||
retry: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Historical pages merged with the live snapshot entries (live wins by id).
|
||||
* Paging is backwards (`before` cursor) and dedupes by entry id.
|
||||
*/
|
||||
export function useSessionHistory(
|
||||
sessionId: string | null | undefined,
|
||||
liveEntries: Entry[],
|
||||
enabled = true,
|
||||
): SessionHistory {
|
||||
const history = useChatStore((state) =>
|
||||
sessionId ? (state.history[sessionId] ?? EMPTY_HISTORY) : EMPTY_HISTORY,
|
||||
);
|
||||
|
||||
const token = history.resyncToken;
|
||||
useEffect(() => {
|
||||
if (!sessionId || !enabled) return;
|
||||
const current = useChatStore.getState().history[sessionId] ?? EMPTY_HISTORY;
|
||||
if (current.loaded || current.loadingInitial) return;
|
||||
|
||||
const seq = nextRequest(sessionId);
|
||||
useChatStore.getState().beginInitial(sessionId);
|
||||
void fetchEntriesPage(sessionId)
|
||||
.then((page) => {
|
||||
if (!isCurrent(sessionId, seq)) return;
|
||||
useChatStore.getState().receiveInitial(sessionId, page.entries, page.cursor);
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!isCurrent(sessionId, seq)) return;
|
||||
const message = error instanceof ApiError ? error.code : error instanceof Error ? error.message : String(error);
|
||||
useChatStore.getState().historyError(sessionId, message);
|
||||
});
|
||||
// `token` is the resync generation; `sessionId`/`enabled` gate loading.
|
||||
}, [sessionId, enabled, token]);
|
||||
|
||||
const loadOlder = useCallback(() => {
|
||||
if (!sessionId) return;
|
||||
const current = useChatStore.getState().history[sessionId] ?? EMPTY_HISTORY;
|
||||
if (current.loadingOlder || current.loadingInitial) return;
|
||||
const before = current.cursor?.before;
|
||||
if (!current.cursor?.hasMore || !before) return;
|
||||
|
||||
const seq = nextRequest(sessionId);
|
||||
useChatStore.getState().beginOlder(sessionId);
|
||||
void fetchEntriesPage(sessionId, before)
|
||||
.then((page) => {
|
||||
if (!isCurrent(sessionId, seq)) return;
|
||||
useChatStore.getState().receiveOlder(sessionId, page.entries, page.cursor);
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!isCurrent(sessionId, seq)) return;
|
||||
const message = error instanceof ApiError ? error.code : error instanceof Error ? error.message : String(error);
|
||||
useChatStore.getState().historyError(sessionId, message);
|
||||
});
|
||||
}, [sessionId]);
|
||||
|
||||
const retry = useCallback(() => {
|
||||
if (!sessionId) return;
|
||||
const current = useChatStore.getState().history[sessionId] ?? EMPTY_HISTORY;
|
||||
if (current.loaded) loadOlder();
|
||||
else useChatStore.getState().bumpResync(sessionId);
|
||||
}, [loadOlder, sessionId]);
|
||||
|
||||
return {
|
||||
entries: mergeEntries(history.entries, liveEntries),
|
||||
history,
|
||||
hasMore: history.cursor?.hasMore === true && Boolean(history.cursor?.before),
|
||||
loadingOlder: history.loadingOlder,
|
||||
loadingInitial: history.loadingInitial,
|
||||
error: history.error,
|
||||
loadOlder,
|
||||
retry,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import type { CSSProperties, ReactNode } from "react";
|
||||
import { useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface ChatLayoutProps {
|
||||
tree: ReactNode;
|
||||
stream: ReactNode;
|
||||
panel: ReactNode;
|
||||
treeOpen: boolean;
|
||||
panelOpen: boolean;
|
||||
treeCollapsed: boolean;
|
||||
treeWidth: number;
|
||||
panelWidth: number;
|
||||
onWidths: (widths: { treeWidth?: number; panelWidth?: number }) => void;
|
||||
onCloseDrawers: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const TREE_MIN = 220;
|
||||
const TREE_MAX = 460;
|
||||
const PANEL_MIN = 260;
|
||||
const PANEL_MAX = 520;
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Three-column chat grid with resizable dividers.
|
||||
* ≥840: tree | stream | panel; 600–839: tree | stream (panel drawer);
|
||||
* <600: single column with tree/panel drawers.
|
||||
*/
|
||||
export function ChatLayout({
|
||||
tree,
|
||||
stream,
|
||||
panel,
|
||||
treeOpen,
|
||||
panelOpen,
|
||||
treeCollapsed,
|
||||
treeWidth,
|
||||
panelWidth,
|
||||
onWidths,
|
||||
onCloseDrawers,
|
||||
className,
|
||||
}: ChatLayoutProps) {
|
||||
const { t } = useTranslation();
|
||||
const startResize = useCallback(
|
||||
(which: "tree" | "panel", event: React.PointerEvent<HTMLDivElement>) => {
|
||||
event.preventDefault();
|
||||
const startX = event.clientX;
|
||||
const startWidth = which === "tree" ? treeWidth : panelWidth;
|
||||
const move = (moveEvent: PointerEvent) => {
|
||||
const delta = which === "tree" ? moveEvent.clientX - startX : startX - moveEvent.clientX;
|
||||
if (which === "tree") onWidths({ treeWidth: clamp(startWidth + delta, TREE_MIN, TREE_MAX) });
|
||||
else onWidths({ panelWidth: clamp(startWidth + delta, PANEL_MIN, PANEL_MAX) });
|
||||
};
|
||||
const up = () => {
|
||||
window.removeEventListener("pointermove", move);
|
||||
window.removeEventListener("pointerup", up);
|
||||
};
|
||||
window.addEventListener("pointermove", move);
|
||||
window.addEventListener("pointerup", up, { once: true });
|
||||
},
|
||||
[onWidths, panelWidth, treeWidth],
|
||||
);
|
||||
|
||||
const nudge = useCallback(
|
||||
(which: "tree" | "panel", delta: number) => {
|
||||
if (which === "tree") onWidths({ treeWidth: clamp(treeWidth + delta, TREE_MIN, TREE_MAX) });
|
||||
else onWidths({ panelWidth: clamp(panelWidth + delta, PANEL_MIN, PANEL_MAX) });
|
||||
},
|
||||
[onWidths, panelWidth, treeWidth],
|
||||
);
|
||||
|
||||
const separator = (which: "tree" | "panel") => (
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label={which === "tree" ? t("chat.resizeTree") : t("chat.resizePanel")}
|
||||
tabIndex={0}
|
||||
className={cn("resize-handle", which === "tree" ? "resize-handle--tree" : "resize-handle--panel")}
|
||||
onPointerDown={(event) => startResize(which, event)}
|
||||
onDoubleClick={() => {
|
||||
if (which === "tree") onWidths({ treeWidth: 300 });
|
||||
else onWidths({ panelWidth: 340 });
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "ArrowLeft") {
|
||||
event.preventDefault();
|
||||
nudge(which, -16);
|
||||
} else if (event.key === "ArrowRight") {
|
||||
event.preventDefault();
|
||||
nudge(which, 16);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
const style = {
|
||||
"--tree-w": `${treeWidth}px`,
|
||||
"--panel-w": `${panelWidth}px`,
|
||||
} as CSSProperties;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"chat-page",
|
||||
treeOpen && "tree-open",
|
||||
panelOpen && "panel-open",
|
||||
treeCollapsed && "tree-collapsed",
|
||||
className,
|
||||
)}
|
||||
style={style}
|
||||
>
|
||||
<aside className="tree-pane">
|
||||
{tree}
|
||||
</aside>
|
||||
{separator("tree")}
|
||||
<section className="stream-pane">{stream}</section>
|
||||
{separator("panel")}
|
||||
<aside className="panel-pane">{panel}</aside>
|
||||
<button
|
||||
type="button"
|
||||
className="drawer-backdrop"
|
||||
aria-label={t("common.close")}
|
||||
tabIndex={treeOpen || panelOpen ? 0 : -1}
|
||||
onClick={onCloseDrawers}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
import type { Batch, Entry, SessionState, Subagent, TodoItem } from "@protocol/types";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { useCallback, useLayoutEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Empty } from "@/components/ui/empty";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import type { ProjectedEntry } from "@/lib/entry-projection";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { BatchBlock, EntryBlock, TodoBlock } from "./blocks";
|
||||
import { findSubagent } from "./session-state";
|
||||
|
||||
/** Below this many items the DOM list is cheaper than virtualizer bookkeeping. */
|
||||
export const VIRTUALIZE_THRESHOLD = 30;
|
||||
|
||||
export type StreamItem =
|
||||
| { kind: "entry"; key: string; entry: Entry; turnStart: boolean }
|
||||
| { kind: "todo"; key: string; todos: TodoItem[] }
|
||||
| { kind: "batch"; key: string; batch: Batch };
|
||||
|
||||
/**
|
||||
* Combine entry-backed messages with the session-level panels (todo, batches)
|
||||
* into one ordered stream. Historical `pi2-todo` checkpoints stay inline; when
|
||||
* history has none, the current todo list is appended as a live block.
|
||||
*/
|
||||
export function buildStreamItems(session: SessionState, entries: Entry[]): StreamItem[] {
|
||||
const items: StreamItem[] = [];
|
||||
let hasTodoEntry = false;
|
||||
entries.forEach((entry, index) => {
|
||||
const projectedTodo = (entry as ProjectedEntry).todo;
|
||||
if (projectedTodo) {
|
||||
hasTodoEntry = true;
|
||||
items.push({ kind: "todo", key: `todo:${entry.id}`, todos: projectedTodo.items });
|
||||
return;
|
||||
}
|
||||
const previous = index > 0 ? entries[index - 1] : undefined;
|
||||
const turnStart = index === 0 || entry.role === "user" || previous?.role === "user";
|
||||
items.push({ kind: "entry", key: `entry:${entry.id}`, entry, turnStart });
|
||||
});
|
||||
if (!hasTodoEntry && session.todos.length) {
|
||||
items.push({ kind: "todo", key: `todo:${session.sessionId}`, todos: session.todos });
|
||||
}
|
||||
for (const batch of session.batches) {
|
||||
items.push({ kind: "batch", key: `batch:${batch.batchId}`, batch });
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
export interface MessageStreamProps {
|
||||
session: SessionState;
|
||||
entries: Entry[];
|
||||
hasMore: boolean;
|
||||
loadingOlder: boolean;
|
||||
error: string | null;
|
||||
onLoadOlder: () => void;
|
||||
onRetry: () => void;
|
||||
onOpenSubagent: (subagent: Subagent) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function MessageStream({
|
||||
session,
|
||||
entries,
|
||||
hasMore,
|
||||
loadingOlder,
|
||||
error,
|
||||
onLoadOlder,
|
||||
onRetry,
|
||||
onOpenSubagent,
|
||||
className,
|
||||
}: MessageStreamProps) {
|
||||
const { t } = useTranslation();
|
||||
const items = buildStreamItems(session, entries);
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null);
|
||||
const [following, setFollowing] = useState(true);
|
||||
const followingRef = useRef(true);
|
||||
const [showTop, setShowTop] = useState(false);
|
||||
const pendingPrepend = useRef<number | null>(null);
|
||||
const loadRequested = useRef(false);
|
||||
const rafRef = useRef<number | null>(null);
|
||||
|
||||
const setFollow = useCallback((value: boolean) => {
|
||||
followingRef.current = value;
|
||||
setFollowing(value);
|
||||
}, []);
|
||||
|
||||
const virtualize = items.length >= VIRTUALIZE_THRESHOLD;
|
||||
const virtualizer = useVirtualizer({
|
||||
count: items.length,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: () => 120,
|
||||
overscan: 8,
|
||||
getItemKey: (index) => items[index]?.key ?? index,
|
||||
});
|
||||
|
||||
const scrollToBottom = useCallback((smooth = false) => {
|
||||
const element = scrollRef.current;
|
||||
if (!element) return;
|
||||
if (typeof element.scrollTo === "function") {
|
||||
element.scrollTo({ top: element.scrollHeight, behavior: smooth ? "smooth" : "auto" });
|
||||
} else {
|
||||
element.scrollTop = element.scrollHeight;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Streaming keeps the DOM height changing; stay pinned while following.
|
||||
useLayoutEffect(() => {
|
||||
if (!followingRef.current) return;
|
||||
if (rafRef.current != null) cancelAnimationFrame(rafRef.current);
|
||||
rafRef.current = requestAnimationFrame(() => {
|
||||
rafRef.current = requestAnimationFrame(() => {
|
||||
rafRef.current = null;
|
||||
if (followingRef.current) scrollToBottom(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const element = scrollRef.current;
|
||||
const previous = pendingPrepend.current;
|
||||
if (previous != null && element) {
|
||||
element.scrollTop += element.scrollHeight - previous;
|
||||
pendingPrepend.current = null;
|
||||
}
|
||||
if (!loadingOlder) loadRequested.current = false;
|
||||
}, [items.length, loadingOlder]);
|
||||
|
||||
const handleScroll = useCallback(() => {
|
||||
const element = scrollRef.current;
|
||||
if (!element) return;
|
||||
const distance = element.scrollHeight - element.scrollTop - element.clientHeight;
|
||||
setFollow(distance < 80);
|
||||
setShowTop(element.scrollTop > 400);
|
||||
if (element.scrollTop < 120 && hasMore && !loadingOlder && !loadRequested.current) {
|
||||
loadRequested.current = true;
|
||||
pendingPrepend.current = element.scrollHeight;
|
||||
onLoadOlder();
|
||||
}
|
||||
}, [hasMore, loadingOlder, onLoadOlder, setFollow]);
|
||||
|
||||
const openByName = useCallback(
|
||||
(name: string) => {
|
||||
const subagent = findSubagent(session.subagents, (candidate) => candidate.name === name);
|
||||
if (subagent) onOpenSubagent(subagent);
|
||||
},
|
||||
[onOpenSubagent, session.subagents],
|
||||
);
|
||||
|
||||
const canOpen = useCallback(
|
||||
(name: string) => Boolean(findSubagent(session.subagents, (candidate) => candidate.name === name)),
|
||||
[session.subagents],
|
||||
);
|
||||
|
||||
const renderItem = useCallback(
|
||||
(item: StreamItem) => {
|
||||
switch (item.kind) {
|
||||
case "entry":
|
||||
return <EntryBlock entry={item.entry} turnStart={item.turnStart} />;
|
||||
case "todo":
|
||||
return <TodoBlock items={item.todos} />;
|
||||
case "batch":
|
||||
return <BatchBlock batch={item.batch} onOpenSubagent={openByName} canOpen={canOpen} />;
|
||||
}
|
||||
},
|
||||
[canOpen, openByName],
|
||||
);
|
||||
|
||||
const status = (
|
||||
<div className="stream-status-row">
|
||||
{loadingOlder ? (
|
||||
<span className="muted stream-status">
|
||||
<Spinner /> {t("chat.loadingOlder")}
|
||||
</span>
|
||||
) : hasMore ? (
|
||||
<button type="button" className="stream-older muted" onClick={onLoadOlder}>
|
||||
{t("chat.loadOlder")}
|
||||
</button>
|
||||
) : null}
|
||||
{error ? (
|
||||
<span className="stream-status stream-status--err">
|
||||
<span>{t("chat.historyError")}</span>
|
||||
<Button size="sm" onClick={onRetry}>
|
||||
{t("common.retry")}
|
||||
</Button>
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
const body = items.length ? (
|
||||
virtualize ? (
|
||||
<div
|
||||
className="stream-list stream-list--virtual"
|
||||
style={{ height: `${virtualizer.getTotalSize()}px` }}
|
||||
>
|
||||
{virtualizer.getVirtualItems().map((virtualItem) => {
|
||||
const item = items[virtualItem.index];
|
||||
if (!item) return null;
|
||||
return (
|
||||
<div
|
||||
key={item.key}
|
||||
data-index={virtualItem.index}
|
||||
ref={(node) => {
|
||||
virtualizer.measureElement(node);
|
||||
}}
|
||||
className={cn("stream-item", item.kind === "entry" && item.turnStart && "turn-start")}
|
||||
style={{ transform: `translateY(${virtualItem.start}px)` }}
|
||||
>
|
||||
{renderItem(item)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="stream-list">
|
||||
{items.map((item) => (
|
||||
<div
|
||||
className={cn("stream-item", item.kind === "entry" && item.turnStart && "turn-start")}
|
||||
key={item.key}
|
||||
>
|
||||
{renderItem(item)}
|
||||
</div>
|
||||
))}
|
||||
<div className="stream-end" />
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
<Empty
|
||||
className="stream-empty"
|
||||
icon={<Icon name="chat" />}
|
||||
title={t("chat.emptyTitle")}
|
||||
description={t("chat.emptyText")}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={cn("stream-body", className)}>
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="stream-scroll"
|
||||
role="log"
|
||||
aria-live="polite"
|
||||
aria-label={t("chat.streamAria")}
|
||||
onScroll={handleScroll}
|
||||
>
|
||||
{status}
|
||||
{body}
|
||||
</div>
|
||||
<div className="stream-fab">
|
||||
<button
|
||||
type="button"
|
||||
className={cn("fab fab--top", showTop && "is-visible")}
|
||||
title={t("chat.toTop")}
|
||||
onClick={() => {
|
||||
scrollRef.current?.scrollTo({ top: 0, behavior: "smooth" });
|
||||
setFollow(false);
|
||||
setShowTop(false);
|
||||
}}
|
||||
>
|
||||
{t("chat.top")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={cn("fab fab--latest", !following && "is-visible")}
|
||||
title={t("chat.backToLatest")}
|
||||
onClick={() => {
|
||||
setFollow(true);
|
||||
scrollToBottom(true);
|
||||
}}
|
||||
>
|
||||
{t("chat.latest")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,557 @@
|
||||
import type { Entry, ModelRef, SessionState, Subagent, TaskItem, ThinkingLevel } from "@protocol/types";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { RelativeTime } from "@/components/shared/relative-time";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
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 { chatCommands, runCommand } from "./commands";
|
||||
import type { ModelGroup } from "./data";
|
||||
import { withCurrentModel } from "./data";
|
||||
import { formatDuration, THINKING_LEVELS } from "./format";
|
||||
import { flattenSubagents } from "./session-state";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* dispatch */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export interface DispatchInput {
|
||||
task: string;
|
||||
name?: string;
|
||||
model?: ModelRef;
|
||||
thinking?: ThinkingLevel;
|
||||
wait?: boolean;
|
||||
cancelSiblingsOnFail?: boolean;
|
||||
}
|
||||
|
||||
export interface DispatchModalProps {
|
||||
open: boolean;
|
||||
session: SessionState;
|
||||
models: ModelGroup[];
|
||||
onClose: () => void;
|
||||
onDispatch: (input: DispatchInput) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export function DispatchModal({ open, session, models, onClose, onDispatch }: DispatchModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const groups = withCurrentModel(models, session.model);
|
||||
const [task, setTask] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [modelValue, setModelValue] = useState("");
|
||||
const [thinking, setThinking] = useState<ThinkingLevel>("low");
|
||||
const [wait, setWait] = useState(false);
|
||||
const [cancelSiblings, setCancelSiblings] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const first = groups[0]?.provider && groups[0]?.models[0] ? `${groups[0].provider}/${groups[0].models[0].id}` : "";
|
||||
setModelValue(session.model ? `${session.model.provider}/${session.model.id}` : first);
|
||||
}, [open, session.model, groups]);
|
||||
|
||||
function parseModel(): ModelRef | undefined {
|
||||
const slash = modelValue.indexOf("/");
|
||||
if (slash <= 0) return undefined;
|
||||
return { provider: modelValue.slice(0, slash), id: modelValue.slice(slash + 1) };
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!task.trim()) {
|
||||
toast.error(t("chat.taskRequired"));
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await onDispatch({
|
||||
task: task.trim(),
|
||||
...(name.trim() ? { name: name.trim() } : {}),
|
||||
...(parseModel() ? { model: parseModel() } : {}),
|
||||
thinking,
|
||||
wait,
|
||||
cancelSiblingsOnFail: cancelSiblings,
|
||||
});
|
||||
setTask("");
|
||||
setName("");
|
||||
onClose();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) onClose();
|
||||
}}
|
||||
title={t("chat.dispatchTitle")}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={() => void submit()} disabled={busy}>
|
||||
{t("chat.dispatch")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="field">
|
||||
<label htmlFor="dispatch-task">{t("chat.taskLabel")}</label>
|
||||
<textarea
|
||||
id="dispatch-task"
|
||||
className="textarea"
|
||||
rows={3}
|
||||
value={task}
|
||||
placeholder={t("chat.taskPlaceholder")}
|
||||
onChange={(event) => setTask(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="dispatch-name">{t("chat.nameLabel")}</label>
|
||||
<input
|
||||
id="dispatch-name"
|
||||
className="input"
|
||||
value={name}
|
||||
placeholder={t("chat.subagentNamePlaceholder")}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="dispatch-model">{t("chat.modelLabel")}</label>
|
||||
<select
|
||||
id="dispatch-model"
|
||||
className="select"
|
||||
value={modelValue}
|
||||
onChange={(event) => setModelValue(event.target.value)}
|
||||
>
|
||||
{groups.map((group) => (
|
||||
<optgroup key={group.provider} label={group.provider}>
|
||||
{group.models.map((item) => (
|
||||
<option key={`${group.provider}/${item.id}`} value={`${group.provider}/${item.id}`}>
|
||||
{item.id}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="dispatch-thinking">{t("chat.thinkingAria")}</label>
|
||||
<select
|
||||
id="dispatch-thinking"
|
||||
className="select"
|
||||
value={thinking}
|
||||
onChange={(event) => setThinking(event.target.value as ThinkingLevel)}
|
||||
>
|
||||
{THINKING_LEVELS.map((level) => (
|
||||
<option key={level} value={level}>
|
||||
{level}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label className="check-row">
|
||||
<input type="checkbox" checked={wait} onChange={(event) => setWait(event.target.checked)} />
|
||||
{t("chat.waitLabel")}
|
||||
</label>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label className="check-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={cancelSiblings}
|
||||
onChange={(event) => setCancelSiblings(event.target.checked)}
|
||||
/>
|
||||
{t("chat.cancelSiblingsLabel")}
|
||||
</label>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* subagent conversation (read-only tail + steer) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const SUB_BADGE: Record<Subagent["status"], { tone: "info" | "ok" | "err" | "warn" | "default"; key: string }> = {
|
||||
active: { tone: "info", key: "active" },
|
||||
completed: { tone: "ok", key: "completed" },
|
||||
failed: { tone: "err", key: "failed" },
|
||||
interrupted: { tone: "warn", key: "interrupted" },
|
||||
dormant: { tone: "default", key: "dormant" },
|
||||
};
|
||||
|
||||
const SUB_DOT: Record<Subagent["status"], string> = {
|
||||
active: "dot--busy",
|
||||
completed: "dot--ok",
|
||||
failed: "dot--err",
|
||||
interrupted: "dot--attention",
|
||||
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 [];
|
||||
}
|
||||
|
||||
export interface SubagentModalProps {
|
||||
open: boolean;
|
||||
session: SessionState;
|
||||
subagent: Subagent | null;
|
||||
onClose: () => void;
|
||||
onBack: () => void;
|
||||
onSteer: (subagent: Subagent, message: string) => void;
|
||||
}
|
||||
|
||||
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 [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);
|
||||
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));
|
||||
})
|
||||
.catch(() => {
|
||||
if (subagent) setTail(statusTail(subagent, t));
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [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) : [];
|
||||
|
||||
function sendSteer() {
|
||||
if (!steer.trim()) {
|
||||
toast.error(t("chat.steerRequired"));
|
||||
return;
|
||||
}
|
||||
if (subagent) onSteer(subagent, steer.trim());
|
||||
setSteer("");
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) onClose();
|
||||
}}
|
||||
title={t("chat.subagentTitle", { name: subagent?.name ?? subagent?.id ?? "" })}
|
||||
size="wide"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t("common.close")}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onBack}>
|
||||
{t("chat.backToParent")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{subagent ? (
|
||||
<div className="sub-preview">
|
||||
<div className="row">
|
||||
<span className={`dot ${SUB_DOT[subagent.status] ?? "dot--exited"}`} />
|
||||
{badge ? <Badge tone={badge.tone}>{t(`state.${badge.key}`)}</Badge> : null}
|
||||
<span className="muted mono truncate">{subagent.id}</span>
|
||||
</div>
|
||||
<div>
|
||||
<KV label={t("chat.task")}>{subagent.task ?? "—"}</KV>
|
||||
<KV label={t("chat.model")} mono>
|
||||
{subagent.model ?? "—"}
|
||||
{subagent.thinking ? ` · ${subagent.thinking}` : ""}
|
||||
</KV>
|
||||
<KV label={t("status.created")}>
|
||||
<RelativeTime ts={subagent.createdAt} />
|
||||
</KV>
|
||||
<KV label={t("status.lastActive")}>
|
||||
<RelativeTime ts={subagent.lastActiveAt} />
|
||||
</KV>
|
||||
</div>
|
||||
{children.length ? (
|
||||
<div className="stack">
|
||||
<div className="muted">{t("chat.currentSubagents", { n: children.length })}</div>
|
||||
{children.map(({ subagent: child, depth }) => (
|
||||
<div
|
||||
key={child.id}
|
||||
className="sub-item sub-item--nested"
|
||||
style={{ marginLeft: `${depth * 16}px` }}
|
||||
>
|
||||
<span className={`dot ${SUB_DOT[child.status] ?? "dot--exited"}`} />
|
||||
<span className="sub-item__main">
|
||||
<span className="sub-item__name truncate">{child.name ?? child.id}</span>
|
||||
<span className="sub-item__meta muted truncate">{child.model ?? "—"}</span>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="sub-preview__feed" aria-label={t("chat.preview")}>
|
||||
{loading ? (
|
||||
<div className="row muted">
|
||||
<Spinner /> {t("chat.loading")}
|
||||
</div>
|
||||
) : (
|
||||
feed.map((entry) => <EntryBlock key={entry.id} entry={entry} />)
|
||||
)}
|
||||
</div>
|
||||
<div className="muted sub-preview__note">{t("chat.previewNote")}</div>
|
||||
<div className="row sub-steer">
|
||||
<input
|
||||
className="input"
|
||||
value={steer}
|
||||
placeholder={t("chat.steerPlaceholder")}
|
||||
aria-label={t("chat.steer")}
|
||||
onChange={(event) => setSteer(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" && !event.nativeEvent.isComposing) {
|
||||
event.preventDefault();
|
||||
sendSteer();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button size="sm" onClick={sendSteer}>
|
||||
{t("chat.steer")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 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);
|
||||
}
|
||||
|
||||
export interface TaskOutputModalProps {
|
||||
open: boolean;
|
||||
session: SessionState;
|
||||
task: TaskItem | null;
|
||||
onClose: () => void;
|
||||
onStop: (task: TaskItem) => void;
|
||||
}
|
||||
|
||||
export function TaskOutputModal({ open, session, task, onClose, onStop }: TaskOutputModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const [output, setOutput] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !task) return;
|
||||
setOutput(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);
|
||||
})
|
||||
.catch(() => setOutput(null))
|
||||
.finally(() => setLoading(false));
|
||||
}, [open, session.sessionId, task]);
|
||||
|
||||
if (!task) return null;
|
||||
const running = task.status === "running";
|
||||
const duration = running ? Date.now() - task.startTime : (task.durationMs ?? 0);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) onClose();
|
||||
}}
|
||||
title={t("chat.taskOutput", { id: task.id })}
|
||||
footer={
|
||||
<>
|
||||
{running ? (
|
||||
<Button variant="danger" onClick={() => onStop(task)}>
|
||||
{t("common.stop")}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="primary" onClick={onClose}>
|
||||
{t("common.close")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<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}
|
||||
<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>
|
||||
</KV>
|
||||
<KV label={t("chat.duration")}>{formatDuration(duration)}</KV>
|
||||
<KV label="exit code" mono>
|
||||
{task.exitCode == null ? "—" : task.exitCode}
|
||||
</KV>
|
||||
<KV label={t("chat.command")} mono>
|
||||
{task.command}
|
||||
</KV>
|
||||
</div>
|
||||
{running ? (
|
||||
<div className="row muted">
|
||||
<Spinner /> {t("chat.taskRunning")}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* rename */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export interface RenameDialogProps {
|
||||
open: boolean;
|
||||
title: string;
|
||||
initial: string;
|
||||
hint?: string;
|
||||
onClose: () => void;
|
||||
onSave: (value: string) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export function RenameDialog({ open, title, initial, hint, onClose, onSave }: RenameDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [value, setValue] = useState(initial);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setValue(initial);
|
||||
setError(null);
|
||||
}
|
||||
}, [open, initial]);
|
||||
|
||||
async function save() {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
setError(t("chat.nameRequired"));
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await onSave(trimmed);
|
||||
onClose();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) onClose();
|
||||
}}
|
||||
title={title}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={() => void save()} disabled={busy}>
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="field">
|
||||
<label htmlFor="rename-input">{t("chat.name")}</label>
|
||||
<input
|
||||
id="rename-input"
|
||||
className="input"
|
||||
value={value}
|
||||
onChange={(event) => {
|
||||
setValue(event.target.value);
|
||||
setError(null);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
void save();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{error ? (
|
||||
<div className="hint is-err" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : hint ? (
|
||||
<div className="hint">{hint}</div>
|
||||
) : null}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
import { applyEvent, createReducer, type Reducer } from "@protocol/reducer";
|
||||
import type { Entry, ModelRef, SessionEvent, SessionState, ThinkingLevel } from "@protocol/types";
|
||||
import type { DotStatus } from "@/components/ui/status-dot";
|
||||
import { normalizeTodos, projectEntries, type ProjectedEntry } from "@/lib/entry-projection";
|
||||
|
||||
const EMPTY_USAGE = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
||||
|
||||
function rec(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function arr<T>(value: unknown): T[] {
|
||||
return Array.isArray(value) ? (value as T[]) : [];
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const STATUSES = new Set(["starting", "busy", "compacting", "idle", "exited", "interrupted"]);
|
||||
const THINKING = new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
|
||||
|
||||
export interface EmptySessionInput {
|
||||
sessionId: string;
|
||||
workspaceId?: string;
|
||||
cwd?: string;
|
||||
name?: string | null;
|
||||
status?: SessionState["status"];
|
||||
model?: ModelRef | null;
|
||||
thinking?: ThinkingLevel | null;
|
||||
}
|
||||
|
||||
export function emptySessionState(input: EmptySessionInput): SessionState {
|
||||
return {
|
||||
sessionId: input.sessionId,
|
||||
workspaceId: input.workspaceId ?? "",
|
||||
cwd: input.cwd ?? "",
|
||||
name: input.name ?? null,
|
||||
status: input.status ?? "idle",
|
||||
flags: { attention: false, done: false, error: false },
|
||||
model: input.model ?? null,
|
||||
thinking: input.thinking ?? null,
|
||||
usage: { ...EMPTY_USAGE },
|
||||
contextUsage: null,
|
||||
queue: [],
|
||||
todos: [],
|
||||
tasks: [],
|
||||
batches: [],
|
||||
subagents: [],
|
||||
attention: [],
|
||||
entries: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function cloneSessionState(state: SessionState): SessionState {
|
||||
if (typeof structuredClone === "function") return structuredClone(state);
|
||||
return JSON.parse(JSON.stringify(state)) as SessionState;
|
||||
}
|
||||
|
||||
export function normalizeModelRef(value: unknown): ModelRef | null {
|
||||
if (typeof value === "string") {
|
||||
const slash = value.indexOf("/");
|
||||
return slash > 0
|
||||
? { provider: value.slice(0, slash), id: value.slice(slash + 1) }
|
||||
: { provider: "pi", id: value };
|
||||
}
|
||||
const record = rec(value);
|
||||
const provider = str(record?.provider);
|
||||
const id = str(record?.id ?? record?.model ?? record?.modelId);
|
||||
if (id) return { provider: provider ?? "pi", id };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Rebuild the reducer bookkeeping a snapshot does not carry. */
|
||||
export function reducerForState(state: SessionState): Reducer {
|
||||
const reducer = createReducer({
|
||||
sessionId: state.sessionId,
|
||||
workspaceId: state.workspaceId,
|
||||
cwd: state.cwd,
|
||||
name: state.name,
|
||||
status: state.status,
|
||||
model: state.model,
|
||||
thinking: state.thinking,
|
||||
});
|
||||
reducer.state = state;
|
||||
let nextEntry = 1;
|
||||
let assistantEntryId: string | null = null;
|
||||
let userEntryId: string | null = null;
|
||||
for (const entry of state.entries) {
|
||||
const match = /^m(\d+)$/.exec(entry.id);
|
||||
if (match?.[1]) nextEntry = Math.max(nextEntry, Number(match[1]) + 1);
|
||||
if (entry.role === "assistant") assistantEntryId = entry.id;
|
||||
if (entry.role === "user") userEntryId = entry.id;
|
||||
entry.blocks.forEach((block, index) => {
|
||||
if (block.type === "tool") reducer.ctx.toolBlocks.set(block.toolCallId, { entryId: entry.id, index });
|
||||
});
|
||||
}
|
||||
reducer.ctx.nextEntry = nextEntry;
|
||||
reducer.ctx.assistantEntryId = assistantEntryId;
|
||||
reducer.ctx.userEntryId = userEntryId;
|
||||
return reducer;
|
||||
}
|
||||
|
||||
function entryText(entry: Entry): string {
|
||||
return entry.blocks
|
||||
.map((block) => (block.type === "text" || block.type === "error" ? block.text : block.type === "thinking" ? block.text : ""))
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
function isDuplicateEntry(entries: Entry[], candidate: Entry): boolean {
|
||||
const text = entryText(candidate);
|
||||
const recent = entries.slice(-8);
|
||||
return recent.some(
|
||||
(entry) =>
|
||||
entry.role === candidate.role &&
|
||||
Math.abs(entry.ts - candidate.ts) < 5_000 &&
|
||||
entryText(entry).trim() === text.trim(),
|
||||
);
|
||||
}
|
||||
|
||||
function patchToolResult(state: SessionState, raw: Record<string, unknown>): boolean {
|
||||
const toolCallId = str(raw.toolCallId);
|
||||
if (!toolCallId) return false;
|
||||
for (const entry of state.entries) {
|
||||
for (const block of entry.blocks) {
|
||||
if (block.type !== "tool" || block.toolCallId !== toolCallId) continue;
|
||||
block.state = raw.isError === true ? "error" : "done";
|
||||
block.output = {
|
||||
text: contentText(raw.content),
|
||||
...(raw.details !== undefined ? { details: raw.details } : {}),
|
||||
isError: raw.isError === true,
|
||||
};
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function contentText(content: unknown): string {
|
||||
if (typeof content === "string") return content;
|
||||
const parts: string[] = [];
|
||||
for (const item of arr<Record<string, unknown>>(content)) {
|
||||
if (item.type === "text" && typeof item.text === "string") parts.push(item.text);
|
||||
}
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle `entry_appended`. The canonical reducer relays pi's streaming
|
||||
* `message_*` events but does not project this authoritative history record, so
|
||||
* the browser applies it here (user messages arrive this way; we never insert a
|
||||
* local user message).
|
||||
*/
|
||||
function applyEntryAppended(state: SessionState, rawEntry: unknown): void {
|
||||
const raw = rec(rawEntry);
|
||||
if (!raw) return;
|
||||
const type = str(raw.type);
|
||||
|
||||
if (type === "custom" && str(raw.customType) === "pi2-todo") {
|
||||
const todos = normalizeTodos(rec(raw.data)?.todos);
|
||||
if (todos.length) state.todos = todos;
|
||||
}
|
||||
|
||||
if (type === "message") {
|
||||
const message = rec(raw.message);
|
||||
if (message?.role === "toolResult" && patchToolResult(state, message)) return;
|
||||
if (message?.role === "assistant") {
|
||||
// Streaming message_* events already own the assistant entry; the
|
||||
// raw append would re-introduce a second copy.
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const [projected] = projectEntries([raw]);
|
||||
if (!projected) return;
|
||||
if (isDuplicateEntry(state.entries, projected)) return;
|
||||
state.entries = [...state.entries, projected];
|
||||
}
|
||||
|
||||
/** Apply one live session event to an immutable copy of the render state. */
|
||||
export function applySessionEvent(state: SessionState, event: SessionEvent): SessionState {
|
||||
const next = cloneSessionState(state);
|
||||
const normalized: SessionEvent = { ...event, ts: typeof event.ts === "number" ? event.ts : Date.now() };
|
||||
|
||||
if (normalized.type === "entry_appended") {
|
||||
applyEntryAppended(next, normalized.entry);
|
||||
return next;
|
||||
}
|
||||
|
||||
applyEvent(reducerForState(next), normalized);
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Enrich a snapshot with its separately-carried entry tail. */
|
||||
export function normalizeSnapshotState(sessionId: string, workspaceId: string, payload: unknown): SessionState {
|
||||
const record = rec(payload);
|
||||
const candidate = rec(record?.state) ?? record ?? {};
|
||||
const base = emptySessionState({
|
||||
sessionId,
|
||||
workspaceId: str(candidate.workspaceId) ?? workspaceId,
|
||||
cwd: str(candidate.cwd) ?? "",
|
||||
});
|
||||
const state: SessionState = {
|
||||
...base,
|
||||
...candidate,
|
||||
sessionId,
|
||||
workspaceId: str(candidate.workspaceId) ?? workspaceId,
|
||||
flags: {
|
||||
attention: candidate.flags ? rec(candidate.flags)?.attention === true : false,
|
||||
done: rec(candidate.flags)?.done === true,
|
||||
error: rec(candidate.flags)?.error === true,
|
||||
},
|
||||
usage: { ...EMPTY_USAGE, ...(rec(candidate.usage) ?? {}) } as SessionState["usage"],
|
||||
queue: arr(candidate.queue),
|
||||
todos: arr(candidate.todos),
|
||||
tasks: arr(candidate.tasks),
|
||||
batches: arr(candidate.batches),
|
||||
subagents: arr(candidate.subagents),
|
||||
attention: arr(candidate.attention),
|
||||
entries: arr(candidate.entries),
|
||||
};
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Canonicalize a workspace/session summary from `workspace.query{kind:"sessions"}`. */
|
||||
export function normalizeSessionSummary(raw: unknown, workspaceId: string, existing?: SessionState): SessionState {
|
||||
const record = rec(raw) ?? {};
|
||||
const sessionId = str(record.sessionId ?? record.session_id ?? record.id) ?? existing?.sessionId ?? "";
|
||||
const base = existing ?? emptySessionState({ sessionId, workspaceId });
|
||||
|
||||
const rawStatus = str(record.status);
|
||||
let status: SessionState["status"] | undefined = rawStatus as SessionState["status"] | undefined;
|
||||
const flags = { ...base.flags };
|
||||
if (rawStatus === "attention") {
|
||||
status = "idle";
|
||||
flags.attention = true;
|
||||
} else if (rawStatus === "done") {
|
||||
status = "idle";
|
||||
flags.done = true;
|
||||
} else if (rawStatus === "error") {
|
||||
status = "idle";
|
||||
flags.error = true;
|
||||
} else if (rawStatus === "dormant") {
|
||||
status = "exited";
|
||||
}
|
||||
if (!status || !STATUSES.has(status)) status = base.status;
|
||||
|
||||
const rawFlags = rec(record.flags);
|
||||
const attentionCount = num(record.attentionCount);
|
||||
if (rawFlags) {
|
||||
flags.attention = rawFlags.attention === true;
|
||||
flags.done = rawFlags.done === true;
|
||||
flags.error = rawFlags.error === true;
|
||||
} else if (attentionCount && attentionCount > 0) {
|
||||
flags.attention = true;
|
||||
}
|
||||
|
||||
const thinkingValue = str(record.thinking);
|
||||
const hasQueue = Array.isArray(record.queue);
|
||||
return {
|
||||
...base,
|
||||
sessionId,
|
||||
workspaceId: str(record.workspaceId) ?? workspaceId,
|
||||
cwd: str(record.cwd) ?? base.cwd,
|
||||
name: record.name === null ? null : (str(record.name) ?? base.name),
|
||||
status,
|
||||
flags,
|
||||
model: record.model !== undefined ? normalizeModelRef(record.model) : base.model,
|
||||
thinking: thinkingValue && THINKING.has(thinkingValue) ? (thinkingValue as ThinkingLevel) : base.thinking,
|
||||
usage: record.usage !== undefined ? ({ ...EMPTY_USAGE, ...(rec(record.usage) ?? {}) } as SessionState["usage"]) : base.usage,
|
||||
contextUsage:
|
||||
record.contextUsage !== undefined
|
||||
? ((rec(record.contextUsage) as unknown as SessionState["contextUsage"]) ?? null)
|
||||
: base.contextUsage,
|
||||
queue: hasQueue ? arr(record.queue) : base.queue,
|
||||
todos: Array.isArray(record.todos) ? arr(record.todos) : base.todos,
|
||||
tasks: Array.isArray(record.tasks) ? arr(record.tasks) : base.tasks,
|
||||
batches: Array.isArray(record.batches) ? arr(record.batches) : base.batches,
|
||||
subagents: Array.isArray(record.subagents) ? arr(record.subagents) : base.subagents,
|
||||
attention: Array.isArray(record.attention) ? arr(record.attention) : base.attention,
|
||||
entries: Array.isArray(record.entries) ? arr<Entry>(record.entries) : base.entries,
|
||||
};
|
||||
}
|
||||
|
||||
/** Parse `{sessions:[...]}` (also bare arrays) into render states. */
|
||||
export function normalizeSessionsPayload(
|
||||
raw: unknown,
|
||||
workspaceId: string,
|
||||
existing: SessionState[] = [],
|
||||
): SessionState[] {
|
||||
const record = rec(raw);
|
||||
const list = Array.isArray(raw) ? raw : arr(record?.sessions ?? record?.items);
|
||||
const byId = new Map(existing.map((session) => [session.sessionId, session]));
|
||||
return list
|
||||
.map((entry) => normalizeSessionSummary(entry, workspaceId, byId.get(str(rec(entry)?.sessionId ?? rec(entry)?.id) ?? "")))
|
||||
.filter((session) => session.sessionId !== "");
|
||||
}
|
||||
|
||||
function attentionPending(state: SessionState): boolean {
|
||||
return state.flags.attention || state.attention.length > 0;
|
||||
}
|
||||
|
||||
/** `:PiSessions` status matrix → base.css dot class. */
|
||||
export function sessionDot(state: SessionState): DotStatus {
|
||||
if (attentionPending(state)) return "attention";
|
||||
if (state.status === "busy" || state.status === "starting") return "busy";
|
||||
if (state.status === "compacting") return "compacting";
|
||||
if (state.status === "interrupted") return "attention";
|
||||
if (state.status === "exited") return "exited";
|
||||
if (state.flags.error) return "err";
|
||||
if (state.flags.done) return "ok";
|
||||
return "idle";
|
||||
}
|
||||
|
||||
/** i18n key under `state.*` for the current session status. */
|
||||
export function sessionStatusKey(state: SessionState): string {
|
||||
if (attentionPending(state)) return "attention";
|
||||
if (state.status === "busy" || state.status === "starting") return "busy";
|
||||
if (state.status === "compacting") return "compacting";
|
||||
if (state.status === "interrupted") return "interrupted";
|
||||
if (state.status === "exited") return "exited";
|
||||
if (state.flags.error) return "error";
|
||||
if (state.flags.done) return "done";
|
||||
return "idle";
|
||||
}
|
||||
|
||||
/** Flatten a subagent tree into render rows with their indent depth. */
|
||||
export function flattenSubagents(
|
||||
list: SessionState["subagents"] | undefined,
|
||||
depth = 0,
|
||||
): { subagent: NonNullable<SessionState["subagents"]>[number]; depth: number }[] {
|
||||
const out: { subagent: NonNullable<SessionState["subagents"]>[number]; depth: number }[] = [];
|
||||
for (const subagent of list ?? []) {
|
||||
out.push({ subagent, depth });
|
||||
out.push(...flattenSubagents(subagent.children, depth + 1));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function findSubagent(
|
||||
list: SessionState["subagents"] | undefined,
|
||||
predicate: (subagent: NonNullable<SessionState["subagents"]>[number]) => boolean,
|
||||
): NonNullable<SessionState["subagents"]>[number] | undefined {
|
||||
for (const subagent of list ?? []) {
|
||||
if (predicate(subagent)) return subagent;
|
||||
const found = findSubagent(subagent.children, predicate);
|
||||
if (found) return found;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export type { ProjectedEntry };
|
||||
@@ -0,0 +1,427 @@
|
||||
import type { SessionState, Subagent, WorkspaceInfo } from "@protocol/types";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Empty } from "@/components/ui/empty";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { StatusDot, subagentDotClass } from "@/components/ui/status-dot";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { flattenSubagents, sessionDot, sessionStatusKey } from "./session-state";
|
||||
|
||||
export interface SessionTreeProps {
|
||||
sessions: SessionState[];
|
||||
workspaces?: WorkspaceInfo[];
|
||||
activeWorkspaceId?: string | null;
|
||||
selectedId?: string | null;
|
||||
filter: string;
|
||||
collapsed: Record<string, boolean>;
|
||||
connected?: boolean;
|
||||
creating?: boolean;
|
||||
onFilter: (value: string) => void;
|
||||
onToggleCollapse: (id: string) => void;
|
||||
onToggleAll: () => void;
|
||||
onSelectSession: (id: string) => void;
|
||||
onSelectWorkspace?: (id: string) => void;
|
||||
onNewSession: () => void;
|
||||
onRenameSession: (session: SessionState) => void;
|
||||
onCloseSession: (session: SessionState) => void;
|
||||
onOpenSubagent?: (session: SessionState, subagent: Subagent) => void;
|
||||
onRenameSubagent?: (subagent: Subagent) => void;
|
||||
onCloseDrawer?: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function sessionName(session: SessionState, fallback: string): string {
|
||||
return session.name?.trim() || fallback;
|
||||
}
|
||||
|
||||
function matchesFilter(session: SessionState, filter: string, fallback: string): boolean {
|
||||
if (!filter) return true;
|
||||
const needle = filter.toLowerCase();
|
||||
if (sessionName(session, fallback).toLowerCase().includes(needle)) return true;
|
||||
return flattenSubagents(session.subagents).some(({ subagent }) =>
|
||||
(subagent.name ?? "").toLowerCase().includes(needle),
|
||||
);
|
||||
}
|
||||
|
||||
function ChevronToggle({
|
||||
hasChildren,
|
||||
collapsed,
|
||||
onClick,
|
||||
}: {
|
||||
hasChildren: boolean;
|
||||
collapsed: boolean;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={cn("tree-toggle", hasChildren ? (collapsed ? undefined : "open") : "leaf")}
|
||||
aria-label={collapsed ? t("chat.unfold") : t("chat.fold")}
|
||||
aria-expanded={hasChildren ? !collapsed : undefined}
|
||||
tabIndex={hasChildren ? 0 : -1}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
if (hasChildren) onClick();
|
||||
}}
|
||||
>
|
||||
<Icon name="chevron-right" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function SubagentRow({
|
||||
session,
|
||||
subagent,
|
||||
collapsed,
|
||||
onToggleCollapse,
|
||||
onOpenSubagent,
|
||||
onRenameSubagent,
|
||||
}: {
|
||||
session: SessionState;
|
||||
subagent: Subagent;
|
||||
collapsed: Record<string, boolean>;
|
||||
onToggleCollapse: (id: string) => void;
|
||||
onOpenSubagent?: (session: SessionState, subagent: Subagent) => void;
|
||||
onRenameSubagent?: (subagent: Subagent) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const children = subagent.children ?? [];
|
||||
const isCollapsed = collapsed[subagent.id] === true;
|
||||
const status = t(`state.${subagent.status}`);
|
||||
const name = subagent.name ?? subagent.id;
|
||||
return (
|
||||
<li>
|
||||
<div
|
||||
className="tree-row tree-row--sub"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={name}
|
||||
onClick={() => onOpenSubagent?.(session, subagent)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
onOpenSubagent?.(session, subagent);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ChevronToggle
|
||||
hasChildren={children.length > 0}
|
||||
collapsed={isCollapsed}
|
||||
onClick={() => onToggleCollapse(subagent.id)}
|
||||
/>
|
||||
<span className={cn("dot", subagentDotClass(subagent.status))} title={status} />
|
||||
<span className="t-main">
|
||||
<span className="t-name truncate">{name}</span>
|
||||
<span className="t-sub truncate muted">
|
||||
{subagent.model ?? "—"}
|
||||
{subagent.thinking ? ` · ${subagent.thinking}` : ""}
|
||||
</span>
|
||||
</span>
|
||||
<span className="t-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
title={t("chat.preview")}
|
||||
aria-label={t("chat.previewSubagent")}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onOpenSubagent?.(session, subagent);
|
||||
}}
|
||||
>
|
||||
<Icon name="eye" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
title={t("chat.rename")}
|
||||
aria-label={t("chat.renameSubagentAria")}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onRenameSubagent?.(subagent);
|
||||
}}
|
||||
>
|
||||
<Icon name="edit" />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
{children.length && !isCollapsed ? (
|
||||
<ul>
|
||||
{children.map((child) => (
|
||||
<SubagentRow
|
||||
key={child.id}
|
||||
session={session}
|
||||
subagent={child}
|
||||
collapsed={collapsed}
|
||||
onToggleCollapse={onToggleCollapse}
|
||||
onOpenSubagent={onOpenSubagent}
|
||||
onRenameSubagent={onRenameSubagent}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function SessionRow({
|
||||
session,
|
||||
selected,
|
||||
collapsed,
|
||||
onToggleCollapse,
|
||||
onSelectSession,
|
||||
onRenameSession,
|
||||
onCloseSession,
|
||||
onOpenSubagent,
|
||||
onRenameSubagent,
|
||||
}: {
|
||||
session: SessionState;
|
||||
selected: boolean;
|
||||
collapsed: Record<string, boolean>;
|
||||
onToggleCollapse: (id: string) => void;
|
||||
onSelectSession: (id: string) => void;
|
||||
onRenameSession: (session: SessionState) => void;
|
||||
onCloseSession: (session: SessionState) => void;
|
||||
onOpenSubagent?: (session: SessionState, subagent: Subagent) => void;
|
||||
onRenameSubagent?: (subagent: Subagent) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const subagents = session.subagents ?? [];
|
||||
const isCollapsed = collapsed[session.sessionId] === true;
|
||||
const dot = sessionDot(session);
|
||||
const status = t(`state.${sessionStatusKey(session)}`);
|
||||
const name = sessionName(session, session.sessionId);
|
||||
return (
|
||||
<li>
|
||||
<div
|
||||
className={cn("tree-row", selected && "selected")}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={name}
|
||||
aria-current={selected ? "true" : undefined}
|
||||
onClick={() => onSelectSession(session.sessionId)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
onSelectSession(session.sessionId);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ChevronToggle
|
||||
hasChildren={subagents.length > 0}
|
||||
collapsed={isCollapsed}
|
||||
onClick={() => onToggleCollapse(session.sessionId)}
|
||||
/>
|
||||
<StatusDot status={dot} title={status} />
|
||||
<span className="t-main">
|
||||
<span className="t-name truncate">
|
||||
{name}
|
||||
{session.flags.attention && session.attention.length ? (
|
||||
<Badge tone="warn">{`!${session.attention.length}`}</Badge>
|
||||
) : null}
|
||||
</span>
|
||||
<span className="t-sub truncate muted">
|
||||
{session.model?.id ?? "—"}
|
||||
{session.thinking ? ` · ${session.thinking}` : ""}
|
||||
</span>
|
||||
</span>
|
||||
{subagents.length ? (
|
||||
<span className="t-meta" title={t("chat.subagentCount", { n: subagents.length })}>
|
||||
{`(${subagents.length})`}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="t-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
title={t("chat.rename")}
|
||||
aria-label={t("chat.renameSession")}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onRenameSession(session);
|
||||
}}
|
||||
>
|
||||
<Icon name="edit" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn icon-btn--danger"
|
||||
title={t("chat.closeProcess")}
|
||||
aria-label={t("chat.closeProcess")}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onCloseSession(session);
|
||||
}}
|
||||
>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
{subagents.length && !isCollapsed ? (
|
||||
<ul>
|
||||
{subagents.map((subagent) => (
|
||||
<SubagentRow
|
||||
key={subagent.id}
|
||||
session={session}
|
||||
subagent={subagent}
|
||||
collapsed={collapsed}
|
||||
onToggleCollapse={onToggleCollapse}
|
||||
onOpenSubagent={onOpenSubagent}
|
||||
onRenameSubagent={onRenameSubagent}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/** Left sidebar: workspace picker + indent-only session/subagent tree. */
|
||||
export function SessionTree({
|
||||
sessions,
|
||||
workspaces = [],
|
||||
activeWorkspaceId,
|
||||
selectedId,
|
||||
filter,
|
||||
collapsed,
|
||||
connected = false,
|
||||
creating = false,
|
||||
onFilter,
|
||||
onToggleCollapse,
|
||||
onToggleAll,
|
||||
onSelectSession,
|
||||
onSelectWorkspace,
|
||||
onNewSession,
|
||||
onRenameSession,
|
||||
onCloseSession,
|
||||
onOpenSubagent,
|
||||
onRenameSubagent,
|
||||
onCloseDrawer,
|
||||
className,
|
||||
}: SessionTreeProps) {
|
||||
const { t } = useTranslation();
|
||||
const visible = sessions.filter((session) => matchesFilter(session, filter, session.sessionId));
|
||||
const allIds = sessions.flatMap((session) => [
|
||||
session.sessionId,
|
||||
...flattenSubagents(session.subagents).map(({ subagent }) => subagent.id),
|
||||
]);
|
||||
const anyOpen = allIds.some((id) => !collapsed[id]);
|
||||
const activeWorkspace = workspaces.find((workspace) => workspace.workspaceId === activeWorkspaceId);
|
||||
const workspaceLabel = activeWorkspace?.name ?? activeWorkspace?.cwd ?? t("chat.workspace");
|
||||
|
||||
return (
|
||||
<div className={cn("tree-pane__inner", className)} aria-label={t("chat.treeAria")}>
|
||||
<div className="pane-head">
|
||||
{workspaces.length ? (
|
||||
<div className="row">
|
||||
<select
|
||||
className="select tree-workspace"
|
||||
aria-label={t("chat.workspace")}
|
||||
value={activeWorkspaceId ?? ""}
|
||||
onChange={(event) => onSelectWorkspace?.(event.target.value)}
|
||||
title={activeWorkspace?.cwd ?? workspaceLabel}
|
||||
>
|
||||
{workspaces.map((workspace) => (
|
||||
<option key={workspace.workspaceId} value={workspace.workspaceId}>
|
||||
{workspace.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{onCloseDrawer ? (
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn tree-close"
|
||||
title={t("common.close")}
|
||||
aria-label={t("chat.closeTree")}
|
||||
onClick={onCloseDrawer}
|
||||
>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="row">
|
||||
<Input
|
||||
type="search"
|
||||
className="tree-search"
|
||||
value={filter}
|
||||
placeholder={t("chat.search")}
|
||||
aria-label={t("chat.searchAria")}
|
||||
onChange={(event) => onFilter(event.target.value)}
|
||||
/>
|
||||
{onCloseDrawer && !workspaces.length ? (
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn tree-close"
|
||||
title={t("common.close")}
|
||||
aria-label={t("chat.closeTree")}
|
||||
onClick={onCloseDrawer}
|
||||
>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="row">
|
||||
<button type="button" className="btn btn--sm" onClick={onNewSession} disabled={creating}>
|
||||
<Icon name="plus" />
|
||||
{t("chat.newSession")}
|
||||
</button>
|
||||
<div className="spacer" />
|
||||
<span className="tree-conn">
|
||||
<StatusDot status={connected ? "ok" : "exited"} />
|
||||
<span className="muted">{t(connected ? "state.online" : "state.offline")}</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
title={t("chat.toggleAll")}
|
||||
aria-label={t("chat.toggleAllAria")}
|
||||
onClick={onToggleAll}
|
||||
>
|
||||
<Icon name={anyOpen ? "chevron-down" : "chevron-right"} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="pane-scroll">
|
||||
{visible.length ? (
|
||||
<ul className="tree">
|
||||
{visible.map((session) => (
|
||||
<SessionRow
|
||||
key={session.sessionId}
|
||||
session={session}
|
||||
selected={session.sessionId === selectedId}
|
||||
collapsed={collapsed}
|
||||
onToggleCollapse={onToggleCollapse}
|
||||
onSelectSession={onSelectSession}
|
||||
onRenameSession={onRenameSession}
|
||||
onCloseSession={onCloseSession}
|
||||
onOpenSubagent={onOpenSubagent}
|
||||
onRenameSubagent={onRenameSubagent}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
) : sessions.length ? (
|
||||
<Empty
|
||||
icon={<Icon name="search" />}
|
||||
title={t("chat.noMatch")}
|
||||
description={t("chat.tryOther")}
|
||||
/>
|
||||
) : (
|
||||
<Empty
|
||||
icon={<Icon name="chat" />}
|
||||
title={t("chat.noSessions")}
|
||||
description={t("chat.noSessionsText")}
|
||||
action={
|
||||
<button type="button" className="btn btn--sm" onClick={onNewSession} disabled={creating}>
|
||||
<Icon name="plus" />
|
||||
{t("chat.newSession")}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
import type { SessionState, Subagent, TaskItem } from "@protocol/types";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Badge, type BadgeProps } from "@/components/ui/badge";
|
||||
import { Empty } from "@/components/ui/empty";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { StatusDot } from "@/components/ui/status-dot";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { TodoList } from "./blocks";
|
||||
import { formatDuration } from "./format";
|
||||
import { flattenSubagents } from "./session-state";
|
||||
import type { PanelTab } from "./store";
|
||||
|
||||
const SUB_BADGE: Record<string, { tone: BadgeProps["tone"]; label: string }> = {
|
||||
active: { tone: "info", label: "active" },
|
||||
completed: { tone: "ok", label: "completed" },
|
||||
failed: { tone: "err", label: "failed" },
|
||||
interrupted: { tone: "warn", label: "interrupted" },
|
||||
dormant: { tone: "default", label: "dormant" },
|
||||
};
|
||||
|
||||
function subagentStatus(status: Subagent["status"]) {
|
||||
return SUB_BADGE[status] ?? { tone: "default" as const, label: status };
|
||||
}
|
||||
|
||||
function taskDot(status: TaskItem["status"]): "busy" | "ok" | "err" | "idle" {
|
||||
if (status === "running") return "busy";
|
||||
if (status === "completed") return "ok";
|
||||
if (status === "failed") return "err";
|
||||
return "idle";
|
||||
}
|
||||
|
||||
export interface SidePanelProps {
|
||||
session: SessionState;
|
||||
tab: PanelTab;
|
||||
onTab: (tab: PanelTab) => void;
|
||||
onDispatch: () => void;
|
||||
onOpenSubagent: (subagent: Subagent) => void;
|
||||
onOpenTask: (task: TaskItem) => void;
|
||||
onStopTask: (task: TaskItem) => void;
|
||||
onCloseDrawer?: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** Right panel: Subagents / Todo / Tasks (tabs + counts + empty states). */
|
||||
export function SidePanel({
|
||||
session,
|
||||
tab,
|
||||
onTab,
|
||||
onDispatch,
|
||||
onOpenSubagent,
|
||||
onOpenTask,
|
||||
onStopTask,
|
||||
onCloseDrawer,
|
||||
className,
|
||||
}: SidePanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const subagents = flattenSubagents(session.subagents);
|
||||
const tasks = session.tasks;
|
||||
const tabs: { id: PanelTab; label: string; count: number }[] = [
|
||||
{ id: "subagents", label: t("chat.tabSubagents"), count: subagents.length },
|
||||
{ id: "todo", label: t("chat.tabTodo"), count: session.todos.length },
|
||||
{ id: "tasks", label: t("chat.tabTasks"), count: tasks.length },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className={cn("panel-pane__inner", className)}>
|
||||
<div className="tabs panel-tabs" role="tablist" aria-label={t("chat.panel")}>
|
||||
{tabs.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === item.id}
|
||||
className={cn("tab", tab === item.id && "active")}
|
||||
onClick={() => onTab(item.id)}
|
||||
>
|
||||
{item.label}
|
||||
{item.count ? <span className="badge">{item.count}</span> : null}
|
||||
</button>
|
||||
))}
|
||||
<div className="spacer" />
|
||||
{onCloseDrawer ? (
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn panel-close"
|
||||
title={t("chat.closePanel")}
|
||||
aria-label={t("chat.closePanel")}
|
||||
onClick={onCloseDrawer}
|
||||
>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="panel-scroll">
|
||||
<div className="panel__body stack">
|
||||
{tab === "subagents" ? (
|
||||
<>
|
||||
<div className="row">
|
||||
<span className="muted grow">
|
||||
{t("chat.currentSubagents", { n: subagents.length })}
|
||||
</span>
|
||||
<button type="button" className="btn btn--sm btn--primary" onClick={onDispatch}>
|
||||
<Icon name="plus" />
|
||||
{t("chat.dispatch")}
|
||||
</button>
|
||||
</div>
|
||||
{subagents.length ? (
|
||||
<div className="stack">
|
||||
{subagents.map(({ subagent, depth }) => {
|
||||
const badge = subagentStatus(subagent.status);
|
||||
return (
|
||||
<div
|
||||
key={subagent.id}
|
||||
className={cn("sub-item", depth > 0 && "sub-item--nested")}
|
||||
style={depth ? { marginLeft: `${depth * 16}px` } : undefined}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => onOpenSubagent(subagent)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
onOpenSubagent(subagent);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"dot",
|
||||
subagent.status === "active"
|
||||
? "dot--busy"
|
||||
: subagent.status === "completed"
|
||||
? "dot--ok"
|
||||
: subagent.status === "failed"
|
||||
? "dot--err"
|
||||
: subagent.status === "interrupted"
|
||||
? "dot--attention"
|
||||
: "dot--exited",
|
||||
)}
|
||||
/>
|
||||
<span className="sub-item__main">
|
||||
<span className="sub-item__name truncate">
|
||||
{subagent.name ?? subagent.id}
|
||||
</span>
|
||||
<span className="sub-item__meta muted truncate">
|
||||
{subagent.model ?? "—"}
|
||||
{subagent.thinking ? ` · ${subagent.thinking}` : ""}
|
||||
</span>
|
||||
</span>
|
||||
<Badge tone={badge.tone}>{t(`state.${badge.label}`)}</Badge>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<Empty
|
||||
icon={<Icon name="branch" />}
|
||||
title={t("chat.noSubagents")}
|
||||
description={t("chat.noSubagentsText")}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{tab === "todo" ? (
|
||||
session.todos.length ? (
|
||||
<>
|
||||
<div className="row">
|
||||
<span className="muted grow">
|
||||
{t("chat.progress", {
|
||||
done: session.todos.filter((item) => item.status === "completed").length,
|
||||
total: session.todos.length,
|
||||
})}
|
||||
</span>
|
||||
<Badge>{t("common.readonly")}</Badge>
|
||||
</div>
|
||||
<Progress
|
||||
value={session.todos.filter((item) => item.status === "completed").length}
|
||||
max={session.todos.length || 1}
|
||||
/>
|
||||
<TodoList items={session.todos} idPrefix="panel-todo" />
|
||||
<div className="muted panel__note">{t("chat.todoNote")}</div>
|
||||
</>
|
||||
) : (
|
||||
<Empty
|
||||
icon={<Icon name="todo" />}
|
||||
title={t("chat.noTodo")}
|
||||
description={t("chat.noTodoText")}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
|
||||
{tab === "tasks" ? (
|
||||
tasks.length ? (
|
||||
tasks.map((task) => {
|
||||
const running = task.status === "running";
|
||||
const duration = running ? Date.now() - task.startTime : (task.durationMs ?? 0);
|
||||
return (
|
||||
<div
|
||||
key={task.id}
|
||||
className="task-item"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => onOpenTask(task)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
onOpenTask(task);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<StatusDot status={taskDot(task.status)} />
|
||||
<span className="grow">
|
||||
<span className="task-item__cmd mono truncate" title={task.command}>
|
||||
{task.command}
|
||||
</span>
|
||||
<span className="task-item__meta muted">
|
||||
{running ? <Spinner /> : null}
|
||||
<span>{formatDuration(duration)}</span>
|
||||
{task.exitCode != null ? (
|
||||
<Badge tone={task.exitCode === 0 ? "ok" : "err"}>
|
||||
{`exit ${task.exitCode}`}
|
||||
</Badge>
|
||||
) : (
|
||||
<span>{t(`state.${task.status}`)}</span>
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
{running ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--sm btn--danger"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onStopTask(task);
|
||||
}}
|
||||
>
|
||||
{t("common.stop")}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<Empty
|
||||
icon={<Icon name="terminal" />}
|
||||
title={t("chat.noTasks")}
|
||||
description={t("chat.noTasksText")}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import type { TaskItem } from "@protocol/types";
|
||||
import { create } from "zustand";
|
||||
|
||||
import type { EntriesCursor, ProjectedEntry } from "@/lib/entry-projection";
|
||||
import { prependUnique } from "@/lib/entry-projection";
|
||||
|
||||
export type PanelTab = "subagents" | "todo" | "tasks";
|
||||
|
||||
export interface Attachment {
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
/** Base64 payload (no data: prefix), ready for `prompt.send {images}`. */
|
||||
data: string;
|
||||
/** Data URL for the preview thumbnail. */
|
||||
preview: string;
|
||||
}
|
||||
|
||||
export interface HistoryState {
|
||||
entries: ProjectedEntry[];
|
||||
cursor: EntriesCursor | null;
|
||||
loaded: boolean;
|
||||
loadingInitial: boolean;
|
||||
loadingOlder: boolean;
|
||||
error: string | null;
|
||||
/** Incremented by `resync_required`; the history hook reloads when it changes. */
|
||||
resyncToken: number;
|
||||
}
|
||||
|
||||
export const EMPTY_HISTORY: HistoryState = {
|
||||
entries: [],
|
||||
cursor: null,
|
||||
loaded: false,
|
||||
loadingInitial: false,
|
||||
loadingOlder: false,
|
||||
error: null,
|
||||
resyncToken: 0,
|
||||
};
|
||||
|
||||
export interface PreviewTarget {
|
||||
sessionId: string;
|
||||
subagentId: string;
|
||||
}
|
||||
|
||||
export interface ChatStore {
|
||||
history: Record<string, HistoryState>;
|
||||
tab: PanelTab;
|
||||
filter: string;
|
||||
collapsed: Record<string, boolean>;
|
||||
treeOpen: boolean;
|
||||
panelOpen: boolean;
|
||||
treeCollapsed: boolean;
|
||||
treeWidth: number;
|
||||
panelWidth: number;
|
||||
sending: { sessionId: string; text: string } | null;
|
||||
attachments: Attachment[];
|
||||
preview: PreviewTarget | null;
|
||||
taskOutput: TaskItem | null;
|
||||
dispatchOpen: boolean;
|
||||
|
||||
setTab: (tab: PanelTab) => void;
|
||||
setFilter: (filter: string) => void;
|
||||
toggleCollapsed: (id: string) => void;
|
||||
setAllCollapsed: (ids: string[], collapsed: boolean) => void;
|
||||
setTreeOpen: (open: boolean) => void;
|
||||
setPanelOpen: (open: boolean) => void;
|
||||
setTreeCollapsed: (collapsed: boolean) => void;
|
||||
setWidths: (widths: { treeWidth?: number; panelWidth?: number }) => void;
|
||||
closeDrawers: () => void;
|
||||
|
||||
setSending: (sending: { sessionId: string; text: string } | null) => void;
|
||||
addAttachment: (attachment: Attachment) => void;
|
||||
removeAttachment: (id: string) => void;
|
||||
clearAttachments: () => void;
|
||||
setPreview: (preview: PreviewTarget | null) => void;
|
||||
setTaskOutput: (task: TaskItem | null) => void;
|
||||
setDispatchOpen: (open: boolean) => void;
|
||||
|
||||
beginInitial: (sessionId: string) => void;
|
||||
beginOlder: (sessionId: string) => void;
|
||||
receiveInitial: (sessionId: string, entries: ProjectedEntry[], cursor: EntriesCursor) => void;
|
||||
receiveOlder: (sessionId: string, entries: ProjectedEntry[], cursor: EntriesCursor) => void;
|
||||
historyError: (sessionId: string, error: string) => void;
|
||||
bumpResync: (sessionId: string) => void;
|
||||
clearHistory: (sessionId: string) => void;
|
||||
}
|
||||
|
||||
function updateHistory(
|
||||
state: ChatStore,
|
||||
sessionId: string,
|
||||
patch: Partial<HistoryState>,
|
||||
): Pick<ChatStore, "history"> {
|
||||
const current = state.history[sessionId] ?? EMPTY_HISTORY;
|
||||
return { history: { ...state.history, [sessionId]: { ...current, ...patch } } };
|
||||
}
|
||||
|
||||
export const useChatStore = create<ChatStore>((set) => ({
|
||||
history: {},
|
||||
tab: "subagents",
|
||||
filter: "",
|
||||
collapsed: {},
|
||||
treeOpen: false,
|
||||
panelOpen: false,
|
||||
treeCollapsed: false,
|
||||
treeWidth: 300,
|
||||
panelWidth: 340,
|
||||
sending: null,
|
||||
attachments: [],
|
||||
preview: null,
|
||||
taskOutput: null,
|
||||
dispatchOpen: false,
|
||||
|
||||
setTab: (tab) => set({ tab }),
|
||||
setFilter: (filter) => set({ filter }),
|
||||
toggleCollapsed: (id) =>
|
||||
set((state) => {
|
||||
const collapsed = { ...state.collapsed };
|
||||
if (collapsed[id]) delete collapsed[id];
|
||||
else collapsed[id] = true;
|
||||
return { collapsed };
|
||||
}),
|
||||
setAllCollapsed: (ids, collapsed) =>
|
||||
set(() => ({ collapsed: collapsed ? Object.fromEntries(ids.map((id) => [id, true])) : {} })),
|
||||
setTreeOpen: (treeOpen) => set({ treeOpen }),
|
||||
setPanelOpen: (panelOpen) => set({ panelOpen }),
|
||||
setTreeCollapsed: (treeCollapsed) => set({ treeCollapsed }),
|
||||
setWidths: (widths) => set(widths),
|
||||
closeDrawers: () => set({ treeOpen: false, panelOpen: false }),
|
||||
|
||||
setSending: (sending) => set({ sending }),
|
||||
addAttachment: (attachment) => set((state) => ({ attachments: [...state.attachments, attachment] })),
|
||||
removeAttachment: (id) => set((state) => ({ attachments: state.attachments.filter((item) => item.id !== id) })),
|
||||
clearAttachments: () => set({ attachments: [] }),
|
||||
setPreview: (preview) => set({ preview }),
|
||||
setTaskOutput: (taskOutput) => set({ taskOutput }),
|
||||
setDispatchOpen: (dispatchOpen) => set({ dispatchOpen }),
|
||||
|
||||
beginInitial: (sessionId) =>
|
||||
set((state) => updateHistory(state, sessionId, { loadingInitial: true, error: null })),
|
||||
beginOlder: (sessionId) =>
|
||||
set((state) => updateHistory(state, sessionId, { loadingOlder: true, error: null })),
|
||||
receiveInitial: (sessionId, entries, cursor) =>
|
||||
set((state) => {
|
||||
const current = state.history[sessionId] ?? EMPTY_HISTORY;
|
||||
return updateHistory(state, sessionId, {
|
||||
entries: entries.length || !current.entries.length ? entries : current.entries,
|
||||
cursor,
|
||||
loaded: true,
|
||||
loadingInitial: false,
|
||||
loadingOlder: false,
|
||||
error: null,
|
||||
resyncToken: current.resyncToken,
|
||||
});
|
||||
}),
|
||||
receiveOlder: (sessionId, entries, cursor) =>
|
||||
set((state) => {
|
||||
const current = state.history[sessionId] ?? EMPTY_HISTORY;
|
||||
return updateHistory(state, sessionId, {
|
||||
entries: prependUnique(current.entries, entries) as ProjectedEntry[],
|
||||
cursor,
|
||||
loadingOlder: false,
|
||||
error: null,
|
||||
});
|
||||
}),
|
||||
historyError: (sessionId, error) =>
|
||||
set((state) =>
|
||||
updateHistory(state, sessionId, {
|
||||
loadingInitial: false,
|
||||
loadingOlder: false,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
bumpResync: (sessionId) =>
|
||||
set((state) => {
|
||||
const current = state.history[sessionId] ?? EMPTY_HISTORY;
|
||||
return updateHistory(state, sessionId, {
|
||||
loaded: false,
|
||||
loadingInitial: false,
|
||||
loadingOlder: false,
|
||||
error: null,
|
||||
resyncToken: current.resyncToken + 1,
|
||||
});
|
||||
}),
|
||||
clearHistory: (sessionId) =>
|
||||
set((state) => {
|
||||
const history = { ...state.history };
|
||||
delete history[sessionId];
|
||||
return { history };
|
||||
}),
|
||||
}));
|
||||
Reference in new issue
Block a user