feat(web): port the pi2-web-ui-design v0.1.1 UI

Sync the React console with the v0.1.1 prototype (20 CHGs): Quiet Workbench
shell, Chat IA v3, tool-family rendering, and the mobile page pill.

Shell / tokens (CHG-01/04/15/20):
- tokens.css rewritten from the prototype (three-layer light/dark/system),
  `--tabbar-h` removed, new faint/border-subtle/surface-1-2/fs-*/dur-*/reading-max
- 56px icon-only nav rail/sidebar (44x44 hit targets, CSS tooltips, active is a
  solid primary fill, no left bar), 52px topbar, merged preferences menu,
  ⌘K/Cmd-K palette
- `<600` gets a topbar page pill + page sheet; the bottom tabbar is gone

Pages (CHG-01): workspaces becomes a card grid with whole-card links and a
320px recent-activity column; status gets four metric tiles + a zero-primary
layout; connect gets a two-column hero, one primary per state and a collapsed
manual form.

Chat IA v3 (CHG-02/10-14/16-19): two columns, single-workspace tree with a
workspace switch, single-line rows with attention, body-level row popover,
session tray (todo/tasks) replacing the right panel, context ring moved into a
composer telemetry line, right-aligned user messages, queued messages as one
stream entity plus a composer status bar, and an in-place subagent child view.

Tool rendering (CHG-05/06/09): new `features/chat/tools` module — one row per
call, DTO adapter for the daemon's block shape, 11 kind families, state
semantics ("one state, one meaning"), 44px touch targets and the diff row
contrast fix.

i18n: 729 keys per language (zh/en parity checked), 0 unresolved keys.

Verification: web typecheck + 297 vitest + vite build green, root typecheck
green, `scripts/smoke.sh` green, and a new visual harness
(`scripts/ui-mock-server.mjs` + `scripts/ui-shots.mjs`, docs/ui-parity.md)
shoots 4 pages x 3 viewports x 2 themes = 24 screenshots clean with
overflow/console/primary/tabbar assertions. `scripts/e2e/ui-e2e.mjs` selectors
are updated to the new DOM; that suite still needs a real pi + nvim to run.
This commit is contained in:
yuez committed 2026-10-26 20:28:47 +08:00
1 parent a8425a51b6
commit 88e73c7737
98 files changed
+17676 -2871

No files matched your search

+60 -82
View File
@@ -1,4 +1,4 @@
import type { Batch, Block, Entry, TodoItem } from "@protocol/types";
import type { Batch, Entry, TodoItem } from "@protocol/types";
import { useState } from "react";
import { useTranslation } from "react-i18next";
@@ -6,32 +6,60 @@ 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";
import "@/styles/pages/chat-msg.css";
import { formatClock } from "./format";
import { fromPi2Block, ToolRow } from "./tools";
import type { ToolCtx } from "./tools";
/**
* `notice` entries report on a subagent; the projection may carry its name so the
* meta row can link into the subagent view (prototype `.who--agent.sub-report__link`).
*/
type NoticeEntry = Entry & { subagentName?: string; subagent?: string | { name?: string } };
function noticeSubagentName(entry: Entry): string | undefined {
const notice = entry as NoticeEntry;
if (notice.subagentName) return notice.subagentName;
const subagent = notice.subagent;
if (typeof subagent === "string") return subagent || undefined;
if (subagent && typeof subagent === "object") return subagent.name || undefined;
return undefined;
}
export interface EntryBlockProps {
entry: Entry;
turnStart?: boolean;
/** `false` on same-turn follow-ups: only the turn's first message repeats the meta row. */
showMeta?: boolean;
/** Opens the subagent view from a `notice` (sub-report) meta link. */
onOpenSubagent?: (name: string) => void;
}
function MessageMeta({ entry }: { entry: Entry }) {
function MessageMeta({ entry, onOpenSubagent }: { entry: Entry; onOpenSubagent?: (name: string) => void }) {
const { t } = useTranslation();
const user = entry.role === "user";
const notice = entry.role === "notice";
const subagent = notice ? noticeSubagentName(entry) : undefined;
const label = user ? t("chat.you") : notice ? t("chat.subReport") : "pi2";
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>
{subagent && onOpenSubagent ? (
<button
type="button"
className="who who--agent sub-report__link"
title={t("chat.viewSubagent", { name: subagent })}
onClick={() => onOpenSubagent(subagent)}
>
<Icon name="branch" />
{label}
</button>
) : (
<span className={cn("who", user ? "who--user" : "who--agent")}>
{notice ? <Icon name="branch" /> : null}
{label}
</span>
)}
{user ? (
<RelativeTime ts={entry.ts} className="muted msg__time" />
) : (
@@ -60,69 +88,6 @@ function ThinkingBlock({ text }: { text: string }) {
);
}
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";
@@ -290,18 +255,24 @@ function ErrorBlock({ text }: { text: string }) {
);
}
export function EntryBlock({ entry, turnStart }: EntryBlockProps) {
export function EntryBlock({ entry, turnStart, showMeta, onOpenSubagent }: EntryBlockProps) {
const lastTextIndex = entry.blocks.reduce(
(last, block, index) => (block.type === "text" ? index : last),
-1,
);
// `user` / `notice` are standalone messages and always carry meta; `system` is a
// fallback row (text only, no invented rail); only `assistant` collapses its meta
// when it merely continues the current turn (`renderMessage(m, turnStart, showMeta)`).
const withMeta =
entry.role === "system" ? false : entry.role === "assistant" ? (showMeta ?? turnStart ?? true) : true;
const toolCtx: ToolCtx = onOpenSubagent ? { onOpenSubagent } : {};
return (
<article
className={cn("msg", `msg--${entry.role}`, turnStart && "turn-start")}
data-entry-id={entry.id}
data-role={entry.role}
>
<MessageMeta entry={entry} />
{withMeta ? <MessageMeta entry={entry} onOpenSubagent={onOpenSubagent} /> : null}
{entry.blocks.map((block, index) => {
if (block.type === "text") {
return (
@@ -317,7 +288,14 @@ export function EntryBlock({ entry, turnStart }: EntryBlockProps) {
return <ThinkingBlock key={`${entry.id}-k-${index}`} text={block.text} />;
}
if (block.type === "tool") {
return <ToolBlock key={`${entry.id}-x-${index}`} block={block} />;
// One tool call = one family row (tools/index.ts exit contract).
return (
<ToolRow
key={`${entry.id}-x-${index}`}
tool={fromPi2Block(block, entry.id, { ts: entry.ts })}
ctx={toolCtx}
/>
);
}
return <ErrorBlock key={`${entry.id}-e-${index}`} text={block.text} />;
})}
+184 -176
View File
@@ -4,10 +4,11 @@ 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 { plural } from "@/lib/i18n";
import { cn } from "@/lib/utils";
import "@/styles/pages/chat-composer.css";
import { promptImage, type PromptImage, type PromptMode } from "./commands";
import type { ModelGroup } from "./data";
import { withCurrentModel } from "./data";
@@ -19,13 +20,26 @@ export interface ComposerProps {
models: ModelGroup[];
connected: boolean;
paired?: boolean;
/**
* The optimistic first message of a send. The composer never renders its body
* any more (CHG-2026-10-26-16): it only adds to the pending count while the
* daemon has not projected the message into `session.queue` yet.
*/
sending?: { text: string } | null;
/** `mode` is `follow_up` when the run is busy (queued) and `steer` for an interrupt. */
onSend: (text: string, images: PromptImage[], mode?: PromptMode) => void;
onAbort: () => void;
onRemoveQueue: (id: string) => void;
/** Steering is a session-wide mode, not a per-message flag. */
/**
* Kept for signature compatibility (`pages/chat.tsx` still passes it). Steering
* is a session-wide mode (`queue.setSteer {mode}`), so the composer renders no
* per-message toggle any more — the queued footer in the stream owns it.
*/
onSetSteer: (steer: boolean) => void;
/** Session-level bulk clear for the status bar; falls back to `onRemoveQueue`. */
onClearQueue?: () => void;
/** Authoritative pending count (e.g. including an in-stream queued entity). */
queuedCount?: number;
onSetModel: (model: ModelRef) => void;
onSetThinking: (level: ThinkingLevel) => void;
disabled?: boolean;
@@ -36,7 +50,10 @@ 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. */
/**
* Bottom composer: auto-growing textarea, a `role="status"` pending bar (no queue
* bodies), model/thinking pickers and one circular send slot that turns into abort.
*/
export function Composer({
session,
models,
@@ -46,7 +63,8 @@ export function Composer({
onSend,
onAbort,
onRemoveQueue,
onSetSteer,
onClearQueue,
queuedCount,
onSetModel,
onSetThinking,
disabled = false,
@@ -67,6 +85,17 @@ export function Composer({
const thinking = session?.thinking ?? "off";
const groups = withCurrentModel(models, model);
const hint = !paired ? t("chat.unpairedHint") : !connected ? t("chat.offlineHint") : null;
// The stream owns the single queued entity; the composer only counts. `sending`
// counts once and only until `queue_update` projects the same message.
const pending = Math.max(queuedCount ?? (queue.length || (sending ? 1 : 0)), 0);
const inline = queue.filter((item) => item.steer).length;
const pendingLabel = plural("chat.queueCount", pending, {
defaultValue: pending === 1 ? "{n} pending message" : "{n} pending messages",
});
const hintLabel =
inline > 0
? t("chat.queueCountInline", { n: inline, defaultValue: "{n} inserting now" })
: t("chat.queueAfterTurn", { defaultValue: "Sends after this turn" });
useLayoutEffect(() => {
const element = textareaRef.current;
@@ -92,6 +121,18 @@ export function Composer({
onSend(trimmed, images, mode ?? (busy ? "follow_up" : undefined));
}
/**
* The protocol has no bulk `queue.clear`: `onClearQueue` (one session-level
* command) wins; the fallback removes the projected items one by one.
*/
function clearQueue() {
if (onClearQueue) {
onClearQueue();
return;
}
for (const item of queue) onRemoveQueue(item.id);
}
async function addFiles(files: FileList | File[] | null) {
if (!files) return;
for (const file of Array.from(files)) {
@@ -117,185 +158,152 @@ export function Composer({
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(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")}
data-testid="composer-input"
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">
<div className="composer__inner">
<div
className={cn("composer__queue", pending === 0 && "is-empty")}
role="status"
aria-live="polite"
data-testid="composer-queue"
>
<span className="queue-bar__ico" aria-hidden="true">
<Icon name={inline > 0 ? "zap" : "clock"} />
</span>
<span className="queue-bar__label">{pendingLabel}</span>
<span className="tsep" aria-hidden="true">
·
</span>
<span className="queue-bar__hint">{hintLabel}</span>
<div className="spacer" />
<button
type="button"
className="btn btn--icon btn--ghost"
title={t("chat.addAttachment")}
aria-label={t("chat.addAttachment")}
disabled={!enabled}
onClick={() => setAttachOpen(true)}
className="btn btn--sm btn--ghost queue-bar__clear"
data-testid="composer-queue-clear"
disabled={!enabled || pending === 0}
onClick={clearQueue}
>
<Icon name="plus" />
{t("chat.queueClear", { defaultValue: "Clear queue" })}
</button>
<select
className="select composer__sel"
aria-label={t("chat.model")}
data-testid="composer-model"
value={model ? `${model.provider}/${model.id}` : ""}
disabled={!enabled || !groups.length}
onChange={(event) => {
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")}
data-testid="composer-thinking"
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="ghost"
className="composer__steer"
title={t("chat.steer")}
data-testid="composer-steer"
disabled={!enabled || !text.trim()}
onClick={() => submit("steer")}
>
<Icon name="alert" />
{t("chat.steer")}
</Button>
<Button
variant="danger"
className="composer__abort"
title={t("chat.abortTitle")}
data-testid="composer-abort"
disabled={!connected}
onClick={onAbort}
>
<Icon name="stop" />
{t("chat.abort")}
</Button>
</>
</div>
<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}
<Button
variant="primary"
className="composer__send"
title={t("chat.sendTitle")}
data-testid="composer-send"
disabled={!enabled || !text.trim()}
onClick={() => submit()}
>
<Icon name="send" />
{t("chat.send")}
</Button>
<textarea
ref={textareaRef}
className="textarea composer__ta"
rows={1}
value={text}
placeholder={t("chat.composerPlaceholder")}
aria-label={t("chat.composerAria")}
data-testid="composer-input"
disabled={!enabled}
onChange={(event) => setText(event.target.value)}
onKeyDown={(event) => {
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")}
data-testid="composer-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")}
data-testid="composer-thinking"
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" />
{/*
* One circular slot: send while idle, abort while busy. The
* text label stays screen-reader only so the button keeps a
* textContent of `Send` for the Playwright facts.
*/}
<Button
variant={busy ? "danger" : "primary"}
className={cn("composer__send", busy && "is-busy")}
title={busy ? t("chat.abortTitle") : t("chat.sendTitle")}
data-testid={busy ? "composer-abort" : "composer-send"}
disabled={busy ? !connected : !enabled || !text.trim()}
onClick={busy ? onAbort : () => submit()}
>
<Icon name={busy ? "stop" : "send"} />
<span className="visually-hidden">{busy ? t("chat.abort") : t("chat.send")}</span>
</Button>
</div>
</div>
{hint ? (
<div className="composer__hint" role="status">
<Icon name="alert" />
{hint}
</div>
) : null}
</div>
{hint ? (
<div className="composer__hint" role="status">
<Icon name="alert" />
{hint}
</div>
) : null}
<Modal
open={attachOpen}
+88
View File
@@ -0,0 +1,88 @@
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { cn } from "@/lib/utils";
import type { TrayTab } from "./store";
export interface HeadChipsProps {
/** Completed / total todo items of the current scope (session scope in the child view). */
planDone: number;
planTotal: number;
/** Background tasks in the current scope. */
taskCount: number;
runningTasks: number;
/** Which tray tab is selected — drives `aria-expanded` / `is-open`. */
trayTab: TrayTab;
trayOpen: boolean;
/** Chip click. The chip is a *toggle*: same tab again closes the tray. */
onToggle: (tab: TrayTab) => void;
/** Hands the chip element back so the page can restore focus on close. */
registerTrigger?: (tab: TrayTab, element: HTMLButtonElement | null) => void;
className?: string;
}
/**
* Stream-head chips (v0.1.1 Chat IA v3): `计划 c/t` + `任务 n`.
*
* They replace the old right panel tabs. Both are dialog triggers — the tray
* itself is `role="dialog" aria-modal="false"` anchored under the stream head.
* `.head-chip__label` is hidden below 1150px, so the icons + counts must be
* readable on their own (the `aria-label` carries the full sentence).
*/
export function HeadChips({
planDone,
planTotal,
taskCount,
runningTasks,
trayTab,
trayOpen,
onToggle,
registerTrigger,
className,
}: HeadChipsProps) {
const { t } = useTranslation();
const planOpen = trayOpen && trayTab === "todo";
const tasksOpen = trayOpen && trayTab === "tasks";
const running = runningTasks > 0;
return (
<div className={cn("head-chips", className)} data-testid="head-chips">
<button
type="button"
ref={(element) => registerTrigger?.("todo", element)}
className={cn("head-chip", planOpen && "is-open")}
data-testid="head-chip-plan"
aria-haspopup="dialog"
aria-expanded={planOpen}
aria-controls="chat-tray"
aria-label={t("chat.planAria")}
title={t("chat.planAria")}
onClick={() => onToggle("todo")}
>
<Icon name="todo" />
<span className="head-chip__label">{t("chat.plan")}</span>
<span className="head-chip__count tabular">
{planTotal ? `${planDone}/${planTotal}` : "—"}
</span>
</button>
<button
type="button"
ref={(element) => registerTrigger?.("tasks", element)}
className={cn("head-chip", running && "has-running", tasksOpen && "is-open")}
data-testid="head-chip-tasks"
aria-haspopup="dialog"
aria-expanded={tasksOpen}
aria-controls="chat-tray"
aria-label={t("chat.tasksAria")}
title={t("chat.tasksAria")}
onClick={() => onToggle("tasks")}
>
<Icon name="terminal" />
<span className="head-chip__label">{t("chat.tabTasks")}</span>
{running ? <span className="dot dot--busy" aria-hidden="true" /> : null}
<span className="head-chip__count tabular">{taskCount}</span>
</button>
</div>
);
}
+23 -104
View File
@@ -1,5 +1,4 @@
import type { CSSProperties, ReactNode } from "react";
import { useCallback } from "react";
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
@@ -7,125 +6,45 @@ import { cn } from "@/lib/utils";
export interface ChatLayoutProps {
tree: ReactNode;
stream: ReactNode;
panel: ReactNode;
/** Narrow-viewport tree drawer (≥1000px the tree is a fixed column). */
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.
* Chat shell, v0.1.1 Chat IA v3: **two columns, no right panel**
* (the Todo/Tasks surfaces are the anchored `SessionTray`, not a third pane).
*
* - ≥1100: tree 280px + stream
* - 1000–1099: tree 240px + stream
* - <1000: single column, the tree becomes a left drawer (`.tree-open`)
*
* The tree is fixed and non-collapsible on desktop: there is no rail, no
* resize handle and no keyboard nudge — collapsing is a per-node concern.
* Structural CSS lives in `styles/pages/chat-tray.css`
* (`.chat-page--v3`), visual tokens in `styles/pages/chat.css`.
*/
export function ChatLayout({
tree,
stream,
panel,
treeOpen,
panelOpen,
treeCollapsed,
treeWidth,
panelWidth,
onWidths,
onCloseDrawers,
className,
}: ChatLayoutProps) {
export function ChatLayout({ tree, stream, treeOpen, 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}
className={cn("chat-page", "chat-page--v3", treeOpen && "tree-open", className)}
data-testid="chat-layout"
data-tree-open={treeOpen ? "true" : "false"}
>
<aside className="tree-pane">
<aside className="tree-pane" data-testid="chat-tree-pane">
{tree}
</aside>
{separator("tree")}
<section className="stream-pane">{stream}</section>
{separator("panel")}
<aside className="panel-pane">{panel}</aside>
<section className="stream-pane" data-testid="chat-stream-pane">
{stream}
</section>
<button
type="button"
className="drawer-backdrop"
data-testid="drawer-backdrop"
aria-label={t("common.close")}
tabIndex={treeOpen || panelOpen ? 0 : -1}
tabIndex={treeOpen ? 0 : -1}
onClick={onCloseDrawers}
/>
</div>
+129 -58
View File
@@ -1,4 +1,4 @@
import type { Batch, Entry, SessionState, Subagent, TodoItem } from "@protocol/types";
import type { Batch, Entry, QueueItem, SessionState, Subagent, TodoItem } from "@protocol/types";
import { useVirtualizer } from "@tanstack/react-virtual";
import { useCallback, useLayoutEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -9,23 +9,43 @@ 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 "@/styles/pages/chat-stream.css";
import { BatchBlock, EntryBlock, TodoBlock } from "./blocks";
import { QueuedMessage, type QueuedMessageActions } from "./queued-messages";
import { findSubagent } from "./session-state";
/** Below this many items the DOM list is cheaper than virtualizer bookkeeping. */
export const VIRTUALIZE_THRESHOLD = 30;
/** Synthesised id for the optimistic prompt the daemon has not echoed as an entry yet. */
export const SENDING_QUEUE_ID = "__sending__";
export type StreamItem =
| { kind: "entry"; key: string; entry: Entry; turnStart: boolean }
| { kind: "todo"; key: string; todos: TodoItem[] }
| { kind: "batch"; key: string; batch: Batch };
| { kind: "batch"; key: string; batch: Batch }
/**
* A pending prompt. `session.queue` is not part of `entries` in pi2d (it is a
* `queue_update` projection with no `ts`), so it is appended as one
* synthetic entity per item — the stream is the only place a pending prompt
* is shown as text. `sending` is the optimistic prompt, folded in as one
* more queued variant.
*/
| { kind: "queued"; key: string; item: QueueItem; sending?: boolean };
/**
* 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.
* and the pending queue into one ordered stream. Historical `pi2-todo`
* checkpoints stay inline; when history has none, the current todo list is
* appended as a live block. Queued entities always go last, in queue order
* (`queue_update` sends steering items before follow-ups), with the optimistic
* `sending` prompt ahead of them.
*/
export function buildStreamItems(session: SessionState, entries: Entry[]): StreamItem[] {
export function buildStreamItems(
session: SessionState,
entries: Entry[],
sending?: { text: string } | null,
): StreamItem[] {
const items: StreamItem[] = [];
let hasTodoEntry = false;
entries.forEach((entry, index) => {
@@ -45,15 +65,33 @@ export function buildStreamItems(session: SessionState, entries: Entry[]): Strea
for (const batch of session.batches) {
items.push({ kind: "batch", key: `batch:${batch.batchId}`, batch });
}
if (sending) {
items.push({
kind: "queued",
key: `queued:${SENDING_QUEUE_ID}`,
item: { id: SENDING_QUEUE_ID, text: sending.text, steer: false },
sending: true,
});
}
for (const item of session.queue) {
items.push({ kind: "queued", key: `queued:${item.id}`, item });
}
return items;
}
export interface MessageStreamProps {
/** `queue.setSteer` is a session-wide mode: it is on when every queued item steers. */
export function steerAllOf(queue: QueueItem[]): boolean {
return queue.length > 0 && queue.every((item) => item.steer);
}
export interface MessageStreamProps extends QueuedMessageActions {
session: SessionState;
entries: Entry[];
hasMore: boolean;
loadingOlder: boolean;
error: string | null;
/** Optimistic prompt already handed to the plugin (rendered as a queued variant). */
sending?: { text: string } | null;
onLoadOlder: () => void;
onRetry: () => void;
onOpenSubagent: (subagent: Subagent) => void;
@@ -66,17 +104,25 @@ export function MessageStream({
hasMore,
loadingOlder,
error,
sending = null,
onLoadOlder,
onRetry,
onOpenSubagent,
onRecallQueued,
onRemoveQueued,
onSetSteerAll,
className,
}: MessageStreamProps) {
const { t } = useTranslation();
const items = buildStreamItems(session, entries);
const allItems = buildStreamItems(session, entries, sending);
// Queued entities always live at the tail, so they are rendered outside the
// virtual window (absolute positioning) as a plain flex column.
const items = allItems.filter((item) => item.kind !== "queued");
const queued = allItems.filter((item) => item.kind === "queued");
const steerAll = steerAllOf(session.queue);
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);
@@ -132,7 +178,6 @@ export function MessageStream({
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;
@@ -162,9 +207,33 @@ export function MessageStream({
return <TodoBlock items={item.todos} />;
case "batch":
return <BatchBlock batch={item.batch} onOpenSubagent={openByName} canOpen={canOpen} />;
case "queued":
return (
<QueuedMessage
item={item.item}
sending={item.sending}
steerAll={steerAll}
onRecallQueued={onRecallQueued}
onRemoveQueued={onRemoveQueued}
onSetSteerAll={onSetSteerAll}
/>
);
}
},
[canOpen, openByName],
[canOpen, onRecallQueued, onRemoveQueued, onSetSteerAll, openByName, steerAll],
);
const itemClassName = useCallback(
(item: StreamItem) =>
cn(
"stream-item",
// A turn spans its user message + everything until the next user
// message: 28px before it, 18px inside it.
item.kind === "entry" && item.turnStart && "turn-start",
item.kind === "queued" && "user-start stream-item--queued",
item.kind === "entry" && item.entry.role === "user" && "user-start",
),
[],
);
const status = (
@@ -194,43 +263,54 @@ export function MessageStream({
</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)` }}
>
const body = items.length || queued.length ? (
<>
{items.length ? (
virtualize ? (
<div
className="stream-list stream-inner 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={itemClassName(item)}
style={{ transform: `translateY(${virtualItem.start}px)` }}
>
{renderItem(item)}
</div>
);
})}
</div>
) : (
<div className="stream-list stream-inner">
{items.map((item) => (
<div className={itemClassName(item)} key={item.key}>
{renderItem(item)}
</div>
))}
{queued.length ? null : <div className="stream-end" />}
</div>
)
) : null}
{queued.length ? (
<div className="stream-list stream-inner stream-list--queued" data-testid="stream-queued">
{queued.map((item) => (
<div className={itemClassName(item)} key={item.key}>
{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>
)
))}
<div className="stream-end" />
</div>
) : null}
</>
) : (
<Empty
className="stream-empty"
@@ -253,29 +333,20 @@ export function MessageStream({
{status}
{body}
</div>
{/* Exactly one floating button: back to latest. Top is End/Home. */}
<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")}
aria-label={t("chat.backToLatest")}
title={t("chat.backToLatest")}
onClick={() => {
setFollow(true);
scrollToBottom(true);
}}
>
{t("chat.latest")}
<Icon name="chevron-down" size={14} />
<span>{t("chat.latest")}</span>
</button>
</div>
</div>
+110
View File
@@ -0,0 +1,110 @@
import type { QueueItem } from "@protocol/types";
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
/**
* Pending ("queued") prompt entity.
*
* The message stream is the only place a pending prompt is rendered as text —
* the composer keeps a status line only (no body, no second delete entry). The
* daemon exposes the queue as `session.queue: QueueItem[]` (a `queue_update`
* projection), which is *not* part of `entries`: there is no `ts` and no
* "sending" state, so `sending` (the optimistic prompt pi2d tracks locally) is
* folded in here as one more queued variant instead of living in the composer.
*/
export interface QueuedMessageActions {
/** Recall to edit: drop the queue entry and refill the composer. */
onRecallQueued?: (id: string) => void;
onRemoveQueued?: (id: string) => void;
/**
* `queue.setSteer {mode}` is **session-wide**: the plugin flips every
* pending message at once. Never render this as a per-message toggle.
*/
onSetSteerAll?: (steer: boolean) => void;
}
export interface QueuedMessageProps extends QueuedMessageActions {
item: QueueItem;
/** Optimistic, locally tracked prompt that was already handed to the plugin. */
sending?: boolean;
/** Session-wide steer mode (`every queued item has steer`). */
steerAll?: boolean;
}
/** One `.msg--user.msg--queued` entity plus its `.msg__queue-foot` actions. */
export function QueuedMessage({
item,
sending = false,
steerAll = false,
onRecallQueued,
onRemoveQueued,
onSetSteerAll,
}: QueuedMessageProps) {
const { t } = useTranslation();
const inline = item.steer;
return (
<article className="msg msg--user msg--queued" data-queue-id={item.id} data-sending={sending ? "true" : undefined}>
<div className="msg__meta">
<span className="who who--user">{t("chat.you")}</span>
{sending ? <span className="muted msg__time">{t("chat.sending")}</span> : null}
</div>
<div className="msg__text">{item.text}</div>
<div className="msg__queue-foot">
<span className={cn("msg__queue-state", inline && "is-inline")}>
<Icon name={inline ? "zap" : "clock"} size={12} />
<span>{t("chat.queuePending")}</span>
<span className="tsep">·</span>
<span>{inline ? t("chat.queueInline") : t("chat.queueAfterTurn")}</span>
{steerAll && !sending ? (
<>
<span className="tsep">·</span>
<span className="msg__queue-scope">{t("chat.queueSteerScope")}</span>
</>
) : null}
</span>
<span className="spacer" />
{onRecallQueued && !sending ? (
<Button
size="sm"
variant="ghost"
className="msg__queue-btn"
data-queue-action="recall"
onClick={() => onRecallQueued(item.id)}
>
{t("chat.queueRecall")}
</Button>
) : null}
{onSetSteerAll && !sending ? (
<Button
size="sm"
variant="ghost"
className={cn("msg__queue-btn", steerAll && "is-active")}
aria-pressed={steerAll}
title={t("chat.queueSteerAll")}
data-queue-action="steer"
onClick={() => onSetSteerAll(!steerAll)}
>
{t("chat.queueInline")}
</Button>
) : null}
{onRemoveQueued && !sending ? (
<Button
size="sm"
variant="ghost"
className="msg__queue-btn is-danger"
aria-label={t("chat.removeQueued")}
title={t("chat.removeQueued")}
data-queue-action="remove"
onClick={() => onRemoveQueued(item.id)}
>
<Icon name="x" size={12} />
</Button>
) : null}
</div>
</article>
);
}
+215
View File
@@ -0,0 +1,215 @@
import type { SessionState } from "@protocol/types";
import { useCallback, useEffect, useLayoutEffect, useRef } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { Icon, type IconName } from "@/components/icons";
import { cn } from "@/lib/utils";
/**
* Session row actions popover (v0.1.1 Chat IA v3, CHG-2026-10-26-13 + -17).
*
* The popover is portalled to `document.body` and positioned `fixed`, so the
* session tree's scroll container (`.pane-scroll`, `overflow-y: auto`) can
* never clip it. It is right-aligned to the row's `…` trigger and flips above
* the row when there is not enough room below.
*
* Menu contents are exactly the prototype's five actions:
* `subagent filter` label + `活跃/全部` radios + `派发子代理` + `重命名` +
* `关闭进程` (danger). Destructive actions are *not* executed here: the parent
* routes them through its confirm dialog (second confirmation), matching
* `confirmDialog(..., { danger: true })` in the prototype.
*/
export interface SessionRowMenuProps {
session: SessionState;
/** The row's `…` button: the popover aligns to it and gets focus back on Esc. */
anchor: HTMLElement;
/** IA lens state, drives the `menuitemradio` checks. */
activeOnly: boolean;
/** `restoreFocus` is true only for Esc/Tab (focus returns to the `…` button). */
onClose: (restoreFocus: boolean) => void;
onToggleActiveOnly: () => void;
onDispatchSubagent: (sessionId: string) => void;
onRenameSession: (session: SessionState) => void;
/** The parent owns the danger confirmation for this one. */
onCloseSession: (session: SessionState) => void;
}
/** Fallback metrics before the popover has been painted (jsdom reports 0). */
const FALLBACK_WIDTH = 184;
const FALLBACK_HEIGHT = 120;
const GAP = 6;
const MARGIN = 8;
const ITEM = "[data-menu-item]";
interface MenuItemProps {
/** Stable hook for tests (`data-menu-action`), independent of the locale. */
action: string;
icon: IconName;
label: string;
onClick: () => void;
danger?: boolean;
/** `null` renders a plain `menuitem`; a boolean renders a `menuitemradio`. */
checked?: boolean | null;
}
function MenuItem({ action, icon, label, onClick, danger = false, checked = null }: MenuItemProps) {
const radio = checked !== null;
return (
<button
type="button"
className={cn("menu__item", danger && "is-danger", checked && "is-active")}
role={radio ? "menuitemradio" : "menuitem"}
aria-checked={radio ? checked : undefined}
data-menu-item=""
data-menu-action={action}
onClick={onClick}
>
<Icon name={icon} />
<span className="grow truncate">{label}</span>
{checked ? (
<span className="menu__check">
<Icon name="check" />
</span>
) : null}
</button>
);
}
export function SessionRowMenu({
session,
anchor,
activeOnly,
onClose,
onToggleActiveOnly,
onDispatchSubagent,
onRenameSession,
onCloseSession,
}: SessionRowMenuProps) {
const { t } = useTranslation();
const menuRef = useRef<HTMLDivElement | null>(null);
// Latest `onClose` for the document-level listeners (they subscribe once).
const closeRef = useRef(onClose);
useEffect(() => {
closeRef.current = onClose;
}, [onClose]);
/** Right-align to the trigger, flip up when the space below is short. */
useLayoutEffect(() => {
const menu = menuRef.current;
if (!menu) return;
const rect = anchor.getBoundingClientRect();
const width = menu.offsetWidth || FALLBACK_WIDTH;
const height = menu.offsetHeight || FALLBACK_HEIGHT;
const left = Math.max(MARGIN, Math.min(rect.right - width, window.innerWidth - width - MARGIN));
let top = rect.bottom + GAP;
if (top + height > window.innerHeight - MARGIN) top = Math.max(MARGIN, rect.top - height - GAP);
menu.style.left = `${Math.round(left)}px`;
menu.style.top = `${Math.round(top)}px`;
}, [anchor]);
// Opening moves focus to the first item.
useLayoutEffect(() => {
menuRef.current?.querySelector<HTMLElement>(ITEM)?.focus({ preventScroll: true });
}, []);
// Outside click, tree/window scroll and window resize all close it. Clicks are
// resolved with `composedPath()` because selecting an item re-renders the tree
// and can detach the node that was actually pressed.
useEffect(() => {
const close = (): void => closeRef.current(false);
const onPointerDown = (event: Event): void => {
const path = typeof event.composedPath === "function" ? event.composedPath() : [];
const menu = menuRef.current;
if (menu && path.includes(menu)) return;
// The trigger toggles the popover itself; let its onClick decide.
if (path.includes(anchor)) return;
close();
};
document.addEventListener("pointerdown", onPointerDown, true);
window.addEventListener("scroll", close, true);
window.addEventListener("resize", close);
return () => {
document.removeEventListener("pointerdown", onPointerDown, true);
window.removeEventListener("scroll", close, true);
window.removeEventListener("resize", close);
};
}, [anchor]);
const run = useCallback(
(action: () => void) => {
// Close first: the action may re-render or unmount the row.
closeRef.current(false);
action();
},
[],
);
const moveFocus = useCallback((key: string) => {
const items = Array.from(menuRef.current?.querySelectorAll<HTMLElement>(ITEM) ?? []);
if (!items.length) return;
const current = items.indexOf(document.activeElement as HTMLElement);
let next = current;
if (key === "ArrowDown") next = current < 0 ? 0 : (current + 1) % items.length;
else if (key === "ArrowUp") next = current < 0 ? items.length - 1 : (current - 1 + items.length) % items.length;
else if (key === "Home") next = 0;
else next = items.length - 1;
items[next]?.focus({ preventScroll: true });
}, []);
return createPortal(
<div
ref={menuRef}
className="menu tree-pop"
role="menu"
aria-label={t("common.manage")}
data-testid="session-row-menu"
data-menu-session={session.sessionId}
onKeyDown={(event) => {
if (event.key === "Escape" || event.key === "Tab") {
event.preventDefault();
event.stopPropagation();
onClose(true);
return;
}
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
event.preventDefault();
moveFocus(event.key);
}}
>
<div className="menu__label">{t("chat.subagentFilter")}</div>
<MenuItem
action="active-only"
icon="eye"
label={t("chat.showActiveOnly")}
checked={activeOnly}
onClick={() => run(() => (activeOnly ? undefined : onToggleActiveOnly()))}
/>
<MenuItem
action="show-all"
icon="todo"
label={t("chat.showAllSubs")}
checked={!activeOnly}
onClick={() => run(() => (activeOnly ? onToggleActiveOnly() : undefined))}
/>
<div className="menu__sep" />
<MenuItem
action="dispatch"
icon="branch"
label={t("chat.dispatchHere")}
onClick={() => run(() => onDispatchSubagent(session.sessionId))}
/>
<MenuItem action="rename" icon="edit" label={t("chat.rename")} onClick={() => run(() => onRenameSession(session))} />
<div className="menu__sep" />
<MenuItem
action="close"
icon="x"
label={t("chat.closeProcess")}
danger
onClick={() => run(() => onCloseSession(session))}
/>
</div>,
document.body,
);
}
+315
View File
@@ -0,0 +1,315 @@
import type { SessionState, Subagent, TaskItem } from "@protocol/types";
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { Badge } from "@/components/ui/badge";
import { Empty } from "@/components/ui/empty";
import { Progress } from "@/components/ui/progress";
import { StatusDot, type DotStatus } from "@/components/ui/status-dot";
import { cn } from "@/lib/utils";
import { TodoList } from "./blocks";
import { formatDuration } from "./format";
import type { TrayTab } from "./store";
import "@/styles/pages/chat-tray.css";
export interface SessionTrayProps {
open: boolean;
tab: TrayTab;
/** The session whose Todo/Tasks are shown (subagent rows share the session's data). */
session: SessionState | null;
/**
* Subagent currently opened in the child view — the tray keeps showing
* **session-scoped** Todo/Tasks (pi2d has no per-subagent buckets yet) and
* says so explicitly instead of silently pretending to be scoped.
*/
subagent: Subagent | null;
onTab: (tab: TrayTab) => void;
onClose: () => void;
onOpenTask: (task: TaskItem) => void;
onStopTask: (task: TaskItem) => void;
className?: string;
}
const TABS: TrayTab[] = ["todo", "tasks"];
function taskDot(status: TaskItem["status"]): DotStatus {
if (status === "running") return "busy";
if (status === "completed") return "ok";
if (status === "failed") return "err";
return "idle";
}
/**
* Session tray (v0.1.1 Chat IA v3) — the replacement for the old right panel.
*
* Anchored under the stream head (`top: 54px`), never a third column:
* `role="dialog" aria-modal="false"` because it is non-blocking and the stream
* stays interactive. Two tabs only (`todo` / `tasks`); subagents moved into the
* session tree and the child view. Todo is read-only, Tasks has a single write
* action (stop, confirmed by the page).
*
* Keyboard: `←/→` cycle the tablist (roving tabindex), `Esc` closes and the
* page restores focus to the chip that opened it. Below 600px the tray becomes
* a bottom sheet with a backdrop; ≥600px the backdrop is always hidden.
*/
export function SessionTray({
open,
tab,
session,
subagent,
onTab,
onClose,
onOpenTask,
onStopTask,
className,
}: SessionTrayProps) {
const { t } = useTranslation();
const rootRef = useRef<HTMLElement | null>(null);
const tabsRef = useRef<HTMLDivElement | null>(null);
const [entered, setEntered] = useState(false);
const title = subagent
? t("chat.subview.trayTitle", { name: subagent.name ?? subagent.id })
: t("chat.trayTitle");
// Enter animation: flip `is-open` on the frame after the node is painted.
useEffect(() => {
if (!open) {
setEntered(false);
return;
}
const frame = requestAnimationFrame(() => setEntered(true));
return () => cancelAnimationFrame(frame);
}, [open]);
// Opening moves focus onto the selected tab (the dialog's first stop).
useEffect(() => {
if (!open) return;
const frame = requestAnimationFrame(() => {
tabsRef.current?.querySelector<HTMLElement>('[aria-selected="true"]')?.focus({ preventScroll: true });
});
return () => cancelAnimationFrame(frame);
}, [open]);
// Esc closes the tray — unless a modal is on top, in which case it belongs
// to the modal (single-layer close chain).
useEffect(() => {
if (!open) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Escape" || event.defaultPrevented) return;
if (document.querySelector(".modal-backdrop")) return;
event.preventDefault();
onClose();
};
document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
}, [onClose, open]);
// Click outside closes. `composedPath()` (not `contains`) because selecting a
// tab re-renders and detaches the clicked node first; a chip click is *not*
// an outside click (it toggles and must keep its own state machine).
useEffect(() => {
if (!open) return;
const onPointerDown = (event: Event) => {
if (document.querySelector(".modal-backdrop")) return;
const path = typeof event.composedPath === "function" ? event.composedPath() : [];
if (rootRef.current && path.includes(rootRef.current)) return;
const fromChip = path.some(
(node) => node instanceof HTMLElement && node.classList.contains("head-chip"),
);
if (fromChip) return;
onClose();
};
document.addEventListener("pointerdown", onPointerDown, true);
return () => document.removeEventListener("pointerdown", onPointerDown, true);
}, [onClose, open]);
const moveTab = useCallback(
(delta: 1 | -1 | "home" | "end") => {
// Two tabs: ←/→ and Home/End both resolve to the other end.
const next: TrayTab =
delta === "home" ? "todo" : delta === "end" ? "tasks" : tab === "todo" ? "tasks" : "todo";
onTab(next);
requestAnimationFrame(() => {
tabsRef.current?.querySelector<HTMLElement>(`[data-tray-tab="${next}"]`)?.focus({
preventScroll: true,
});
});
},
[onTab, tab],
);
const todos = session?.todos ?? [];
const tasks = session?.tasks ?? [];
const done = todos.filter((item) => item.status === "completed").length;
const counts: Record<TrayTab, number> = { todo: todos.length, tasks: tasks.length };
return (
<>
<div
className={cn("tray-backdrop", open && "is-open")}
data-testid="tray-backdrop"
aria-hidden="true"
onClick={onClose}
/>
<aside
ref={rootRef}
id="chat-tray"
className={cn("session-tray", open && entered && "is-open", className)}
role="dialog"
aria-modal="false"
aria-labelledby="chat-tray-title"
data-testid="session-tray"
data-tab={tab}
hidden={!open}
>
<div className="tray-head">
<h3 id="chat-tray-title" className="tray-head__title">
<Icon name="todo" />
<span className="truncate">{title}</span>
</h3>
<button
type="button"
className="icon-btn tray-close"
aria-label={t("chat.closeTray")}
title={t("chat.closeTray")}
onClick={onClose}
>
<Icon name="x" />
</button>
</div>
<p className="tray-scope" data-testid="tray-scope">
<span className="tray-scope__label">
{subagent
? t("chat.trayScopeSubagent", { name: subagent.name ?? subagent.id })
: t("chat.trayScopeSession")}
</span>
{subagent ? <span className="tray-scope__note">{t("chat.trayScopeNote")}</span> : null}
</p>
<div
ref={tabsRef}
className="seg seg--quiet tray-tabs"
role="tablist"
aria-label={t("chat.trayTitle")}
>
{TABS.map((item) => {
const selected = tab === item;
return (
<button
key={item}
type="button"
role="tab"
id={`chat-tray-tab-${item}`}
data-tray-tab={item}
data-testid={`tray-tab-${item}`}
className={cn("tray-tab", selected && "active")}
aria-selected={selected}
aria-controls="chat-tray-body"
tabIndex={selected ? 0 : -1}
onClick={() => onTab(item)}
onKeyDown={(event) => {
if (event.key === "ArrowRight") {
event.preventDefault();
moveTab(1);
} else if (event.key === "ArrowLeft") {
event.preventDefault();
moveTab(-1);
} else if (event.key === "Home") {
event.preventDefault();
moveTab("home");
} else if (event.key === "End") {
event.preventDefault();
moveTab("end");
}
}}
>
<span>{t(item === "todo" ? "chat.tabTodo" : "chat.tabTasks")}</span>
{counts[item] ? <span className="badge badge--sm">{counts[item]}</span> : null}
</button>
);
})}
</div>
<div
className="tray-body"
id="chat-tray-body"
role="tabpanel"
aria-labelledby={`chat-tray-tab-${tab}`}
>
{tab === "todo" ? (
todos.length ? (
<>
<div className="tray-row">
<span className="muted grow">
{t("chat.progress", { done, total: todos.length })}
</span>
<Badge>{t("common.readonly")}</Badge>
</div>
<Progress value={done} max={todos.length || 1} label={t("chat.tabTodo")} />
<TodoList items={todos} idPrefix="tray-todo" />
<div className="tray__note muted">{t("chat.todoNote")}</div>
</>
) : (
<Empty
icon={<Icon name="todo" />}
title={t("chat.noTodo")}
description={t("chat.noTodoText")}
/>
)
) : tasks.length ? (
<div className="tray-list">
{tasks.map((task) => {
const running = task.status === "running";
const duration = running ? Date.now() - task.startTime : task.durationMs;
return (
<div key={task.id} className="task-row" data-task-id={task.id}>
<StatusDot status={taskDot(task.status)} />
<button
type="button"
className="task-row__main"
title={t("chat.taskOutput", { id: task.id })}
aria-label={t("chat.taskOutput", { id: task.id })}
onClick={() => onOpenTask(task)}
>
<span className="task-row__cmd mono truncate">{task.command}</span>
<span className="task-row__meta">
<span className="tabular">{formatDuration(duration)}</span>
{task.exitCode != null ? (
<Badge tone={task.exitCode === 0 ? "ok" : "err"}>
{`exit ${task.exitCode}`}
</Badge>
) : (
<span className="faint">{t(`state.${task.status}`)}</span>
)}
</span>
</button>
{running ? (
<button
type="button"
className="btn btn--sm btn--danger task-row__stop"
onClick={() => onStopTask(task)}
>
{t("common.stop")}
</button>
) : null}
</div>
);
})}
</div>
) : (
<Empty
icon={<Icon name="terminal" />}
title={t("chat.noTasks")}
description={t("chat.noTasksText")}
/>
)}
</div>
</aside>
</>
);
}
+155 -27
View File
@@ -7,6 +7,14 @@ import type { SessionState, Subagent } from "@protocol/types";
* own (the child session row always wins).
*
* Pure and React-free, so the shape is unit-testable without a DOM.
*
* Two independent filters feed the tree (v0.1.1 Chat IA v3):
*
* - `activeOnly` — the IA lens ("only live rows", persisted as `pi2-active-only`).
* - `showHidden` — the plugin's `:PiSessions` visibility policy (`visible:false`).
*
* They are NOT the same boolean: one is a user preference, the other is data the
* daemon already filtered for us.
*/
export interface SessionTreeNode {
@@ -14,12 +22,14 @@ export interface SessionTreeNode {
session: SessionState;
depth: number;
children: TreeNode[];
/** Number of children actually rendered, so a `(N)` badge matches the UI. */
/** Number of children actually rendered. */
childCount: number;
/** True when the row is hidden by the plugin's visibility policy. */
hidden: boolean;
/** Keep this row open even when the user folded it (selected/filtered descendant). */
forcedOpen: boolean;
/** Direct children dropped by `activeOnly` (rendered as `+N`). */
hiddenCount: number;
}
export interface SubagentTreeNode {
@@ -29,23 +39,43 @@ export interface SubagentTreeNode {
subagent: Subagent;
depth: number;
children: TreeNode[];
/** Number of children actually rendered, so a `(N)` badge matches the UI. */
/** Number of children actually rendered. */
childCount: number;
/** True when the row is hidden by the plugin's visibility policy. */
hidden: boolean;
/** Keep this row open even when the user folded it (search match below). */
forcedOpen: boolean;
/** Direct children dropped by `activeOnly` (rendered as `+N`). */
hiddenCount: number;
}
export type TreeNode = SessionTreeNode | SubagentTreeNode;
export interface SessionTreeOptions {
/** Case-insensitive name needle; empty (or absent) means "no filter". */
/** Case-insensitive needle over session name / model id; empty means "no filter". */
filter?: string;
/** Render rows the plugin marked `visible: false`. */
showHidden?: boolean;
/** The routed session; always rendered, even when it is hidden/filtered out. */
selectedId?: string | null;
/**
* IA lens: drop rows whose process is gone (see `isSessionActive` /
* `isSubagentActive`). Defaults to `false` so the model stays usable for
* callers that do their own filtering.
*/
activeOnly?: boolean;
/** Subagent shown in the child view: it and its ancestors stay visible. */
viewingSubagentId?: string | null;
}
export interface SessionTreeView {
roots: TreeNode[];
/** Root sessions dropped by `activeOnly` — the `.tree-hidden` "N hidden" count. */
hiddenSessions: number;
/** Rows (any depth) dropped by the plugin's `visible:false` policy. */
hiddenByPolicy: number;
/** Manifest path (root → viewing subagent) of the child view, empty when none. */
viewingPath: string[];
}
/** Stable key for a node (manifest ids are not unique across sessions). */
@@ -58,6 +88,57 @@ export function treeNodeId(node: TreeNode): string {
return node.kind === "session" ? node.session.sessionId : node.subagent.id;
}
/* ------------------------------------------------------------------ */
/* Active-row predicates (pure, unit-tested) */
/* ------------------------------------------------------------------ */
/**
* A session is "active" while its process is alive. The design excludes the
* three terminal states; `done`/`exited`/`dormant` rows only reappear through
* "show all sessions".
*/
export function isSessionActive(session: Pick<SessionState, "status">): boolean {
return !["done", "exited", "dormant"].includes(session.status);
}
/**
* A subagent is "active" when the user may still act on it — a failed or
* interrupted subagent stays reachable, a completed/dormant one does not.
*/
export function isSubagentActive(subagent: Pick<Subagent, "status">): boolean {
return ["active", "interrupted", "failed"].includes(subagent.status);
}
/**
* Is `id` on the path to the subagent being viewed (itself or an ancestor)?
*
* The child view must keep its own row reachable no matter how aggressive the
* `activeOnly` lens is — a completed subagent you are reading stays in the tree.
*/
export function isOnCurrentSubPath(id: string, path: readonly string[]): boolean {
return path.includes(id);
}
/** Manifest path (root → `id`) to a nested subagent; `[]` when it is not there. */
export function subagentPath(list: Subagent[] | undefined, id: string | null): Subagent[] {
if (!id) return [];
for (const subagent of list ?? []) {
if (subagent.id === id) return [subagent];
const nested = subagentPath(subagent.children, id);
if (nested.length) return [subagent, ...nested];
}
return [];
}
/** Ids of the viewing subagent and its ancestors, for `isOnCurrentSubPath`. */
export function subagentPathIds(list: Subagent[] | undefined, id: string | null): string[] {
return subagentPath(list, id).map((subagent) => subagent.id);
}
/* ------------------------------------------------------------------ */
/* Tree building */
/* ------------------------------------------------------------------ */
/** Does this subtree contain `id` (used to expand the path to the routed row)? */
function containsNode(node: TreeNode, id: string): boolean {
if (treeNodeId(node) === id) return true;
@@ -72,6 +153,12 @@ function subagentLabel(subagent: Subagent): string {
return subagent.name?.trim() || subagent.id;
}
/** Search matches the session/subagent name or its model id (prototype behaviour). */
function matches(label: string, model: string | undefined, needle: string): boolean {
if (needle === "") return true;
return label.toLowerCase().includes(needle) || (model ?? "").toLowerCase().includes(needle);
}
/**
* The parent a row is grouped under, or `null` when it is a root.
*
@@ -101,8 +188,12 @@ function effectiveParent(session: SessionState, index: Map<string, SessionState>
* order the list delivered; a session's synthetic subagent rows follow its real
* child sessions, in manifest order.
*/
export function buildSessionTree(sessions: SessionState[], options: SessionTreeOptions = {}): TreeNode[] {
export function buildSessionTreeView(
sessions: SessionState[],
options: SessionTreeOptions = {},
): SessionTreeView {
const showHidden = options.showHidden === true;
const activeOnly = options.activeOnly === true;
const selectedId = options.selectedId ?? null;
const needle = (options.filter ?? "").trim().toLowerCase();
@@ -112,6 +203,8 @@ export function buildSessionTree(sessions: SessionState[], options: SessionTreeO
if (!index.has(session.sessionId)) index.set(session.sessionId, session);
}
let hiddenByPolicy = 0;
// Children grouped by their effective parent, in list order.
const childSessions = new Map<string | null, SessionState[]>();
for (const session of sessions) {
@@ -122,51 +215,59 @@ export function buildSessionTree(sessions: SessionState[], options: SessionTreeO
else childSessions.set(parentId, [session]);
}
/** Viewing subagent + ancestors: always kept when `activeOnly` hides them. */
const viewingPath = activeOnly
? subagentPathIds(selectedId ? index.get(selectedId)?.subagents : undefined, options.viewingSubagentId ?? null)
: [];
/**
* Selection, search and ancestry; visibility is only one of the inputs.
*
* Selection overrides the visibility policy (a deep-linked hidden row always
* renders) but NOT an explicit search: the filter is the user's intent and a
* non-matching row stays out.
* Session keep decision. Precedence: search (explicit intent) > routed row >
* active lens > plugin policy > "an kept descendant needs the ancestor".
*/
function keepRow(id: string, label: string, selfVisible: boolean, children: TreeNode[]): boolean {
if (needle !== "") {
// Search is an explicit intent: a matching hidden row IS shown.
if (label.toLowerCase().includes(needle)) return true;
return children.length > 0;
}
if (selectedId !== null && id === selectedId) return true;
if (showHidden || selfVisible) return true;
// Hidden, but kept because a rendered descendant needs its ancestor.
return children.length > 0;
function keepSession(session: SessionState, childCount: number): boolean {
if (needle !== "") return matches(sessionLabel(session), session.model?.id, needle) || childCount > 0;
if (selectedId !== null && session.sessionId === selectedId) return true;
if (activeOnly && !isSessionActive(session)) return childCount > 0;
if (session.visible === false) return showHidden || childCount > 0;
return true;
}
function buildSessionNode(session: SessionState, depth: number, path: Set<string>): SessionTreeNode | null {
if (path.has(session.sessionId)) return null;
const nextPath = new Set(path).add(session.sessionId);
const children: TreeNode[] = [];
let hiddenCount = 0;
for (const child of childSessions.get(session.sessionId) ?? []) {
const node = buildSessionNode(child, depth + 1, nextPath);
if (node) children.push(node);
else if (activeOnly && needle === "" && child.visible !== false) hiddenCount += 1;
}
for (const subagent of session.subagents ?? []) {
const node = buildSubagentNode(session, subagent, depth + 1, nextPath);
if (node) children.push(node);
else if (activeOnly && needle === "" && !isSubagentActive(subagent) && subagent.visible !== false) {
hiddenCount += 1;
}
}
if (!keepSession(session, children.length)) {
if (needle === "" && session.visible === false) hiddenByPolicy += 1;
return null;
}
const selfVisible = session.visible !== false;
if (!keepRow(session.sessionId, sessionLabel(session), selfVisible, children)) return null;
return {
kind: "session",
session,
depth,
children,
childCount: children.length,
hidden: !selfVisible,
hidden: session.visible === false,
// A folded parent must still reveal the routed row or a search hit
// inside it; otherwise the selection would silently disappear.
forcedOpen:
children.length > 0 &&
(needle !== "" || (selectedId !== null && children.some((child) => containsNode(child, selectedId)))),
(needle !== "" ||
(selectedId !== null && children.some((child) => containsNode(child, selectedId))) ||
children.some((child) => viewingPath.includes(treeNodeId(child)))),
hiddenCount,
};
}
@@ -178,14 +279,33 @@ export function buildSessionTree(sessions: SessionState[], options: SessionTreeO
): SubagentTreeNode | null {
// Dedupe: a manifest entry with a session row of its own is that row.
if (index.has(subagent.id) || path.has(subagent.id)) return null;
// The active lens never hides a row on the path to the child view.
if (activeOnly && !isSubagentActive(subagent) && !isOnCurrentSubPath(subagent.id, viewingPath)) return null;
const nextPath = new Set(path).add(subagent.id);
const children: TreeNode[] = [];
let hiddenCount = 0;
for (const child of subagent.children ?? []) {
const node = buildSubagentNode(session, child, depth + 1, nextPath);
if (node) children.push(node);
else if (activeOnly && needle === "" && !isSubagentActive(child) && child.visible !== false) {
hiddenCount += 1;
}
}
const selfVisible = subagent.visible !== false;
if (!keepRow(subagent.id, subagentLabel(subagent), selfVisible, children)) return null;
if (subagent.visible === false) {
// Policy-hidden row: kept by the show-hidden toggle, a search hit, the
// routed row or a rendered descendant — never silently by default.
const keep =
showHidden ||
selectedId === subagent.id ||
children.length > 0 ||
(needle !== "" && matches(subagentLabel(subagent), subagent.model, needle));
if (!keep) {
if (needle === "") hiddenByPolicy += 1;
return null;
}
}
// Search keeps only matching sessions; inside a kept session the
// manifest rows are not filtered by the needle (prototype behaviour).
return {
kind: "subagent",
session,
@@ -193,16 +313,24 @@ export function buildSessionTree(sessions: SessionState[], options: SessionTreeO
depth,
children,
childCount: children.length,
hidden: !selfVisible,
hidden: subagent.visible === false,
forcedOpen: children.length > 0 && needle !== "",
hiddenCount,
};
}
const roots: TreeNode[] = [];
let hiddenSessions = 0;
const emptyPath = new Set<string>();
for (const session of childSessions.get(null) ?? []) {
const node = buildSessionNode(session, 0, emptyPath);
if (node) roots.push(node);
else if (activeOnly && needle === "" && session.visible !== false) hiddenSessions += 1;
}
return roots;
return { roots, hiddenSessions, hiddenByPolicy, viewingPath };
}
/** Convenience wrapper for callers that only need the rows. */
export function buildSessionTree(sessions: SessionState[], options: SessionTreeOptions = {}): TreeNode[] {
return buildSessionTreeView(sessions, options).roots;
}
+330 -380
View File
@@ -1,382 +1,306 @@
import type { SessionState, Subagent, WorkspaceInfo } from "@protocol/types";
import { useMemo } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
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";
import { SessionRowMenu } from "./session-row-menu";
import { flattenSubagents, sessionDot } from "./session-state";
import {
buildSessionTree,
buildSessionTreeView,
treeNodeId,
treeNodeKey,
type SessionTreeNode,
type SubagentTreeNode,
type TreeNode,
} from "./session-tree-model";
import { WorkspaceSwitch } from "./workspace-switch";
/**
* Left rail of the chat page (v0.1.1 Chat IA v3, CHG-2026-10-26-10/11/12/13/17).
*
* One workspace, one flat-indent tree: every row is a *single* line
* (`.tree-row__main` = status dot + name + `!N` attention), hierarchy is
* expressed by indentation only, and the per-row `…` button opens a body-level
* anchored popover (`SessionRowMenu`). Sessions and sub-sessions/subagents are
* selectable; the child view lives in the stream pane, not in a modal.
*
* The two filters are independent and deliberately so:
* - `activeOnly` — the user's IA lens ("only live rows", persisted).
* - `showHidden` — the plugin's `:PiSessions` visibility policy.
*/
export interface SessionTreeProps {
/** Sessions of the active workspace only. */
sessions: SessionState[];
workspaces?: WorkspaceInfo[];
activeWorkspaceId?: string | null;
selectedId?: string | null;
workspaces: WorkspaceInfo[];
activeWorkspaceId: string | null;
selectedId: string | null;
/** Subagent shown in the in-place child view (`?sub=`); its row stays reachable. */
activeSubagentId: string | null;
filter: string;
collapsed: Record<string, boolean>;
/** Render sub-sessions the plugin marked `visible: false`. */
/** IA lens: hide rows whose process is gone. */
activeOnly: boolean;
/** Render rows the plugin marked `visible: false`. */
showHidden: boolean;
connected?: boolean;
creating?: boolean;
onFilter: (value: string) => void;
onToggleCollapse: (id: string) => void;
onToggleAll: () => void;
onToggleShowHidden: () => 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;
/** Accepted for the page contract; the v0.1.1 tree shows no connection dot. */
connected: boolean;
creating: boolean;
onFilter(value: string): void;
onToggleCollapse(id: string): void;
onToggleAll(): void;
onToggleActiveOnly(): void;
onToggleShowHidden(): void;
onSelectSession(id: string): void;
onSelectWorkspace(id: string): void;
onSelectSubagent(sessionId: string, subagentId: string): void;
onNewSession(): void;
onRenameSession(session: SessionState): void;
onCloseSession(session: SessionState): void;
onDispatchSubagent(sessionId: string): void;
/**
* Reserved for the subagent child-view `⋯` menu (stream workstream): the
* tree rows themselves open no subagent menu in v0.1.1.
*/
onRenameSubagent(subagent: Subagent): void;
onCloseDrawer?(): void;
className?: string;
}
function sessionName(session: SessionState, fallback: string): string {
return session.name?.trim() || fallback;
/** `name · model · thinking [· status]` — the row shows the name, the title the rest. */
function rowTitle(parts: (string | null | undefined)[]): string {
return parts.filter((part): part is string => Boolean(part && part.trim())).join(" · ");
}
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>
);
}
interface TreeHandlers {
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;
}
/**
* One row of the session tree plus its children.
*
* A real child session renders as a `tree-row--sub` (indent only, no vertical
* guides) and navigates to its own transcript; a manifest subagent keeps the
* eye/rename affordances of the subagent preview.
*/
function TreeRow({
node,
selectedId,
collapsed,
...handlers
}: TreeHandlers & { node: TreeNode; selectedId?: string | null; collapsed: Record<string, boolean> }) {
const isCollapsed = collapsed[treeNodeId(node)] === true && !node.forcedOpen;
return (
<li>
{node.kind === "session" ? (
<SessionNodeRow
node={node}
collapsed={isCollapsed}
selected={node.session.sessionId === selectedId}
{...handlers}
/>
) : (
<SubagentNodeRow node={node} collapsed={isCollapsed} {...handlers} />
)}
{node.children.length && !isCollapsed ? (
<ul>
{node.children.map((child) => (
<TreeRow
key={treeNodeKey(child)}
node={child}
collapsed={collapsed}
selectedId={selectedId}
{...handlers}
/>
))}
</ul>
) : null}
</li>
);
}
function SessionNodeRow({
node,
collapsed,
selected,
onToggleCollapse,
onSelectSession,
onRenameSession,
onCloseSession,
}: {
node: SessionTreeNode;
collapsed: boolean;
selected: boolean;
} & Pick<TreeHandlers, "onToggleCollapse" | "onSelectSession" | "onRenameSession" | "onCloseSession">) {
const { t } = useTranslation();
const session = node.session;
const status = t(`state.${sessionStatusKey(session)}`);
const name = sessionName(session, session.sessionId);
return (
<div
className={cn("tree-row", node.depth > 0 && "tree-row--sub", selected && "selected")}
role="button"
tabIndex={0}
aria-label={name}
aria-current={selected ? "true" : undefined}
data-session-id={session.sessionId}
data-hidden={node.hidden ? "true" : undefined}
onClick={() => onSelectSession(session.sessionId)}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
onSelectSession(session.sessionId);
}
}}
>
<ChevronToggle
hasChildren={node.children.length > 0}
collapsed={collapsed}
onClick={() => onToggleCollapse(session.sessionId)}
/>
<StatusDot status={sessionDot(session)} 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>
{node.childCount ? (
<span className="t-meta" title={t("chat.childCount", { n: node.childCount })}>
{`(${node.childCount})`}
</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>
);
}
function SubagentNodeRow({
node,
collapsed,
onToggleCollapse,
onOpenSubagent,
onRenameSubagent,
}: {
node: SubagentTreeNode;
collapsed: boolean;
} & Pick<TreeHandlers, "onToggleCollapse" | "onOpenSubagent" | "onRenameSubagent">) {
const { t } = useTranslation();
const { session, subagent } = node;
const status = t(`state.${subagent.status}`);
const name = subagent.name ?? subagent.id;
return (
<div
className="tree-row tree-row--sub"
role="button"
tabIndex={0}
aria-label={name}
data-subagent-id={subagent.id}
data-hidden={node.hidden ? "true" : undefined}
onClick={() => onOpenSubagent?.(session, subagent)}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
onOpenSubagent?.(session, subagent);
}
}}
>
<ChevronToggle
hasChildren={node.children.length > 0}
collapsed={collapsed}
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>
{node.childCount ? (
<span className="t-meta" title={t("chat.childCount", { n: node.childCount })}>
{`(${node.childCount})`}
</span>
) : null}
<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>
);
}
/** Left sidebar: workspace picker + indent-only session/subagent tree. */
export function SessionTree({
sessions,
workspaces = [],
workspaces,
activeWorkspaceId,
selectedId,
activeSubagentId,
filter,
collapsed,
activeOnly,
showHidden,
connected = false,
creating = false,
creating,
onFilter,
onToggleCollapse,
onToggleAll,
onToggleActiveOnly,
onToggleShowHidden,
onSelectSession,
onSelectWorkspace,
onSelectSubagent,
onNewSession,
onRenameSession,
onCloseSession,
onOpenSubagent,
onRenameSubagent,
onDispatchSubagent,
onCloseDrawer,
className,
}: SessionTreeProps) {
const { t } = useTranslation();
const nodes = useMemo(
() => buildSessionTree(sessions, { filter, showHidden, selectedId }),
[sessions, filter, showHidden, selectedId],
const [wsMenuOpen, setWsMenuOpen] = useState(false);
const [rowMenu, setRowMenu] = useState<{ session: SessionState; anchor: HTMLElement } | null>(null);
const anchorRef = useRef<HTMLElement | null>(null);
const view = useMemo(
() =>
buildSessionTreeView(sessions, {
filter,
showHidden,
selectedId,
activeOnly,
viewingSubagentId: activeSubagentId,
}),
[sessions, filter, showHidden, selectedId, activeOnly, activeSubagentId],
);
// Every id — including rows the visibility policy or the filter dropped — so
// "collapse all" also folds folded-away parents.
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");
// "Collapse all" is a toggle: fold everything while any row is open.
const anyOpen = useMemo(() => {
const ids = sessions.flatMap((session) => [
session.sessionId,
...flattenSubagents(session.subagents).map(({ subagent }) => subagent.id),
]);
return ids.some((id) => collapsed[id] !== true);
}, [sessions, collapsed]);
useEffect(() => {
anchorRef.current = rowMenu?.anchor ?? null;
}, [rowMenu]);
const closeRowMenu = useCallback((restoreFocus: boolean) => {
const anchor = anchorRef.current;
anchorRef.current = null;
setRowMenu(null);
// Esc/Tab hand focus back to the `…` button (the row never unmounts).
if (restoreFocus) anchor?.focus({ preventScroll: true });
}, []);
function toggleRowMenu(session: SessionState, anchor: HTMLElement): void {
if (rowMenu?.session.sessionId === session.sessionId) {
closeRowMenu(true);
return;
}
anchorRef.current = anchor;
setRowMenu({ session, anchor });
}
const isOpen = (node: TreeNode): boolean =>
node.children.length > 0 && (collapsed[treeNodeId(node)] !== true || node.forcedOpen);
function foldButton(node: TreeNode, label: string) {
const open = isOpen(node);
return (
<button
type="button"
className={cn("tree-toggle", open && "open")}
aria-expanded={open}
aria-label={label}
onClick={(event) => {
event.stopPropagation();
onToggleCollapse(treeNodeId(node));
}}
>
<Icon name="chevron-right" />
</button>
);
}
function renderSessionRow(node: SessionTreeNode) {
const session = node.session;
const selected = session.sessionId === selectedId;
const menuOpen = rowMenu?.session.sessionId === session.sessionId;
const name = session.name?.trim() || session.sessionId;
const attention = session.attention.length;
return (
<div
className={cn(
"tree-row",
// A child session is a sub row: same single line, indent-only.
node.depth > 0 && "tree-row--sub",
node.depth > 0 && `sub-d${Math.min(node.depth, 3)}`,
selected && "selected",
menuOpen && "is-menu",
)}
data-session-id={session.sessionId}
data-hidden={node.hidden ? "true" : undefined}
>
{node.children.length ? (
foldButton(node, t(isOpen(node) ? "chat.fold" : "chat.unfold"))
) : (
<span className="tree-toggle leaf" aria-hidden="true">
<Icon name="chevron-right" />
</span>
)}
<button
type="button"
className="tree-row__main"
title={rowTitle([name, session.model?.id, session.thinking])}
aria-current={selected ? "true" : undefined}
onClick={() => onSelectSession(session.sessionId)}
>
<StatusDot status={sessionDot(session)} />
<span className="t-name truncate">{name}</span>
{attention > 0 ? <span className="t-attn">{`!${attention}`}</span> : null}
</button>
<button
type="button"
className="icon-btn t-more"
aria-haspopup="menu"
aria-expanded={menuOpen}
aria-label={t("common.manage")}
title={t("common.manage")}
data-menu-id={session.sessionId}
onClick={(event) => {
event.stopPropagation();
toggleRowMenu(session, event.currentTarget);
}}
>
<Icon name="more" />
</button>
</div>
);
}
function renderSubagentRow(node: SubagentTreeNode) {
const { session, subagent } = node;
const viewing = subagent.id === activeSubagentId;
const name = subagent.name?.trim() || subagent.id;
// Status is carried by the dot only; text goes to title/aria-label.
const label = rowTitle([name, subagent.model, subagent.thinking, t(`state.${subagent.status}`)]);
return (
<div
className={cn(
"tree-row tree-row--sub",
`sub-d${Math.min(node.depth, 3)}`,
viewing && "is-viewing",
)}
data-subagent-id={subagent.id}
data-hidden={node.hidden ? "true" : undefined}
>
{node.children.length ? (
foldButton(node, t(isOpen(node) ? "chat.fold" : "chat.unfold"))
) : (
<span className="tree-toggle leaf" aria-hidden="true">
<Icon name="chevron-right" />
</span>
)}
<button
type="button"
className={cn("tree-row__main", viewing && "is-viewing")}
title={label}
aria-label={label}
aria-current={viewing ? "true" : undefined}
data-sub-id={subagent.id}
onClick={() => onSelectSubagent(session.sessionId, subagent.id)}
>
<span className={cn("dot", subagentDotClass(subagent.status))} aria-hidden="true" />
<span className="t-name truncate">{name}</span>
{node.hiddenCount > 0 ? (
<span className="t-hidden tabular" title={t("chat.hiddenSubs", { n: node.hiddenCount })}>
{`+${node.hiddenCount}`}
</span>
) : null}
</button>
</div>
);
}
function renderRows(nodes: TreeNode[], level: number) {
return (
<ul className={level === 0 ? "tree tree--sessions" : "tree"}>
{nodes.map((node) => (
<li key={treeNodeKey(node)}>
{node.kind === "session" ? renderSessionRow(node) : renderSubagentRow(node)}
{isOpen(node) ? renderRows(node.children, level + 1) : null}
</li>
))}
</ul>
);
}
const hiddenByPolicy = showHidden ? 0 : view.hiddenByPolicy;
return (
<div className={cn("tree-pane__inner", className)} aria-label={t("chat.treeAria")}>
<div className={cn("tree-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)}
<div className="tree-head-row">
<WorkspaceSwitch
className="tree-head__switch"
workspaces={workspaces}
activeWorkspaceId={activeWorkspaceId}
sessionCount={sessions.length}
open={wsMenuOpen}
onOpenChange={setWsMenuOpen}
onSelect={onSelectWorkspace}
/>
{onCloseDrawer && !workspaces.length ? (
{onCloseDrawer ? (
<button
type="button"
className="icon-btn tree-close"
title={t("common.close")}
title={t("chat.closeTree")}
aria-label={t("chat.closeTree")}
onClick={onCloseDrawer}
>
@@ -384,30 +308,30 @@ export function SessionTree({
</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>
<div className="tree-toolbar">
<input
type="search"
className="tree-search"
value={filter}
placeholder={t("chat.searchPlaceholder")}
aria-label={t("chat.searchAria")}
onChange={(event) => onFilter(event.target.value)}
/>
<button
type="button"
className={cn("icon-btn", showHidden && "is-on")}
title={t("chat.showHidden")}
aria-label={t("chat.showHiddenAria")}
aria-pressed={showHidden}
onClick={onToggleShowHidden}
className="icon-btn"
title={t("chat.newSessionShort")}
aria-label={t("chat.newSessionShort")}
data-testid="tree-new-session"
disabled={creating}
onClick={onNewSession}
>
<Icon name="eye" />
<Icon name="plus" />
</button>
<button
type="button"
className="icon-btn"
title={t("chat.toggleAll")}
title={t("chat.toggleAllAria")}
aria-label={t("chat.toggleAllAria")}
onClick={onToggleAll}
>
@@ -416,55 +340,81 @@ export function SessionTree({
</div>
</div>
<div className="pane-scroll">
{nodes.length ? (
<ul className="tree">
{nodes.map((node) => (
<TreeRow
key={treeNodeKey(node)}
node={node}
selectedId={selectedId}
collapsed={collapsed}
onToggleCollapse={onToggleCollapse}
onSelectSession={onSelectSession}
onRenameSession={onRenameSession}
onCloseSession={onCloseSession}
onOpenSubagent={onOpenSubagent}
onRenameSubagent={onRenameSubagent}
/>
))}
</ul>
) : filter.trim() ? (
<Empty
icon={<Icon name="search" />}
title={t("chat.noMatch")}
description={t("chat.tryOther")}
/>
) : sessions.length ? (
<Empty
icon={<Icon name="eye" />}
title={t("chat.allHidden")}
description={t("chat.allHiddenText")}
action={
<button type="button" className="btn btn--sm" onClick={onToggleShowHidden}>
{view.roots.length ? (
<>
{renderRows(view.roots, 0)}
{view.hiddenSessions > 0 ? (
<button
type="button"
className="tree-hidden"
title={t("chat.showAllSessions")}
data-testid="tree-hidden-sessions"
onClick={onToggleActiveOnly}
>
<Icon name="eye" />
{t("chat.showHidden")}
<span className="truncate">{t("chat.hiddenSubs", { n: view.hiddenSessions })}</span>
</button>
}
/>
) : (
) : null}
{hiddenByPolicy > 0 ? (
<button
type="button"
className="tree-hidden"
title={t("chat.showHidden")}
data-testid="tree-hidden-policy"
onClick={onToggleShowHidden}
>
<Icon name="eye" />
<span className="truncate">{t("chat.hiddenSubs", { n: hiddenByPolicy })}</span>
</button>
) : null}
</>
) : sessions.length === 0 ? (
<Empty
icon={<Icon name="chat" />}
title={t("chat.noSessions")}
description={t("chat.noSessionsText")}
title={t("chat.noSessionInWorkspace")}
description={t("chat.noSessionInWorkspaceText")}
action={
<button type="button" className="btn btn--sm" onClick={onNewSession} disabled={creating}>
<Icon name="plus" />
{t("chat.newSession")}
{t("chat.newSessionShort")}
</button>
}
/>
) : filter.trim() ? (
<Empty icon={<Icon name="search" />} title={t("chat.noMatch")} description={t("chat.tryOther")} />
) : (
<Empty
icon={<Icon name="check" />}
title={t("chat.noActiveTitle")}
description={t("chat.noActiveText")}
action={
view.hiddenByPolicy > 0 && !showHidden ? (
<button type="button" className="btn btn--sm" onClick={onToggleShowHidden}>
<Icon name="eye" />
{t("chat.showHidden")}
</button>
) : (
<button type="button" className="btn btn--sm" onClick={onToggleActiveOnly}>
<Icon name="eye" />
{t("chat.showAllSessions")}
</button>
)
}
/>
)}
</div>
{rowMenu ? (
<SessionRowMenu
session={rowMenu.session}
anchor={rowMenu.anchor}
activeOnly={activeOnly}
onClose={closeRowMenu}
onToggleActiveOnly={onToggleActiveOnly}
onDispatchSubagent={onDispatchSubagent}
onRenameSession={onRenameSession}
onCloseSession={onCloseSession}
/>
) : null}
</div>
);
}
+12 -3
View File
@@ -1,3 +1,11 @@
/**
* @deprecated v0.1.1 Chat IA v3 — the right panel is gone. Subagents live in the
* session tree / child view, and Todo + Tasks moved to the anchored session tray
* (`./session-tray.tsx`, triggered by the stream-head chips). This file is kept
* only because it still typechecks against the store and other pages may import
* it; nothing in the Chat page renders it any more. Delete once no importer
* remains.
*/
import type { SessionState, Subagent, TaskItem } from "@protocol/types";
import { useTranslation } from "react-i18next";
@@ -34,8 +42,9 @@ function taskDot(status: TaskItem["status"]): "busy" | "ok" | "err" | "idle" {
export interface SidePanelProps {
session: SessionState;
tab: PanelTab;
onTab: (tab: PanelTab) => void;
/** Legacy three-tab vocabulary; the deprecated `subagents` tab is still accepted. */
tab: PanelTab | "subagents";
onTab: (tab: PanelTab | "subagents") => void;
onDispatch: () => void;
onOpenSubagent: (subagent: Subagent) => void;
onOpenTask: (task: TaskItem) => void;
@@ -59,7 +68,7 @@ export function SidePanel({
const { t } = useTranslation();
const subagents = flattenSubagents(session.subagents);
const tasks = session.tasks;
const tabs: { id: PanelTab; label: string; count: number }[] = [
const tabs: { id: PanelTab | "subagents"; 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 },
+91 -22
View File
@@ -4,7 +4,39 @@ import { create } from "zustand";
import type { EntriesCursor, ProjectedEntry } from "@/lib/entry-projection";
import { prependUnique } from "@/lib/entry-projection";
export type PanelTab = "subagents" | "todo" | "tasks";
/**
* Session tray tabs (v0.1.1 Chat IA v3). The old right panel had a third
* `subagents` tab; subagents now live in the session tree, the tray keeps only
* the two session-scoped, read-mostly panels.
*/
export type TrayTab = "todo" | "tasks";
/**
* @deprecated v0.1.1 IA: the right panel is gone. Kept as an alias so callers
* written against the panel still typecheck while they migrate to `TrayTab`.
*/
export type PanelTab = TrayTab;
/** localStorage key for the IA "active only" filter (default on). */
export const ACTIVE_ONLY_KEY = "pi2-active-only";
function readActiveOnly(): boolean {
try {
const value = localStorage.getItem(ACTIVE_ONLY_KEY);
return value == null ? true : value === "1";
} catch {
// Private mode / no storage: the design default is "active only".
return true;
}
}
function writeActiveOnly(value: boolean): void {
try {
localStorage.setItem(ACTIVE_ONLY_KEY, value ? "1" : "0");
} catch {
// ignore
}
}
export interface Attachment {
id: string;
@@ -37,6 +69,11 @@ export const EMPTY_HISTORY: HistoryState = {
resyncToken: 0,
};
/**
* @deprecated v0.1.1 replaced the "subagent preview modal" with the in-place
* child view (`?sub=<id>` + `activeSubagentId`). The field is kept because the
* session-id migration still re-keys it; the UI no longer reads it.
*/
export interface PreviewTarget {
sessionId: string;
subagentId: string;
@@ -44,37 +81,55 @@ export interface PreviewTarget {
export interface ChatStore {
history: Record<string, HistoryState>;
tab: PanelTab;
/** Active tray tab (`todo` / `tasks`). */
trayTab: TrayTab;
/** Tray visibility. The chips in the stream head toggle it. */
trayOpen: boolean;
filter: string;
collapsed: Record<string, boolean>;
/** Render sub-sessions the plugin hid (`:PiSessions` policy). */
/** Render sub-sessions the plugin hid (`:PiSessions` policy) — not the IA filter. */
showHidden: boolean;
/**
* IA filter "only live rows". Deliberately separate from `showHidden`:
* `showHidden` is the plugin's visibility policy, this is the user's lens.
*/
activeOnly: boolean;
treeOpen: boolean;
panelOpen: boolean;
treeCollapsed: boolean;
treeWidth: number;
panelWidth: number;
/** Subagent shown in the in-place child view (mirrors `?sub=` in the URL). */
activeSubagentId: string | null;
/** Session id whose row actions popover (`…`) is open, or `null`. */
rowMenuId: string | null;
/** Workspace switch menu (`ws-menu`) visibility. */
wsMenuOpen: boolean;
sending: { sessionId: string; text: string } | null;
attachments: Attachment[];
/** @deprecated see `PreviewTarget`. */
preview: PreviewTarget | null;
taskOutput: TaskItem | null;
dispatchOpen: boolean;
setTab: (tab: PanelTab) => void;
setTrayTab: (tab: TrayTab) => void;
setTrayOpen: (open: boolean) => void;
/** Same tab again = close (the chip is a toggle). */
toggleTray: (tab: TrayTab) => void;
setFilter: (filter: string) => void;
toggleCollapsed: (id: string) => void;
setAllCollapsed: (ids: string[], collapsed: boolean) => void;
toggleShowHidden: () => void;
setShowHidden: (show: boolean) => void;
setActiveOnly: (activeOnly: boolean) => void;
toggleActiveOnly: () => void;
setTreeOpen: (open: boolean) => void;
setPanelOpen: (open: boolean) => void;
setTreeCollapsed: (collapsed: boolean) => void;
setWidths: (widths: { treeWidth?: number; panelWidth?: number }) => void;
setActiveSubagentId: (id: string | null) => void;
setRowMenuId: (id: string | null) => void;
setWsMenuOpen: (open: boolean) => void;
closeDrawers: () => void;
setSending: (sending: { sessionId: string; text: string } | null) => void;
addAttachment: (attachment: Attachment) => void;
removeAttachment: (id: string) => void;
clearAttachments: () => void;
/** @deprecated see `PreviewTarget`. */
setPreview: (preview: PreviewTarget | null) => void;
setTaskOutput: (task: TaskItem | null) => void;
setDispatchOpen: (open: boolean) => void;
@@ -89,7 +144,7 @@ export interface ChatStore {
/**
* Re-key every per-session slice after the plugin migrates `tmp-N` → the
* real id: history (so an in-flight prompt and its page are not lost),
* the optimistic `sending` chip and the preview target.
* the optimistic `sending` chip and the (deprecated) preview target.
*/
migrateSession: (from: string, to: string) => void;
}
@@ -105,22 +160,26 @@ function updateHistory(
export const useChatStore = create<ChatStore>((set) => ({
history: {},
tab: "subagents",
trayTab: "todo",
trayOpen: false,
filter: "",
collapsed: {},
showHidden: false,
activeOnly: readActiveOnly(),
treeOpen: false,
panelOpen: false,
treeCollapsed: false,
treeWidth: 300,
panelWidth: 340,
activeSubagentId: null,
rowMenuId: null,
wsMenuOpen: false,
sending: null,
attachments: [],
preview: null,
taskOutput: null,
dispatchOpen: false,
setTab: (tab) => set({ tab }),
setTrayTab: (trayTab) => set({ trayTab }),
setTrayOpen: (trayOpen) => set({ trayOpen }),
toggleTray: (tab) =>
set((state) => (state.trayOpen && state.trayTab === tab ? { trayOpen: false } : { trayTab: tab, trayOpen: true })),
setFilter: (filter) => set({ filter }),
toggleCollapsed: (id) =>
set((state) => {
@@ -132,11 +191,21 @@ export const useChatStore = create<ChatStore>((set) => ({
setAllCollapsed: (ids, collapsed) =>
set(() => ({ collapsed: collapsed ? Object.fromEntries(ids.map((id) => [id, true])) : {} })),
toggleShowHidden: () => set((state) => ({ showHidden: !state.showHidden })),
setShowHidden: (showHidden) => set({ showHidden }),
setActiveOnly: (activeOnly) => {
writeActiveOnly(activeOnly);
set({ activeOnly });
},
toggleActiveOnly: () =>
set((state) => {
writeActiveOnly(!state.activeOnly);
return { activeOnly: !state.activeOnly };
}),
setTreeOpen: (treeOpen) => set({ treeOpen }),
setPanelOpen: (panelOpen) => set({ panelOpen }),
setTreeCollapsed: (treeCollapsed) => set({ treeCollapsed }),
setWidths: (widths) => set(widths),
closeDrawers: () => set({ treeOpen: false, panelOpen: false }),
setActiveSubagentId: (activeSubagentId) => set({ activeSubagentId }),
setRowMenuId: (rowMenuId) => set({ rowMenuId }),
setWsMenuOpen: (wsMenuOpen) => set({ wsMenuOpen }),
closeDrawers: () => set({ treeOpen: false }),
setSending: (sending) => set({ sending }),
addAttachment: (attachment) => set((state) => ({ attachments: [...state.attachments, attachment] })),
+412
View File
@@ -0,0 +1,412 @@
import type { Block, Entry, SessionState, Subagent } from "@protocol/types";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { Empty } from "@/components/ui/empty";
import { StatusDot, type DotStatus } from "@/components/ui/status-dot";
import { toast } from "@/components/ui/toast";
import { cn } from "@/lib/utils";
import { EntryBlock } from "./blocks";
import { Composer } from "./composer";
import type { ModelGroup } from "./data";
import { HeadChips } from "./head-chips";
import type { TrayTab } from "./store";
import "@/styles/pages/chat-telemetry.css";
type ToolBlock = Extract<Block, { type: "tool" }>;
const SUB_DOT: Record<Subagent["status"], DotStatus> = {
active: "busy",
completed: "ok",
failed: "err",
interrupted: "attention",
dormant: "exited",
};
function str(value: unknown): string | undefined {
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}
function rec(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
/** Keys a tool call uses to name a subagent (`task`/`subagent` tools vary by provider). */
const AGENT_KEYS = ["agent", "subagent", "target", "name", "ref"] as const;
function firstNamed(record: Record<string, unknown> | undefined): string | undefined {
if (!record) return undefined;
for (const key of AGENT_KEYS) {
const value = str(record[key]);
if (value) return value;
}
return undefined;
}
/**
* Name of the subagent a tool block spawned, if it names one.
*
* pi2d's tool DTO carries free-form `args`, so this mirrors the prototype's
* `tool.agent === sa.name` check across the spellings providers use; the
* tool result `details` is the fallback (it survives older payloads that only
* keep the result).
*/
export function toolAgentName(block: ToolBlock): string | undefined {
return firstNamed(rec(block.args)) ?? firstNamed(rec(block.output?.details));
}
function textOf(entry: Entry): string {
return entry.blocks
.map((block) => (block.type === "text" || block.type === "error" || block.type === "thinking" ? block.text : ""))
.filter(Boolean)
.join("\n");
}
/**
* Synthetic **read-only** timeline for a subagent (design §4.3, CHG-26-18).
*
* pi2d keeps no per-subagent `entries` (`session.subagents` is manifest
* metadata only), so nothing is filtered out of the parent transcript and no
* conversation is invented:
*
* 1. `subagent.task` becomes the first `user` message (it *is* what was asked);
* 2. parent entries whose tool blocks name this subagent are copied with only
* those tool blocks kept;
* 3. `notice` entries (pi2d's sub-reports) that mention the subagent by name/id
* are copied verbatim;
* 4. the result is sorted by `ts`.
*
* Everything else stays in the parent stream, so this never pretends to be a
* complete transcript — the empty state says so when nothing matched.
*/
export function synthesizeSubagentTimeline(subagent: Subagent, entries: Entry[]): Entry[] {
const name = subagent.name?.trim() || undefined;
const task = subagent.task?.trim();
const timeline: Entry[] = [];
if (task) {
timeline.push({
id: `sub-task-${subagent.id}`,
role: "user",
ts: subagent.createdAt ?? 0,
blocks: [{ type: "text", text: task }],
done: true,
});
}
const names = new Set([name, subagent.id].filter((value): value is string => Boolean(value)));
if (!names.size) return timeline;
const matches = (value: string | undefined) => Boolean(value && names.has(value));
for (const entry of entries) {
const toolBlocks = entry.blocks.filter(
(block): block is ToolBlock => block.type === "tool" && matches(toolAgentName(block)),
);
if (toolBlocks.length) {
timeline.push({ ...entry, blocks: toolBlocks });
continue;
}
if (entry.role === "notice") {
const text = textOf(entry);
if (!text) continue;
const mentions = [...names].some((value) => text.includes(value));
if (mentions) timeline.push(entry);
}
}
return timeline.sort((a, b) => a.ts - b.ts);
}
export interface SubagentViewChips {
planDone: number;
planTotal: number;
/** Session-scope tasks (see the scope note in the view). */
taskCount: number;
runningTasks: number;
trayTab: TrayTab;
trayOpen: boolean;
onToggle: (tab: TrayTab) => void;
registerTrigger?: (tab: TrayTab, element: HTMLButtonElement | null) => void;
}
export interface SubagentViewProps {
session: SessionState;
subagent: Subagent;
/** The parent session timeline the child timeline is synthesized from. */
entries: Entry[];
/** `← 父级` / menu: back to the session stream (page keeps Esc + focus restore). */
onBack: () => void;
/** Head chips + `…` menu open the workbench tray. */
onOpenTray: () => void;
/** Narrow viewports: the tree drawer trigger (page owns the drawer). */
onOpenTree: () => void;
/** steer send; the page owns the command layer (`subagent.steer`). */
onSteer: (text: string) => void;
chips: SubagentViewChips;
composer: { models: ModelGroup[]; connected: boolean; paired: boolean };
className?: string;
}
/**
* In-place subagent child view (design §4, CHG-2026-10-26-18/19).
*
* Structure, top to bottom:
* - `.stream-head--sub`: `← 父级` / status dot / name / head chips / `…`.
* **No** status text, model or elapsed time here — those live in the
* telemetry line under the composer (asserted by `chat.subview.test.tsx`).
* - scope note: TODO/Tasks are session-scope in pi2d and are *not* filtered
* per subagent (no fabricated filtering, PLAN §1).
* - the synthetic read-only timeline (reuses `EntryBlock`).
* - steer composer + its note.
*
* Composer dependency: `Composer` has no `subagent` prop yet (that file is
* outside this workstream), so the steer mode is reached with
* `className="is-sub"` (CSS hides attach / model / thinking / queue / abort)
* and a small effect that rewrites the textarea placeholder. When `Composer`
* grows a first-class `subagent`/`placeholder` prop this effect goes away.
* The `onSend` `mode` argument is ignored on purpose: every send is a steer.
*/
export function SubagentView({
session,
subagent,
entries,
onBack,
onOpenTray,
onOpenTree,
onSteer,
chips,
composer,
className,
}: SubagentViewProps) {
const { t } = useTranslation();
const name = subagent.name?.trim() || subagent.id;
const task = subagent.task?.trim() || "";
// `live` is authoritative when present; the status is the fallback.
const isLive = subagent.live === true || subagent.status === "active";
const timeline = useMemo(() => synthesizeSubagentTimeline(subagent, entries), [entries, subagent]);
const [menuOpen, setMenuOpen] = useState(false);
const menuRef = useRef<HTMLDivElement | null>(null);
const moreRef = useRef<HTMLButtonElement | null>(null);
const composerRef = useRef<HTMLDivElement | null>(null);
// The steer composer must never offer the parent session's abort slot nor its
// pending-queue bar, so it gets a neutralised view of the session: idle (the
// single send slot stays a send) and an empty queue. Sends still go through
// `onSteer` → `subagent.steer`, never `prompt.send`.
const steerSession = useMemo<SessionState>(
() => ({ ...session, status: "idle", queue: [] }),
[session],
);
// Composer API gap (see the component note): steer copy lives here.
useEffect(() => {
const element = composerRef.current?.querySelector<HTMLTextAreaElement>("textarea.composer__ta");
if (!element) return;
element.placeholder = isLive ? t("chat.steerPlaceholder") : "";
element.setAttribute("aria-label", t("chat.steer"));
}, [isLive, t]);
// `…` menu: Esc closes the menu (captured, so the page's child-view Esc
// does not fire in the same keypress) and outside clicks dismiss it.
useEffect(() => {
if (!menuOpen) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Escape") return;
event.preventDefault();
event.stopPropagation();
setMenuOpen(false);
moreRef.current?.focus({ preventScroll: true });
};
const onPointerDown = (event: MouseEvent) => {
if (menuRef.current?.contains(event.target as Node)) return;
setMenuOpen(false);
};
document.addEventListener("keydown", onKeyDown, true);
document.addEventListener("mousedown", onPointerDown);
return () => {
document.removeEventListener("keydown", onKeyDown, true);
document.removeEventListener("mousedown", onPointerDown);
};
}, [menuOpen]);
function copyId() {
setMenuOpen(false);
const clipboard = typeof navigator === "undefined" ? undefined : navigator.clipboard;
if (!clipboard?.writeText) return;
void clipboard
.writeText(subagent.id)
.then(() => toast.success(t("chat.subview.copyId")))
.catch(() => undefined);
}
return (
<div
className={cn("subagent-view", "subagent-view--child", className)}
data-testid="subagent-view"
data-sub-id={subagent.id}
data-live={isLive ? "true" : "false"}
>
<div
className="stream-head stream-head--sub"
role="group"
aria-label={t("chat.subview.statusAria", { name, state: t(`state.${subagent.status}`) })}
>
<button
type="button"
className="btn btn--sm btn--ghost stream-head__tree"
aria-label={t("chat.expandTree")}
title={t("chat.expandTree")}
onClick={onOpenTree}
>
<Icon name="branch" />
</button>
<button
type="button"
className="sub-back"
title={t("chat.subview.backTo", { name })}
aria-label={t("chat.subview.backTo", { name })}
onClick={onBack}
>
<Icon name="chevron-right" />
<span className="sub-back__label">{t("chat.subview.back")}</span>
</button>
<div className="stream-title">
<StatusDot status={SUB_DOT[subagent.status]} title={t(`state.${subagent.status}`)} />
<h2 className="stream-name truncate" tabIndex={-1} title={task ? `${name} · ${task}` : name}>
{name}
</h2>
</div>
<div className="spacer" />
<HeadChips
planDone={chips.planDone}
planTotal={chips.planTotal}
taskCount={chips.taskCount}
runningTasks={chips.runningTasks}
trayTab={chips.trayTab}
trayOpen={chips.trayOpen}
onToggle={chips.onToggle}
registerTrigger={chips.registerTrigger}
/>
<div className="sub-menu" ref={menuRef}>
<button
ref={moreRef}
type="button"
className="btn btn--icon btn--ghost sub-more"
aria-haspopup="menu"
aria-expanded={menuOpen}
aria-label={t("chat.subview.menu")}
title={t("chat.subview.menu")}
onClick={() => setMenuOpen((open) => !open)}
>
<Icon name="more" />
</button>
{menuOpen ? (
<div className="sub-pop" role="menu" aria-label={t("chat.subview.menu")}>
<button
type="button"
role="menuitem"
className="sub-pop__item"
onClick={() => {
setMenuOpen(false);
onOpenTray();
}}
>
<Icon name="terminal" />
{t("chat.subview.openTray")}
</button>
<button
type="button"
role="menuitem"
className="sub-pop__item sub-pop__item--back"
onClick={onBack}
>
<Icon name="chevron-right" />
{t("chat.backToParent")}
</button>
<button type="button" role="menuitem" className="sub-pop__item" onClick={copyId}>
<Icon name="copy" />
{t("chat.subview.copyId")}
</button>
</div>
) : null}
</div>
</div>
<p className="sub-scope faint" data-testid="sub-scope">
<Icon name="todo" />
{t("chat.subview.scopeNote")}
</p>
<div className="stream-body stream-body--sub">
<div
className="stream-scroll stream-scroll--sub"
role="log"
aria-live="polite"
aria-readonly="true"
aria-label={t("chat.subview.timelineAria", { name })}
data-testid="sub-timeline"
>
{timeline.length ? (
<div className="stream-list">
{timeline.map((entry, index) => {
const previous = index > 0 ? timeline[index - 1] : undefined;
const turnStart = index === 0 || entry.role === "user" || previous?.role === "user";
return (
<div
key={entry.id}
className={cn("stream-item", turnStart && "turn-start")}
data-entry-id={entry.id}
>
<EntryBlock entry={entry} turnStart={turnStart} />
</div>
);
})}
<div className="stream-end" />
</div>
) : (
<Empty
className="stream-empty sub-empty"
icon={<Icon name="branch" />}
title={t("chat.subview.emptyTitle")}
description={t("chat.subview.emptyText")}
/>
)}
</div>
</div>
<div className="sub-composer" ref={composerRef}>
<div
className={cn("sub-note", isLive ? "is-live" : "is-ended")}
role="note"
data-testid="sub-note"
>
<Icon name={isLive ? "branch" : "revoke"} />
{t(isLive ? "chat.subview.steerNote" : "chat.subview.endedNote")}
</div>
<Composer
session={steerSession}
models={composer.models}
connected={composer.connected}
paired={composer.paired}
sending={null}
queuedCount={0}
onSend={(text) => onSteer(text)}
onAbort={() => undefined}
onRemoveQueue={() => undefined}
onSetSteer={() => undefined}
onSetModel={() => undefined}
onSetThinking={() => undefined}
disabled={!isLive}
className="is-sub"
/>
</div>
</div>
);
}
+269
View File
@@ -0,0 +1,269 @@
import type { ContextUsage, Entry, SessionState, Subagent, UsageTotals } from "@protocol/types";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { plural } from "@/lib/i18n";
import { cn } from "@/lib/utils";
import { formatDuration } from "./format";
import { synthesizeSubagentTimeline } from "./subagent-view";
import "@/styles/pages/chat-telemetry.css";
/** Inline ring geometry (the SVG is the only inline-sized element in the line). */
const RING_R = 9.5;
const RING_C = 2 * Math.PI * RING_R;
const RING_SIZE = 14;
/** Subagent status → tone class on `.sub-state` (design §3.1 mapping). */
const SUB_TONE: Record<Subagent["status"], string> = {
active: "is-live",
completed: "is-ok",
failed: "is-err",
interrupted: "is-warn",
dormant: "is-idle",
};
const SUB_DOT: Record<Subagent["status"], string> = {
active: "dot--busy",
completed: "dot--ok",
failed: "dot--err",
interrupted: "dot--attention",
dormant: "dot--exited",
};
export interface TelemetryCounts {
/** `role === "user"` entries in the view's timeline. */
turns: number;
/** Tool blocks in the view's timeline (pi2d is a block model, not a flat message list). */
tools: number;
}
/** Turns / tools of a timeline — the two facts the main line starts with. */
export function countTelemetry(entries: Entry[]): TelemetryCounts {
let turns = 0;
let tools = 0;
for (const entry of entries) {
if (entry.role === "user") turns += 1;
for (const block of entry.blocks) if (block.type === "tool") tools += 1;
}
return { turns, tools };
}
/** Compact token counts (`840`, `1.2k`, `200k`, `1.1M`) for the mono status line. */
export function compactTokens(value: number): string {
if (!Number.isFinite(value) || value <= 0) return "0";
if (value < 1_000) return String(Math.round(value));
if (value < 10_000) return `${(value / 1_000).toFixed(1)}k`;
if (value < 1_000_000) return `${Math.round(value / 1_000)}k`;
return `${(value / 1_000_000).toFixed(1)}M`;
}
function ringTone(percent: number): string {
if (percent >= 90) return "is-err";
if (percent >= 75) return "is-warn";
return "";
}
/**
* Context-usage ring: a 24×24 viewBox SVG rendered at 14px (design §3.2) with
* `stroke-dasharray: c*pct/100 c` and `rotate(-90 12 12)`. The label doubles as
* `role="img"` + `aria-label` and as the visible `上下文占用 …` text.
*/
function CtxRing({ usage }: { usage: ContextUsage }) {
const { t } = useTranslation();
const percent = Number.isFinite(usage.percent) ? Math.max(0, Math.min(100, usage.percent)) : 0;
const used = compactTokens(usage.tokens);
const window = compactTokens(usage.window);
const label = t("chat.contextUsage", { used, window });
return (
<span className="telemetry__ctx" data-testid="telemetry-ctx">
<svg
className={cn("ctx-ring", ringTone(percent))}
width={RING_SIZE}
height={RING_SIZE}
viewBox="0 0 24 24"
role="img"
aria-label={label}
>
<title>{label}</title>
<circle className="ctx-ring__track" cx="12" cy="12" r={RING_R} fill="none" strokeWidth="2.4" />
<circle
className="ctx-ring__fill"
cx="12"
cy="12"
r={RING_R}
fill="none"
strokeWidth="2.4"
strokeLinecap="round"
transform="rotate(-90 12 12)"
strokeDasharray={`${(RING_C * percent) / 100} ${RING_C}`}
/>
</svg>
<span className="telemetry__ctx-label">{label}</span>
</span>
);
}
/** Session usage → `输入 … · 输出 …`, omitted when the session has no usage yet. */
function usageFacts(usage: UsageTotals | null | undefined): { in: string; out: string } | null {
if (!usage) return null;
const input = compactTokens(usage.input);
const output = compactTokens(usage.output);
if (input === "0" && output === "0") return null;
return { in: input, out: output };
}
function Tsep({ bar = false }: { bar?: boolean }) {
return (
<span className={cn("tsep", bar && "tsep--bar")} aria-hidden="true">
{bar ? "|" : "·"}
</span>
);
}
/** `输入 … · 输出 …`, or nothing when the session has no usage yet. */
function Tokens({ usage }: { usage: UsageTotals | null | undefined }) {
const { t } = useTranslation();
const facts = usageFacts(usage);
if (!facts) return null;
return (
<span className="telemetry__fact" data-testid="telemetry-tokens">
{t("chat.telemetryTokens", facts)}
</span>
);
}
function hasTokens(usage: UsageTotals | null | undefined): boolean {
return usageFacts(usage) !== null;
}
export interface TelemetryProps {
session: SessionState | null;
/** Set in the child view: switches to `.telemetry--sub` (CHG-2026-10-26-19). */
subagent?: Subagent | null;
/** The view's timeline: live+history entries for the session, the parent's for the child. */
entries: Entry[];
className?: string;
}
/**
* The composer status line — the only place the context ring lives (design
* §3). Two branches:
*
* - session: `轮 · 工具 | ctx 环 · token`
* - child view: `状态 · 耗时 · 工具 · 轮 | ctx · token · model · thinking`
* (model / thinking last so narrow screens see state and cost first)
*
* The subagent has no own usage on the wire (`Subagent` carries no
* `contextUsage`/`usage`), so the child branch shows the session-scope numbers
* — never a fabricated per-subagent split. `createdAt`/`lastActiveAt` are the
* only per-subagent timing facts, and the live case ticks once a second.
*/
export function Telemetry({ session, subagent, entries, className }: TelemetryProps) {
const { t } = useTranslation();
const ticking = Boolean(subagent && (subagent.live === true || subagent.status === "active"));
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
if (!ticking) return;
const timer = setInterval(() => setNow(Date.now()), 1_000);
return () => clearInterval(timer);
}, [ticking]);
if (!session && !subagent) return null;
if (subagent) {
const timeline = synthesizeSubagentTimeline(subagent, entries);
const { turns, tools } = countTelemetry(timeline);
const created = subagent.createdAt;
const end = ticking ? now : (subagent.lastActiveAt ?? created);
// `<1s` never renders `0.0s` (design §5.9); below that the elapsed fact is dropped.
const elapsedMs =
created !== undefined && Number.isFinite(created) && end !== undefined ? Math.max(0, end - created) : undefined;
const elapsed = elapsedMs !== undefined && elapsedMs >= 1_000 ? formatDuration(elapsedMs) : null;
const tone = SUB_TONE[subagent.status];
return (
<div
className={cn("telemetry", "telemetry--sub", className)}
role="status"
aria-live="polite"
data-testid="telemetry"
>
<span className={cn("telemetry__state", "sub-state", tone)} data-testid="telemetry-state">
<span className={cn("dot", SUB_DOT[subagent.status])} aria-hidden="true" />
{t(`state.${subagent.status}`)}
</span>
{elapsed ? (
<>
<Tsep />
<span className="sub-fact sub-fact--elapsed" data-testid="telemetry-elapsed">
{t(ticking ? "chat.subview.elapsed" : "chat.subview.duration", { dur: elapsed })}
</span>
</>
) : null}
<Tsep />
<span className="sub-fact" data-testid="telemetry-tools">
{plural("chat.telemetryTools", tools)}
</span>
<Tsep />
<span className="sub-fact" data-testid="telemetry-turns">
{plural("chat.telemetryTurns", turns)}
</span>
{session?.contextUsage ? (
<>
<Tsep bar />
<CtxRing usage={session.contextUsage} />
</>
) : null}
{hasTokens(session?.usage) ? (
<>
<Tsep />
<Tokens usage={session?.usage} />
</>
) : null}
{subagent.model ? (
<>
<Tsep />
<span className="sub-fact sub-fact--model" data-testid="telemetry-model" title={subagent.model}>
{subagent.model}
</span>
</>
) : null}
{subagent.thinking ? (
<>
<Tsep />
<span className="sub-fact sub-fact--think" data-testid="telemetry-thinking">
{subagent.thinking}
</span>
</>
) : null}
</div>
);
}
const counts = countTelemetry(entries);
return (
<div className={cn("telemetry", className)} role="status" aria-live="polite" data-testid="telemetry">
<span className="telemetry__fact" data-testid="telemetry-turns">
{plural("chat.telemetryTurns", counts.turns)}
</span>
<Tsep />
<span className="telemetry__fact" data-testid="telemetry-tools">
{plural("chat.telemetryTools", counts.tools)}
</span>
{session?.contextUsage ? (
<>
<Tsep bar />
<CtxRing usage={session.contextUsage} />
</>
) : null}
{hasTokens(session?.usage) ? (
<>
<Tsep />
<Tokens usage={session?.usage} />
</>
) : null}
</div>
);
}
+196
View File
@@ -0,0 +1,196 @@
/**
* DTO adapter: daemon `Block` → normalized `ToolView`.
*
* pi2d ships `{toolCallId, name, args, output, state, durationMs}`
* (`src/protocol/types.ts`), while the tool-render contract speaks
* `{input, text, result, diff, matches, …}`. This is the single translation layer;
* everything downstream (`ToolRow`, families) only sees `ToolView`.
*/
import type { Block, ToolOutput } from "@protocol/types";
import { fileDiff } from "../diff";
import { splitLines } from "./format";
import { kindOf } from "./kind";
import { stateOf } from "./state";
import type { DiffFile, DiffHunk, DiffLine, DiffPayload, ToolMeta, ToolResult, ToolState, ToolView } from "./types";
export type ToolBlock = Extract<Block, { type: "tool" }>;
export interface AdaptOptions {
/** Agent that issued the call (subagent runs) → `chat.meta.agent` fact. */
agent?: string;
/** Message timestamp — used as `startedAt` while the call is running. */
ts?: number;
/** Explicit elapsed start, overriding `ts`. */
startedAt?: number;
}
/** pi2d's 4 wire states → the canonical state vocabulary. */
const WIRE_STATE: Record<string, ToolState> = {
pending: "queued",
running: "running",
done: "done",
error: "failed",
};
const PATH_KEYS = ["path", "file_path", "filePath", "file", "filename"];
const BEFORE_KEYS = ["oldText", "old_string", "oldString", "before", "original"];
const AFTER_KEYS = ["newText", "new_string", "newString", "after", "content", "replacement"];
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function firstString(source: Record<string, unknown>, keys: string[]): string | undefined {
for (const key of keys) {
const value = source[key];
if (typeof value === "string" && value !== "") return value;
}
return undefined;
}
function firstNumber(source: Record<string, unknown>, keys: string[]): number | undefined {
for (const key of keys) {
const value = source[key];
if (typeof value === "number" && Number.isFinite(value)) return value;
}
return undefined;
}
/** Repo diff line (`"@@ -12,3 +12,4 @@"` + `+/-/ ` prefixed text) → numbered payload line. */
function toPayloadHunk(hunk: { header?: string; lines?: string[] }): DiffHunk {
const header = String(hunk.header ?? "");
const match = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(header);
let oldLine = Number(match?.[1] ?? 1);
let newLine = Number(match?.[2] ?? 1);
const lines: DiffLine[] = (hunk.lines ?? []).map((raw) => {
const sign = raw.slice(0, 1);
const text = raw.slice(1);
if (sign === "+") {
const line: DiffLine = { t: "add", old: null, new: newLine, text };
newLine += 1;
return line;
}
if (sign === "-") {
const line: DiffLine = { t: "del", old: oldLine, new: null, text };
oldLine += 1;
return line;
}
const line: DiffLine = { t: "ctx", old: oldLine, new: newLine, text };
oldLine += 1;
newLine += 1;
return line;
});
return {
header,
oldStart: Number(match?.[1] ?? 1),
newStart: Number(match?.[2] ?? 1),
lines,
};
}
/**
* Best-effort diff for edit-style calls. pi2d never sends a structured diff, so we
* rebuild one from the before/after snippets when the arguments carry them; calls
* without them keep `diff` undefined and the family renders `.diff__empty`.
*/
export function diffFromArgs(args: Record<string, unknown> | undefined): DiffPayload | undefined {
if (!args) return undefined;
const direct = args.diff ?? args.patch;
if (isRecord(direct) && Array.isArray(direct.files)) {
const files = (direct.files as unknown[]).filter(isRecord).map<DiffFile>((file) => ({
path: String(file.path ?? file.file ?? ""),
status: typeof file.status === "string" ? file.status : "modified",
added: firstNumber(file, ["added", "add"]),
removed: firstNumber(file, ["removed", "del"]),
hunks: Array.isArray(file.hunks)
? (file.hunks as unknown[]).filter(isRecord).map((hunk) => toPayloadHunk(hunk as { header?: string; lines?: string[] }))
: [],
}));
return files.length ? { files } : undefined;
}
const path = firstString(args, PATH_KEYS);
if (!path) return undefined;
const before = firstString(args, BEFORE_KEYS);
const after = firstString(args, AFTER_KEYS);
if (before === undefined && after === undefined) return undefined;
const diff = fileDiff(path, before ?? "", after ?? "");
return {
files: [
{
path,
status: before === undefined ? "added" : "modified",
added: diff.add,
removed: diff.del,
hunks: diff.hunks.map((hunk) => toPayloadHunk(hunk)),
},
],
};
}
function textFromOutput(output: ToolOutput | undefined): { lines?: string[]; error?: string; details?: unknown } {
const text = typeof output?.text === "string" ? output.text : "";
const details = output?.details;
const legacy = typeof details === "string" ? details : "";
const source = text || legacy;
const lines = source ? splitLines(source) : undefined;
const error = output?.isError && source.trim() ? source : undefined;
return { lines, error, details };
}
/** `(block, messageId) => ToolView` — the exit contract other workstreams use. */
export function fromPi2Block(block: ToolBlock, messageId: string, options: AdaptOptions = {}): ToolView {
const state = WIRE_STATE[String(block.state ?? "")] ?? stateOf({ state: block.state });
const args = isRecord(block.args) ? block.args : undefined;
const { lines, error, details } = textFromOutput(block.output);
const result: ToolResult = {};
if (error) result.error = error;
if (details !== undefined && !isRecord(details)) result.details = details;
const meta: ToolMeta = {};
if (isRecord(details)) {
// Structured `details` (e.g. `{exitCode, truncated, added}`) is a legacy
// result carrier; surface the facts families know how to render.
result.details = details;
const exitCode = firstNumber(details, ["exitCode", "code"]);
if (exitCode != null) {
result.exitCode = exitCode;
meta.exitCode = exitCode;
}
if (details.truncated === true) result.truncated = true;
const added = firstNumber(details, ["added"]);
const removed = firstNumber(details, ["removed"]);
if (added != null) meta.added = added;
if (removed != null) meta.removed = removed;
}
if (isRecord(args?.meta)) Object.assign(meta, args.meta);
const startedAt = options.startedAt ?? options.ts;
const view: ToolView = {
id: block.toolCallId || messageId,
messageId,
name: block.name,
kind: kindOf(block.name),
state,
durationMs: block.durationMs,
input: args,
result: Object.keys(result).length ? result : undefined,
meta: Object.keys(meta).length ? meta : undefined,
diff: diffFromArgs(args),
};
if (state === "running" && startedAt) view.startedAt = startedAt;
if (options.agent) view.agent = options.agent;
if (typeof block.args === "string" && lines) {
// Legacy `args` that is not an object still renders in the generic body.
view.raw = lines.length === 1 ? (lines[0] ?? "") : lines;
} else if (block.args !== undefined && !args) {
view.raw = block.args;
}
if (lines?.length) view.text = { lines };
return view;
}
+75
View File
@@ -0,0 +1,75 @@
/**
* Row facts (`.tool__meta`) — at most 3 per row, "宁少不多" (design §1).
* Also home of `normalizeTool()`, the legacy-DTO degradation the prototype does
* in `core.js:177-183` (old `details` string → `text.lines`).
*/
import { fileTarget, tpNum, tr } from "./format";
import { isFailure, stateOf } from "./state";
import type { Fact, ToolView } from "./types";
/** §1: facts are capped at 3; everything past it is dropped, never summarized. */
export const MAX_FACTS = 3;
export function fact(text: string): Fact {
return { kind: "text", text };
}
export function statFact(added: number, removed: number): Fact {
return { kind: "stat", added, removed };
}
export function tagFact(label: string): Fact {
return { kind: "tag", label };
}
export function capFacts(facts: Fact[] | null | undefined, max = MAX_FACTS): Fact[] {
return (facts ?? []).filter(Boolean).slice(0, max);
}
/**
* Legacy DTO compatibility: an old `{details: "text"}` tool has no `text.lines`,
* so degrade `details` into lines. Never mutates the caller's object.
*/
export function normalizeTool(tool: ToolView): ToolView {
const hasLines = Array.isArray(tool.text?.lines) && (tool.text?.lines?.length ?? 0) > 0;
if (hasLines || tool.details == null || tool.details === "") return tool;
return { ...tool, text: { ...(tool.text ?? {}), lines: String(tool.details).split("\n") } };
}
/** Generic facts for families without a `meta()` override (`core.js:196-217`). */
export function defaultFacts(tool: ToolView): Fact[] {
const meta = tool.meta ?? {};
const state = stateOf(tool);
const out: Fact[] = [];
const hasRange = Array.isArray(meta.range) && Boolean(tool.input?.path);
if (meta.lines != null && !hasRange) out.push(fact(tpNum("chat.meta.lines", Number(meta.lines))));
if (meta.matches != null) out.push(fact(tpNum("chat.meta.matches", Number(meta.matches))));
if (meta.files != null) out.push(fact(tpNum("chat.meta.files", Number(meta.files))));
if (meta.entries != null) out.push(fact(tpNum("chat.meta.entries", Number(meta.entries))));
if (meta.images != null) out.push(fact(tpNum("chat.meta.images", Number(meta.images))));
if (meta.added != null || meta.removed != null) {
out.push(statFact(Number(meta.added) || 0, Number(meta.removed) || 0));
}
if (meta.newFile) out.push(tagFact(tr("chat.meta.newFile")));
if (tool.input?.background) out.push(fact(tr("chat.meta.background")));
if (isFailure(state) && meta.exitCode != null) {
out.push(fact(tr("chat.meta.exit", { code: String(meta.exitCode) })));
}
if (tool.result?.truncated) out.push(fact(tr("chat.meta.truncated")));
if (tool.agent) out.push(fact(tr("chat.meta.agent", { name: tool.agent })));
return capFacts(out);
}
/** Facts for a row: the family's own list, or the generic default. */
export function factsFor(tool: ToolView, provided: Fact[] | null | undefined): Fact[] {
return capFacts(provided && provided.length ? provided : defaultFacts(tool));
}
/** Target fallback shared by every spec that does not override it. */
export function targetFor(tool: ToolView, provided?: (tool: ToolView) => string): string {
if (!provided) return fileTarget(tool);
const value = provided(tool);
return value == null || value === "" ? fileTarget(tool) : value;
}
@@ -0,0 +1,343 @@
/**
* `read` (inline row, no body) + `write` (edit / write / patch / multi_edit).
*
* The write body is the unified-diff viewer: file accordion (first file open), hunk
* folding (>40 lines → head 20 + tail 10, >3 hunks → "还有 N 段"), two-column line
* numbers. `+`/`-` rows colour the row background and the gutter only; line numbers
* use `--muted-foreground` (not `--faint`) so they stay ≥4.5:1.
*/
import "@/styles/tool-file.css";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { ChevronDown, Copy } from "lucide-react";
import { Button } from "@/components/ui/button";
import { capFacts, defaultFacts, fact, statFact, tagFact } from "../facts";
import { copyText, fileTarget, fmtNum, tpNum, tr } from "../format";
import { KIND_ICON } from "../kind";
import { isFailure, stateOf } from "../state";
import type { DiffFile, DiffHunk, DiffLine, Fact, ToolBodyProps, ToolSpec, ToolView } from "../types";
const LINE_CAP = 40;
const HUNK_HEAD = 20;
const HUNK_TAIL = 10;
const HUNKS_SHOWN = 3;
function str(value: unknown): string | undefined {
return typeof value === "string" && value !== "" ? value : undefined;
}
function toNumber(value: unknown): number | undefined {
const parsed = typeof value === "number" ? value : Number(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
function isCreate(tool: ToolView): boolean {
return tool.name === "write" || tool.input?.mode === "create";
}
/** Failure phrase, appending `chat.diff.notFound` unless the message already says it. */
function writeError(tool: ToolView): string | null {
const raw = String(tool.result?.error || tool.result?.stderr || "").split("\n")[0]?.trim() ?? "";
const head = raw || (isFailure(stateOf(tool)) ? (tool.text?.lines?.[0]?.trim() ?? "") : "");
if (isCreate(tool)) return head || null;
const notFound = tr("chat.diff.notFound");
if (head) {
// The provider message often already names the reason — do not double-prefix it.
if (head.toLowerCase().includes(notFound.toLowerCase())) return head;
return `${notFound} · ${head}`;
}
return isFailure(stateOf(tool)) ? notFound : null;
}
function readError(tool: ToolView): string | null {
const raw = String(tool.result?.error || tool.result?.stderr || "").split("\n")[0]?.trim() ?? "";
const head = raw || (isFailure(stateOf(tool)) ? (tool.text?.lines?.[0]?.trim() ?? "") : "");
return head || null;
}
function lineTotals(file: DiffFile): { added: number; removed: number } {
const hunks = Array.isArray(file.hunks) ? file.hunks : [];
let added = toNumber(file.added);
let removed = toNumber(file.removed);
if (added == null && removed == null) {
added = 0;
removed = 0;
for (const hunk of hunks) {
for (const line of hunk?.lines ?? []) {
if (line?.t === "add") added += 1;
else if (line?.t === "del") removed += 1;
}
}
}
return { added: added ?? 0, removed: removed ?? 0 };
}
/** Row totals: explicit meta → diff files → result (prototype `file.js:67-85`). */
function toolTotals(tool: ToolView): { added: number; removed: number } | null {
if (tool.meta?.added != null || tool.meta?.removed != null) {
return { added: toNumber(tool.meta.added) ?? 0, removed: toNumber(tool.meta.removed) ?? 0 };
}
const files = (tool.diff?.files ?? []).filter(Boolean);
if (files.length) {
return files.reduce<{ added: number; removed: number }>(
(acc, file) => {
const one = lineTotals(file);
acc.added += one.added;
acc.removed += one.removed;
return acc;
},
{ added: 0, removed: 0 },
);
}
if (tool.result?.added != null || tool.result?.removed != null) {
return { added: toNumber(tool.result.added) ?? 0, removed: toNumber(tool.result.removed) ?? 0 };
}
return null;
}
function readMeta(tool: ToolView): Fact[] {
const out: Fact[] = [];
const lines = toNumber(tool.meta?.lines) ?? toNumber(tool.result?.lines);
if (lines != null) out.push(fact(tpNum("chat.meta.lines", lines)));
if (tool.result?.truncated) out.push(fact(tr("chat.meta.truncated")));
if (tool.agent) out.push(fact(tr("chat.meta.agent", { name: tool.agent })));
return capFacts(out);
}
function writeMeta(tool: ToolView): Fact[] {
const out: Fact[] = [];
const totals = toolTotals(tool);
if (totals && (totals.added || totals.removed)) out.push(statFact(totals.added, totals.removed));
const addedFile = (tool.diff?.files ?? []).some((file) => file?.status === "added");
if (tool.meta?.newFile || isCreate(tool) || addedFile) out.push(tagFact(tr("chat.meta.newFile")));
if (tool.meta?.lines != null) out.push(fact(tpNum("chat.meta.lines", Number(tool.meta.lines))));
if (tool.agent) out.push(fact(tr("chat.meta.agent", { name: tool.agent })));
return capFacts(out);
}
function diffText(files: DiffFile[]): string {
const out: string[] = [];
for (const file of files) {
const path = String(file.path ?? "");
out.push(`diff --git a/${path} b/${path}`);
if (file.status === "added") out.push("new file mode 100644");
if (file.status === "deleted") out.push("deleted file mode 100644");
out.push(file.status === "added" ? "--- /dev/null" : `--- a/${path}`);
out.push(file.status === "deleted" ? "+++ /dev/null" : `+++ b/${path}`);
for (const hunk of file.hunks ?? []) {
if (!hunk) continue;
out.push(String(hunk.header ?? `@@ -${hunk.oldStart ?? 0} +${hunk.newStart ?? 0} @@`));
for (const line of hunk.lines ?? []) {
if (!line) continue;
const sign = line.t === "add" ? "+" : line.t === "del" ? "-" : " ";
out.push(sign + String(line.text ?? ""));
}
}
}
return out.join("\n");
}
function EmptyDiff({ tool }: { tool: ToolView }) {
const { t } = useTranslation();
const path = str(tool.input?.path) ?? fileTarget(tool);
return (
<div className="diff__empty">
<span className="diff__empty-text">{t("chat.diff.empty")}</span>
{path ? (
<span className="diff__empty-path mono truncate" title={path}>
{path}
</span>
) : null}
</div>
);
}
function Sign({ kind }: { kind: "add" | "del" | "ctx" }) {
return (
<span className="diff__sign" aria-hidden="true">
{kind === "add" ? "+" : kind === "del" ? "−" : " "}
</span>
);
}
function LineRow({ line }: { line: DiffLine }) {
const kind: "add" | "del" | "ctx" = line.t === "add" ? "add" : line.t === "del" ? "del" : "ctx";
return (
<div className={`diff__line diff__line--${kind}`}>
<span className="diff__num diff__num--old tabular">{line.old == null ? "" : String(line.old)}</span>
<span className="diff__num diff__num--new tabular">{line.new == null ? "" : String(line.new)}</span>
<span className="diff__code">
<Sign kind={kind} />
<span className="diff__text mono">{String(line.text ?? "")}</span>
</span>
</div>
);
}
function Hunk({ hunk }: { hunk: DiffHunk }) {
const [expanded, setExpanded] = useState(false);
const lines = (hunk.lines ?? []).filter(Boolean);
const header = String(hunk.header ?? `@@ -${hunk.oldStart ?? 0} +${hunk.newStart ?? 0} @@`);
if (lines.length <= LINE_CAP || expanded) {
return (
<div className="diff__hunk">
<div className="diff__hunkhead mono">{header}</div>
{lines.map((line, index) => (
<LineRow line={line} key={index} />
))}
</div>
);
}
const head = lines.slice(0, HUNK_HEAD);
const tail = lines.slice(lines.length - HUNK_TAIL);
const omitted = lines.length - HUNK_HEAD - HUNK_TAIL;
return (
<div className="diff__hunk">
<div className="diff__hunkhead mono">{header}</div>
{head.map((line, index) => (
<LineRow line={line} key={`h${index}`} />
))}
<button className="diff__more" type="button" onClick={() => setExpanded(true)}>
<span className="diff__more-count">{tpNum("chat.meta.omitted", omitted)}</span>
<span className="diff__more-cta">{tpNum("chat.diff.showMore", omitted)}</span>
</button>
{tail.map((line, index) => (
<LineRow line={line} key={`t${index}`} />
))}
</div>
);
}
function FileBlock({ file, open, onToggle }: { file: DiffFile; open: boolean; onToggle: () => void }) {
const { t } = useTranslation();
const [showAllHunks, setShowAllHunks] = useState(false);
const path = String(file.path ?? "");
const totals = lineTotals(file);
const hunks = (file.hunks ?? []).filter(Boolean);
const tagKey = file.status === "added" ? "chat.meta.newFile" : file.status === "deleted" ? "chat.meta.deletedFile" : null;
return (
<div className={`diff__file${open ? " is-open" : ""}`}>
<button className="diff__head" type="button" aria-expanded={open} onClick={onToggle}>
<span className="diff__caret" aria-hidden="true">
<ChevronDown size={12} />
</span>
{tagKey ? <span className="diff__tag">{t(tagKey)}</span> : null}
<span className="diff__path mono truncate" title={path}>
{path}
</span>
{totals.added || totals.removed ? (
<span className="diff__stat tabular">
<span className="is-add">{t("chat.meta.added", { n: fmtNum(totals.added) })}</span>
<span className="is-del">{t("chat.meta.removed", { n: fmtNum(totals.removed) })}</span>
</span>
) : null}
</button>
{open ? (
<div className="diff__body">
{hunks.length === 0 ? (
<div className="diff__empty">
<span className="diff__empty-text">{t("chat.diff.empty")}</span>
</div>
) : (
<>
{(showAllHunks ? hunks : hunks.slice(0, HUNKS_SHOWN)).map((hunk, index) => (
<Hunk hunk={hunk} key={index} />
))}
{!showAllHunks && hunks.length > HUNKS_SHOWN ? (
<button className="diff__more" type="button" onClick={() => setShowAllHunks(true)}>
{tpNum("chat.diff.moreHunks", hunks.length - HUNKS_SHOWN)}
</button>
) : null}
</>
)}
</div>
) : null}
</div>
);
}
function DiffBody({ tool }: ToolBodyProps) {
const { t } = useTranslation();
const files = (tool.diff?.files ?? []).filter(Boolean);
const [open, setOpen] = useState<Record<number, boolean>>({ 0: true });
if (!files.length) return <EmptyDiff tool={tool} />;
const setAll = (next: boolean) => {
setOpen(Object.fromEntries(files.map((_, index) => [index, next])));
};
return (
<div className="diff">
{files.length > 1 ? (
<div className="diff__bar">
<span className="diff__bar-files tabular">{tpNum("chat.diff.files", files.length)}</span>
<Button variant="ghost" size="sm" className="diff__bar-btn" onClick={() => setAll(true)}>
{t("chat.meta.showAll")}
</Button>
<Button variant="ghost" size="sm" className="diff__bar-btn" onClick={() => setAll(false)}>
{t("chat.meta.collapse")}
</Button>
<Button
variant="ghost"
size="sm"
className="diff__bar-btn diff__bar-copy"
aria-label={t("chat.diff.copy")}
title={t("chat.diff.copy")}
onClick={() => copyText(diffText(files))}
>
<Copy size={12} aria-hidden />
<span>{t("chat.diff.copy")}</span>
</Button>
</div>
) : null}
<div className="diff__files">
{files.map((file, index) => (
<FileBlock
file={file}
key={`${file.path ?? "file"}-${index}`}
open={Boolean(open[index])}
onToggle={() => setOpen((current) => ({ ...current, [index]: !current[index] }))}
/>
))}
</div>
</div>
);
}
/** `read` is inline: one row, no caret, no body (design §4.2). */
export const readSpec: ToolSpec = {
id: "read",
icon: KIND_ICON.read,
inline: true,
verb: "read",
target: fileTarget,
meta: readMeta,
error: readError,
actions: (tool) => [
{
icon: Copy,
labelKey: "chat.meta.copyPath",
onAction: () => copyText(str(tool.input?.path) ?? fileTarget(tool)),
},
],
};
export const writeSpec: ToolSpec = {
id: "write",
icon: KIND_ICON.write,
verb: (tool) => (isCreate(tool) ? "write.create" : "write"),
target: fileTarget,
meta: writeMeta,
error: writeError,
Body: (props) => <DiffBody {...props} />,
};
/** Read-only fallback for the generic family when it needs the shared defaults. */
export { defaultFacts };
@@ -0,0 +1,106 @@
/**
* `generic` — unregistered tools and MCP calls (`mcp__server__tool`).
*
* Contract §4.11: never blank, never throws. Two `.ts` sections (input / result);
* every value renders as JSON with a 24-line budget and a counted fold, empty
* values render `chat.meta.noOutput`.
*/
import "@/styles/tool-generic.css";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { firstLine, tpNum } from "../format";
import { KIND_ICON, humanName } from "../kind";
import { isFailure, stateOf } from "../state";
import type { ToolBodyProps, ToolSpec, ToolView } from "../types";
import { ToolFoot } from "../tool-body";
/** `jsonBlock` fold budget (prototype `core.js:260-275`). */
const JSON_LINES = 24;
function isEmptyValue(value: unknown): boolean {
if (value == null) return true;
if (typeof value === "string") return value.trim() === "";
if (Array.isArray(value)) return value.length === 0;
if (typeof value === "object") return Object.keys(value as Record<string, unknown>).length === 0;
return false;
}
function jsonText(value: unknown): string {
try {
const text = JSON.stringify(value, null, 2);
return text == null ? String(value) : text;
} catch {
return String(value);
}
}
/** JSON block with a 24-line budget; the fold always reports how many lines are hidden. */
function JsonBlock({ value }: { value: unknown }) {
const { t } = useTranslation();
const [expanded, setExpanded] = useState(false);
const text = jsonText(value);
const lines = text.split("\n");
const omitted = Math.max(0, lines.length - JSON_LINES);
const shown = expanded || omitted === 0 ? text : `${lines.slice(0, JSON_LINES).join("\n")}\n…`;
return (
<div className="tool-json">
<pre className="mono tool__pre tool__pre--json">{shown}</pre>
{expanded || omitted === 0 ? null : (
<ToolFoot>
<span className="tool__foot-count tabular">{tpNum("chat.meta.omitted", omitted)}</span>
<Button variant="ghost" size="sm" onClick={() => setExpanded(true)}>
{t("chat.meta.showAll")}
</Button>
</ToolFoot>
)}
</div>
);
}
function Section({ titleKey, value }: { titleKey: string; value: unknown }) {
const { t } = useTranslation();
return (
<section className="ts generic__section">
<h4 className="ts__title">{t(titleKey)}</h4>
{isEmptyValue(value) ? (
<div className="tool-empty">{t("chat.meta.noOutput")}</div>
) : (
<JsonBlock value={value} />
)}
</section>
);
}
function GenericBody({ tool }: ToolBodyProps) {
// Legacy DTOs carry a bare `raw` args value instead of a structured `input`.
const input = tool.input ?? tool.raw;
return (
<div className="generic__body">
<Section titleKey="chat.meta.input" value={input} />
<Section titleKey="chat.meta.result" value={tool.result} />
</div>
);
}
/** Failure phrase: explicit `result.error` / `stderr`, else first output line on hard failure. */
function errorOf(tool: ToolView): string | null {
const explicit = tool.result?.error || tool.result?.stderr;
const first = tool.text?.lines?.[0] ?? null;
const raw = explicit || (isFailure(stateOf(tool)) ? first : null);
if (raw == null || raw === "") return null;
return firstLine(raw);
}
export const genericSpec: ToolSpec = {
id: "generic",
icon: KIND_ICON.generic,
verb: "generic",
target: (tool) => humanName(tool.name),
error: errorOf,
Body: (props) => <GenericBody {...props} />,
};
@@ -0,0 +1,516 @@
/**
* `search` (grep / search) + `find` (find / glob / ls / list_dir).
*
* Row: `搜索 “pattern” · path | N 个文件 · M 处`. Bodies: hits grouped by file with
* pattern highlighting and a three-level fold budget (6 hits/file, 60 hits, 12 files);
* `find` is a flat, one-level-directory-grouped list folded at 15 items. Every fold
* reports how many items are hidden (`chat.meta.more`).
*/
import "@/styles/tool-search.css";
import { Fragment, useState } from "react";
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Copy, File, Folder } from "lucide-react";
import { capFacts, fact } from "../facts";
import { copyText, fileTarget, fmtNum, tpNum, tr } from "../format";
import { KIND_ICON, humanName } from "../kind";
import type { Fact, FsEntry, SearchMatch, ToolBodyProps, ToolSpec, ToolView } from "../types";
/* Fold budgets (contract §4.4 / §4.5). */
const MAX_HITS_PER_FILE = 6;
const MAX_HITS = 60;
const MAX_FILES = 12;
const MAX_FIND_ITEMS = 15;
/** Highlight loop guard against pathological patterns (`search.js:17`). */
const MARK_GUARD = 400;
function str(value: unknown): string | undefined {
return typeof value === "string" && value !== "" ? value : undefined;
}
function numOf(value: unknown): number {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
}
function cmpStr(a: unknown, b: unknown): number {
const x = String(a);
const y = String(b);
return x < y ? -1 : x > y ? 1 : 0;
}
function splitPath(path: unknown): { parts: string[]; name: string } {
const parts = String(path ?? "")
.split("/")
.filter(Boolean);
const name = parts.length ? (parts[parts.length - 1] ?? "") : String(path ?? "");
return { parts, name };
}
/* ------------------------------------------------------------------ highlight */
interface Piece {
text: string;
mark?: boolean;
}
function patternRegex(pattern: string): RegExp | null {
if (!pattern) return null;
try {
return new RegExp(pattern, "gi");
} catch {
return null;
}
}
function literalPieces(src: string, needle: string): Piece[] {
const out: Piece[] = [];
const hay = src.toLowerCase();
const low = needle.toLowerCase();
let from = 0;
let guard = 0;
let idx = hay.indexOf(low, from);
while (idx !== -1 && guard < MARK_GUARD) {
guard += 1;
if (idx > from) out.push({ text: src.slice(from, idx) });
out.push({ text: src.slice(idx, idx + needle.length), mark: true });
from = idx + needle.length;
idx = hay.indexOf(low, from);
}
if (from < src.length) out.push({ text: src.slice(from) });
return out.length ? out : [{ text: src }];
}
function regexPieces(src: string, re: RegExp): Piece[] | null {
const out: Piece[] = [];
let from = 0;
let guard = 0;
let match = re.exec(src);
while (match !== null && guard < MARK_GUARD) {
guard += 1;
const at = match.index;
if (!match[0]) {
// Zero-width match: skip one char so the loop always advances.
re.lastIndex += 1;
} else {
if (at > from) out.push({ text: src.slice(from, at) });
out.push({ text: match[0], mark: true });
from = at + match[0].length;
if (re.lastIndex <= at) re.lastIndex = from;
}
match = re.exec(src);
}
if (!out.length) return null;
if (from < src.length) out.push({ text: src.slice(from) });
return out;
}
function highlight(text: unknown, pattern: unknown): ReactNode {
const src = text == null ? "" : String(text);
const needle = pattern == null ? "" : String(pattern);
if (!src || !needle) return src;
const re = patternRegex(needle);
const pieces = (re && regexPieces(src, re)) || literalPieces(src, needle);
return pieces.map((piece, index) =>
piece.mark ? (
<mark className="search__mark" key={index}>
{piece.text}
</mark>
) : (
<Fragment key={index}>{piece.text}</Fragment>
),
);
}
/* ------------------------------------------------------------------- helpers */
function TextLines({ lines }: { lines: string[] }) {
return (
<div className="tool-lines">
{lines.map((line, index) => (
<div className="tool-line" key={index}>
<span className="tool-line__txt mono">{line}</span>
</div>
))}
</div>
);
}
function EmptyOutput() {
return <div className="tool-empty">{tr("chat.meta.noOutput")}</div>;
}
function matchesOf(tool: ToolView): SearchMatch[] {
return (Array.isArray(tool.matches) ? tool.matches : []).filter((m) => m && m.path != null && String(m.path) !== "");
}
function uniquePaths(list: SearchMatch[]): string[] {
const seen = new Set<string>();
const out: string[] = [];
for (const match of list) {
const path = String(match.path);
if (!seen.has(path)) {
seen.add(path);
out.push(path);
}
}
return out.sort(cmpStr);
}
interface HitGroup {
path: string;
hits: SearchMatch[];
}
function groupHits(list: SearchMatch[]): HitGroup[] {
const map = new Map<string, SearchMatch[]>();
for (const match of list) {
const path = String(match.path);
const bucket = map.get(path);
if (bucket) bucket.push(match);
else map.set(path, [match]);
}
const groups: HitGroup[] = [...map.entries()].map(([path, hits]) => ({
path,
hits: [...hits].sort((a, b) => numOf(a.line) - numOf(b.line) || numOf(a.col) - numOf(b.col)),
}));
groups.sort((a, b) => cmpStr(a.path, b.path));
return groups;
}
/* -------------------------------------------------------------------- search */
interface HitRow {
hit: SearchMatch;
hidden: boolean;
overGroup: boolean;
overGlobal: boolean;
}
function SearchBody({ tool }: ToolBodyProps) {
const { t } = useTranslation();
const [openGroups, setOpenGroups] = useState<Record<string, boolean>>({});
const [allOpen, setAllOpen] = useState(false);
const matches = matchesOf(tool);
if (!matches.length) {
const lines = Array.isArray(tool.text?.lines) ? tool.text.lines : null;
if (lines?.length) return <TextLines lines={lines} />;
return (
<div className="search__empty">
<span className="search__empty-title">{t("chat.meta.noMatches")}</span>
<span className="search__empty-hint">{t("chat.search.noMatchesHint")}</span>
</div>
);
}
const pattern = str(tool.input?.pattern) ?? "";
const groups = groupHits(matches);
// Budget accounting, exactly in prototype order: per-file first, then global.
let shownFiles = 0;
let shownHits = 0;
let hiddenHits = 0;
let globalOverflow = false;
const blocks = groups.map((group) => {
const globalOk = shownFiles < MAX_FILES && shownHits < MAX_HITS;
const rows: HitRow[] = [];
group.hits.forEach((hit, index) => {
const overGroup = index >= MAX_HITS_PER_FILE;
const overGlobal = !globalOk || shownHits >= MAX_HITS;
if (overGroup || overGlobal) {
hiddenHits += 1;
if (overGlobal) globalOverflow = true;
} else {
shownHits += 1;
}
rows.push({ hit, hidden: overGroup || overGlobal, overGroup, overGlobal });
});
if (!globalOk) globalOverflow = true;
else shownFiles += 1;
return { group, globalOk, rows };
});
const groupMore = (path: string) => {
if (allOpen) return false;
const block = blocks.find((b) => b.group.path === path);
return Boolean(block && block.globalOk && block.rows.some((row) => row.overGroup));
};
const rowHidden = (path: string, row: HitRow): boolean => {
if (allOpen) return false;
if (!row.hidden) return false;
return !(openGroups[path] && row.overGroup);
};
return (
<div className="search">
{blocks.map(({ group, globalOk, rows }) => {
const hidden = !globalOk && !allOpen;
const hiddenCount = rows.filter((row) => row.overGroup).length;
return (
<div className="search__group" hidden={hidden} key={group.path}>
<div className="search__file">
<span className="search__ico" aria-hidden="true">
<File size={12} />
</span>
<span className="search__path mono truncate" title={group.path}>
{group.path}
</span>
<span className="badge badge--outline badge--sm tabular">{fmtNum(group.hits.length)}</span>
</div>
<div className="search__hits">
{rows.map((row, index) => (
<div className="search__hit" hidden={rowHidden(group.path, row)} key={index}>
<span className="search__ln tabular" aria-hidden="true">
{row.hit.line == null ? "" : String(row.hit.line)}
</span>
<span className="search__code mono">{highlight(row.hit.text, pattern)}</span>
</div>
))}
</div>
{groupMore(group.path) ? (
<div className="search__foot">
<button
className="search__more search__more--group"
type="button"
onClick={() =>
setOpenGroups((current) => ({ ...current, [group.path]: true }))
}
>
{t("chat.meta.more", { n: fmtNum(hiddenCount) })}
</button>
</div>
) : null}
</div>
);
})}
{hiddenHits > 0 && globalOverflow && !allOpen ? (
<div className="search__foot search__foot--all">
<button className="search__more" type="button" onClick={() => setAllOpen(true)}>
{t("chat.meta.more", { n: fmtNum(hiddenHits) })}
</button>
</div>
) : null}
</div>
);
}
/* ---------------------------------------------------------------------- find */
interface FindItem {
key: string;
title: string;
dir: string;
name: string;
type: "file" | "dir";
size?: number | null;
}
interface FindGroup {
key: string;
label: string;
items: FindItem[];
}
function filesGroups(tool: ToolView, files: string[]): FindGroup[] {
const map = new Map<string, FindItem[]>();
for (const path of [...files].sort(cmpStr)) {
const { parts } = splitPath(path);
const key =
parts.length > 1 ? String(parts[0]) : (str(tool.input?.path) ?? humanName(tool.name));
const rest = parts.length > 1 ? parts.slice(1) : parts;
const name = rest.length ? String(rest[rest.length - 1]) : String(path);
const item: FindItem = {
key: `${key}\u0000${path}`,
title: path,
dir: rest.slice(0, -1).join("/"),
name,
type: "file",
};
const bucket = map.get(key);
if (bucket) bucket.push(item);
else map.set(key, [item]);
}
return [...map.entries()]
.sort((a, b) => cmpStr(a[0], b[0]))
.map(([key, items]) => ({
key,
label: key,
items: items.sort((a, b) => cmpStr(a.name, b.name)),
}));
}
function entriesGroups(tool: ToolView, entries: FsEntry[]): FindGroup[] {
const label = str(tool.input?.path) ?? humanName(tool.name);
const items = [...entries]
.sort((a, b) => cmpStr(a?.name, b?.name))
.map<FindItem>((entry, index) => {
const isDir = entry?.type === "dir" || entry?.type === "directory";
const name = String(entry?.name ?? "");
return {
key: `entry-${index}-${name}`,
title: name,
dir: "",
name,
type: isDir ? "dir" : "file",
size: entry?.size ?? null,
};
});
return [{ key: label, label, items }];
}
function FindBody({ tool }: ToolBodyProps) {
const { t } = useTranslation();
const [expanded, setExpanded] = useState(false);
const entries = Array.isArray(tool.entries) ? tool.entries : null;
const files = (Array.isArray(tool.files) ? tool.files : []).map(String).filter(Boolean);
let groups: FindGroup[] | null = null;
if (entries?.length) groups = entriesGroups(tool, entries);
else if (files.length) groups = filesGroups(tool, files);
if (!groups) {
const lines = Array.isArray(tool.text?.lines) ? tool.text.lines : null;
return lines?.length ? <TextLines lines={lines} /> : <EmptyOutput />;
}
let shown = 0;
let hiddenTotal = 0;
const budgeted = groups.map((group) => {
const items = group.items.map((item) => {
if (!expanded && shown >= MAX_FIND_ITEMS) {
hiddenTotal += 1;
return { item, hidden: true };
}
shown += 1;
return { item, hidden: false };
});
return { ...group, items };
});
return (
<div className="find">
{budgeted.map((group) => {
const visible = group.items.some((entry) => !entry.hidden);
return (
<div className="find__group-box" hidden={!visible} key={group.key}>
<div className="find__group mono truncate" title={group.label}>
{group.label}
</div>
<div className="find__list">
{group.items.map(({ item, hidden }) => (
<div className="find__item" hidden={hidden} title={item.title} key={item.key}>
<span className="find__ico" aria-hidden="true">
{item.type === "dir" ? <Folder size={12} /> : <File size={12} />}
</span>
<span className="find__path mono">
{item.dir ? <span className="find__dir">{item.dir}/</span> : null}
<span className="find__name">{item.name}</span>
</span>
{item.size != null ? (
<span className="find__size tabular" aria-hidden="true">
{fmtNum(item.size)}
</span>
) : null}
</div>
))}
</div>
</div>
);
})}
{hiddenTotal > 0 && !expanded ? (
<div className="find__foot">
<button className="find__more" type="button" onClick={() => setExpanded(true)}>
{t("chat.meta.more", { n: fmtNum(hiddenTotal) })}
</button>
</div>
) : null}
</div>
);
}
/* ---------------------------------------------------------------------- specs */
function targetOf(tool: ToolView): string {
const input = tool.input ?? {};
const pattern = str(input.pattern);
const path = str(input.path);
if (pattern && path) return `“${pattern}” · ${path}`;
if (pattern) return `“${pattern}”`;
return fileTarget(tool);
}
function searchMeta(tool: ToolView): Fact[] {
const matches = matchesOf(tool);
const total = matches.length || Number(tool.meta?.matches ?? 0);
const files = matches.length ? uniquePaths(matches).length : Number(tool.meta?.files ?? 0);
const out: Fact[] = [];
// 0 hits stay quiet: only `0 处`, never "0 个文件" and never an error.
if (files && total) out.push(fact(tpNum("chat.meta.files", files)));
out.push(fact(tpNum("chat.meta.matches", total)));
if (tool.result?.truncated) out.push(fact(tr("chat.meta.truncated")));
return capFacts(out);
}
function errorOf(tool: ToolView): string | null {
const raw = tool.result?.error || tool.result?.stderr;
if (!raw) return null;
return String(raw).split("\n")[0]?.trim() || null;
}
function findTarget(tool: ToolView): string {
const input = tool.input ?? {};
const name = String(tool.name ?? "").toLowerCase();
if (name === "ls" || name === "list_dir") return str(input.path) ?? humanName(tool.name);
if (str(input.pattern)) return `“${String(input.pattern)}”`;
if (str(input.path)) return String(input.path);
return humanName(tool.name);
}
function findMeta(tool: ToolView): Fact[] {
const out: Fact[] = [];
const entries = Array.isArray(tool.entries) ? tool.entries : null;
const files = (Array.isArray(tool.files) ? tool.files : []).map(String).filter(Boolean);
if (entries) out.push(fact(tpNum("chat.meta.entries", entries.length)));
else if (files.length || tool.meta?.files != null) {
out.push(fact(tpNum("chat.meta.files", files.length || Number(tool.meta?.files ?? 0))));
}
if (tool.result?.truncated) out.push(fact(tr("chat.meta.truncated")));
return capFacts(out);
}
const FIND_VERB: Record<string, string> = { ls: "find.list", list_dir: "find.list" };
export const searchSpec: ToolSpec = {
id: "search",
icon: KIND_ICON.search,
verb: "search",
target: targetOf,
meta: searchMeta,
error: errorOf,
actions: () => [],
Body: (props) => <SearchBody {...props} />,
};
export const findSpec: ToolSpec = {
id: "find",
icon: KIND_ICON.find,
verb: (tool) => FIND_VERB[String(tool.name ?? "").toLowerCase()] ?? "find",
target: findTarget,
meta: findMeta,
error: errorOf,
actions: (tool) => {
const files = (Array.isArray(tool.files) ? tool.files : []).map(String).filter(Boolean);
if (!files.length) return [];
return [
{
icon: Copy,
labelKey: "chat.meta.copyPath",
onAction: () => copyText(files.join("\n")),
},
];
},
Body: (props) => <FindBody {...props} />,
};
@@ -0,0 +1,274 @@
/**
* `shell` (bash / exec / shell) + `task` (task / tasks) — one family, one shape.
*
* Row: `verb target · background · exit N · N 行`. Body: `$ command` (≤3 lines,
* copy), log (head 5 + tail 5 with a counted fold), and a footer that only exists
* for failed / soft states (`task` adds the stop button).
*/
import "@/styles/tool-shell.css";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Copy, Square } from "lucide-react";
import { Button } from "@/components/ui/button";
import { capFacts, fact } from "../facts";
import { copyText, durShort, fileTarget, tpNum, tr } from "../format";
import { KIND_ICON } from "../kind";
import { isFailure, isRunning, isSoft, stateOf } from "../state";
import type { Fact, ToolBodyProps, ToolCtx, ToolSpec, ToolView } from "../types";
function str(value: unknown): string | undefined {
return typeof value === "string" && value !== "" ? value : undefined;
}
function num(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function cmdOf(tool: ToolView): string {
return str(tool.input?.command) ?? "";
}
function exitCodeOf(tool: ToolView): number | null {
const meta = num(tool.meta?.exitCode);
if (meta != null) return meta;
const result = num(tool.result?.exitCode);
return result ?? null;
}
function lineCountOf(tool: ToolView): number | null {
const total = num(tool.text?.totalLines);
if (total != null) return total;
const meta = num(tool.meta?.lines);
if (meta != null) return meta;
const lines = tool.text?.lines;
if (Array.isArray(lines)) return lines.length;
return num(tool.result?.lines) ?? null;
}
function taskIdOf(tool: ToolView): string | null {
return str(tool.input?.taskId) ?? str(tool.result?.taskId) ?? str(tool.meta?.taskId) ?? null;
}
function isTruncated(tool: ToolView): boolean {
return Boolean(tool.text?.truncated) || tool.result?.truncated === true;
}
/** Target = first non-empty command line (prototype `shell.js:52-58`). */
function targetOf(tool: ToolView): string {
const command = cmdOf(tool);
if (!command) return fileTarget(tool);
const first = command
.split("\n")
.map((line) => line.trim())
.find(Boolean);
return first || fileTarget(tool);
}
/** Facts, in priority order: background · exit N · N 行 · truncated (≤3). */
function metaOf(tool: ToolView): Fact[] {
const out: Fact[] = [];
const exitCode = exitCodeOf(tool);
const lines = lineCountOf(tool);
if (tool.input?.background) out.push(fact(tr("chat.meta.background")));
if (exitCode != null && exitCode !== 0) out.push(fact(tr("chat.meta.exit", { code: String(exitCode) })));
if (lines != null) out.push(fact(tpNum("chat.meta.lines", lines)));
if (isTruncated(tool)) out.push(fact(tr("chat.meta.truncated")));
return capFacts(out);
}
/** Failure phrase: `result.error` → `result.stderr` → (hard failure only) first line. */
function errorOf(tool: ToolView): string | null {
const first = tool.text?.lines?.[0] ?? null;
const raw = tool.result?.error || tool.result?.stderr || (isFailure(stateOf(tool)) ? first : null);
if (raw == null || raw === "") return null;
return String(raw).split("\n")[0] ?? null;
}
function actionsOf(tool: ToolView, ctx: ToolCtx) {
const actions: ReturnType<NonNullable<ToolSpec["actions"]>> = [];
const command = cmdOf(tool);
if (command) {
actions.push({
icon: Copy,
labelKey: "chat.shell.copyCommand",
onAction: () => copyText(command),
});
}
const taskId = taskIdOf(tool);
if (tool.input?.background && taskId && isRunning(stateOf(tool)) && ctx.onStopTask) {
actions.push({
icon: Square,
labelKey: "chat.shell.stop",
danger: true,
onAction: () => ctx.onStopTask?.(taskId),
});
}
return actions;
}
function CmdBlock({ command }: { command: string }) {
const { t } = useTranslation();
const all = command.split("\n");
const shown = all.slice(0, 3).join("\n");
const hidden = all.length - 3;
return (
<div className="shell__cmd">
<span className="shell__prompt" aria-hidden="true">
$
</span>
<div className="shell__cmd-main">
<pre className="shell__cmd-text mono" title={command}>
{shown}
</pre>
{hidden > 0 ? (
<span className="shell__cmd-count">{t("chat.meta.shownOfTotal", { shown: 3, total: all.length })}</span>
) : null}
</div>
<Button
variant="ghost"
size="sm"
className="shell__copy"
aria-label={t("chat.shell.copyCommand")}
title={t("chat.shell.copyCommand")}
onClick={() => copyText(command)}
>
<Copy size={12} aria-hidden />
<span className="shell__copy-label">{t("chat.shell.copyCommand")}</span>
</Button>
</div>
);
}
function LogBlock({ tool }: { tool: ToolView }) {
const { t } = useTranslation();
const [expanded, setExpanded] = useState(false);
const logRef = useRef<HTMLDivElement>(null);
const all = tool.text?.lines ?? [];
const truncated = tool.text?.truncated && typeof tool.text.truncated === "object" ? tool.text.truncated : null;
const headCount = truncated ? (truncated.headLines ?? 5) : all.length;
const tailCount = truncated ? (truncated.tailLines ?? 5) : 0;
const total = truncated?.total ?? all.length;
const head = all.slice(0, headCount);
const tail = tailCount ? all.slice(Math.max(head.length, all.length - tailCount)) : [];
const omitted = truncated ? Math.max(0, total - headCount - tailCount) : 0;
const running = isRunning(stateOf(tool));
// Running rows follow the tail; a manual scroll stops it because the fold is local state.
useEffect(() => {
const node = logRef.current;
if (running && node && !expanded) node.scrollTop = node.scrollHeight;
}, [running, all.length, expanded]);
if (!all.length) return <div className="tool-empty">{t("chat.meta.noOutput")}</div>;
const showAllLines = expanded || !truncated || omitted <= 0;
const lines = showAllLines ? all : head;
return (
<div className="shell__log" ref={logRef}>
{lines.map((line, index) => (
<div className="shell__line mono" key={index}>
{line}
</div>
))}
{showAllLines ? null : (
<>
<div className="shell__omitted">
<span className="shell__omitted-text">{tpNum("chat.meta.omitted", omitted)}</span>
<Button variant="ghost" size="sm" className="shell__show-all" onClick={() => setExpanded(true)}>
{t("chat.meta.showAll")}
</Button>
</div>
{tail.map((line, index) => (
<div className="shell__line mono" key={`tail-${index}`}>
{line}
</div>
))}
</>
)}
</div>
);
}
function FootBlock({ tool, ctx, stop }: ToolBodyProps & { stop?: boolean }) {
const { t } = useTranslation();
const state = stateOf(tool);
const exitCode = exitCodeOf(tool);
const lines = lineCountOf(tool);
const duration = tool.durationMs != null ? durShort(tool.durationMs) : null;
const parts: string[] = [];
if (exitCode != null) parts.push(tr("chat.meta.exit", { code: String(exitCode) }));
if (duration) parts.push(duration);
if (lines != null) parts.push(tpNum("chat.meta.lines", lines));
const taskId = taskIdOf(tool);
const canStop = Boolean(stop && taskId && (state === "running" || state === "queued") && ctx.onStopTask);
// Success has no footer at all (§0.2); failures/soft states explain themselves.
const showFacts = (isFailure(state) || isSoft(state)) && parts.length > 0;
if (!showFacts && !canStop) return null;
return (
<div className="shell__foot">
{showFacts
? parts.map((part, index) => (
<span key={part + index}>
{index ? (
<span className="tsep" aria-hidden="true">
·
</span>
) : null}
<span className="shell__foot-item tabular">{part}</span>
</span>
))
: null}
{canStop ? (
<Button
variant="danger"
size="sm"
className="shell__stop"
onClick={() => {
if (taskId) ctx.onStopTask?.(taskId);
}}
>
<Square size={12} aria-hidden />
<span>{t("chat.shell.stop")}</span>
</Button>
) : null}
</div>
);
}
function ShellBody({ tool, ctx, stop }: ToolBodyProps & { stop?: boolean }) {
const command = cmdOf(tool);
return (
<div className="shell__body">
{command ? <CmdBlock command={command} /> : null}
<LogBlock tool={tool} />
<FootBlock tool={tool} ctx={ctx} stop={stop} />
</div>
);
}
export const shellSpec: ToolSpec = {
id: "shell",
icon: KIND_ICON.shell,
verb: "shell",
target: targetOf,
meta: metaOf,
error: errorOf,
actions: actionsOf,
Body: (props) => <ShellBody {...props} />,
};
/** Same shape as `shell`; only the verb, glyph and the footer stop button differ. */
export const taskSpec: ToolSpec = {
...shellSpec,
id: "task",
icon: KIND_ICON.task,
verb: "task",
Body: (props) => <ShellBody {...props} stop />,
};
+123
View File
@@ -0,0 +1,123 @@
/**
* Pure formatting helpers — `durShort` / `fileTarget` / `domainOf` / `tpNum`
* (prototype `core.js:126-193`), plus the number and text utilities the tool
* families share. No React, no DOM writes (except the clipboard helper).
*/
import i18n, { plural } from "@/lib/i18n";
import { humanName } from "./kind";
import type { ToolView } from "./types";
/** Translate through the shared i18next instance (keys are flat + dotted). */
export function tr(key: string, params?: Record<string, unknown>): string {
return String(i18n.t(key, params ?? {}));
}
/** Grouped counts, mirroring the prototype `App.fmt.num` (`860`, `12.3k`, `1.2M`). */
export function fmtNum(n: number): string {
const value = Number.isFinite(n) ? n : 0;
if (value >= 1e6) return `${(value / 1e6).toFixed(1)}M`;
if (value >= 1e3) return `${(value / 1e3).toFixed(1)}k`;
return String(value);
}
/**
* Plural-aware count: picks `key.one` / `key.other` through `Intl.PluralRules`
* and falls back to the base key (prototype `I18N.plural`, `i18n.js:1394-1400`).
*/
export function tpNum(key: string, n: number): string {
return plural(key, n, { n: fmtNum(n) });
}
/** Compact duration: `<0.1s` / `340ms` → `0.3s` / `1.2s` / `12s` / `2m 5s`. */
export function durShort(ms: number | null | undefined): string {
if (ms == null || !Number.isFinite(ms)) return "";
if (ms < 100) return "<0.1s";
if (ms < 1_000) return `${(Math.max(0, ms) / 1_000).toFixed(1)}s`;
if (ms < 60_000) {
const seconds = ms / 1_000;
return `${seconds < 10 ? seconds.toFixed(1) : String(Math.round(seconds))}s`;
}
const minutes = Math.floor(ms / 60_000);
const seconds = Math.round((ms % 60_000) / 1_000);
return seconds ? `${minutes}m ${seconds}s` : `${minutes}m`;
}
export function domainOf(url: unknown): string {
const raw = String(url ?? "");
try {
return new URL(raw).hostname.replace(/^www\./, "");
} catch {
return raw.replace(/^https?:\/\//, "").split("/")[0] ?? raw;
}
}
export function firstLine(value: unknown): string {
if (value == null) return "";
return String(value).split("\n")[0]?.trim() ?? "";
}
function str(value: unknown): string | undefined {
return typeof value === "string" && value !== "" ? value : undefined;
}
function num(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
/**
* The one "human intent" label of a row: path (`path:offset-limit`), pattern,
* query, domain, command, … falling back to the legacy `summary` and finally the
* humanized tool name (prototype `core.js:153-175`).
*/
export function fileTarget(tool: ToolView): string {
const input = tool.input ?? {};
const path = str(input.path);
const range = Array.isArray(tool.meta?.range) ? tool.meta?.range : null;
if (path && range && range.length >= 2) return `${path}:${range[0]}–${range[1]}`;
const offset = num(input.offset);
if (path && offset) {
const limit = num(input.limit);
const end = limit ? offset + limit - 1 : null;
return `${path}:${offset}${end ? `–${end}` : "+"}`;
}
const pattern = str(input.pattern);
if (pattern && path) return `“${pattern}” · ${path}`;
if (pattern) return `“${pattern}”`;
const query = str(input.query);
if (query) return `“${query}”`;
const claim = str(input.claim);
if (claim) return `“${claim}”`;
const url = str(input.url);
if (url) return domainOf(url);
if (path) return path;
const command = str(input.command);
if (command) return command.split("\n")[0] ?? command;
const target = str(input.target);
if (target) return target;
const taskId = str(input.taskId);
if (taskId) return taskId;
const batchId = str(input.batchId);
if (batchId) return batchId;
// §6 legacy DTO: no structured input → fall back to the old summary text.
if (tool.summary) return String(tool.summary);
return humanName(tool.name);
}
/** Best-effort clipboard write; silently no-ops in non-secure contexts / SSR. */
export function copyText(text: string | null | undefined): void {
if (!text) return;
try {
void navigator.clipboard?.writeText(String(text));
} catch {
/* clipboard unavailable (http, private mode) */
}
}
export function splitLines(text: string): string[] {
if (!text) return [];
const lines = text.replace(/\r\n?/g, "\n").split("\n");
if (lines.length && lines[lines.length - 1] === "") lines.pop();
return lines;
}
+9
View File
@@ -0,0 +1,9 @@
/**
* Tool call rendering — public surface.
*
* Exit contract for the message stream / other workstreams (do not change):
* `ToolRow`, `fromPi2Block`, and the shared view/context types.
*/
export { ToolRow } from "./tool-row";
export { fromPi2Block } from "./adapt";
export type { ToolView, ToolCtx, ToolAction, ToolState, FamilyId } from "./types";
+97
View File
@@ -0,0 +1,97 @@
/**
* Tool name → kind, and the family glyph table.
*
* Single mapping table, ported verbatim from the prototype `core.js:13-36`
* (design/CHAT-TOOL-RENDER.md §5). Anything unknown — including MCP
* `mcp__server__tool` names — falls back to `generic`.
*/
import { Code, FileDiff, FileText, FolderSearch, GitBranch, Globe, Image, ListTodo, Search, SquareTerminal, Terminal } from "lucide-react";
import type { FamilyId, ToolIconComponent } from "./types";
export const KIND_OF: Record<string, FamilyId> = {
bash: "shell",
exec: "shell",
shell: "shell",
read: "read",
edit: "write",
write: "write",
patch: "write",
apply_patch: "write",
edit_file: "write",
multi_edit: "write",
grep: "search",
search: "search",
find: "find",
glob: "find",
ls: "find",
list_dir: "find",
web_search: "web",
web_fetch: "web",
fetch_content: "web",
source_check: "web",
get_search_content: "web",
web: "web",
todo_write: "plan",
update_plan: "plan",
plan: "plan",
dispatch_subagents: "subagent",
list_subagents: "subagent",
read_subagent: "subagent",
poll_subagents: "subagent",
wait_subagents: "subagent",
list_batches: "subagent",
stop_subagents: "subagent",
vision: "vision",
image: "vision",
screenshot: "vision",
task: "task",
tasks: "task",
};
/** Family glyph (prototype `KIND_ICON`, `core.js:29-36`). */
export const KIND_ICON: Record<FamilyId, ToolIconComponent> = {
shell: SquareTerminal,
read: FileText,
write: FileDiff,
search: Search,
find: FolderSearch,
web: Globe,
plan: ListTodo,
subagent: GitBranch,
task: Terminal,
vision: Image,
generic: Code,
};
/** Every registered kind, in prototype order (useful for `Record<FamilyId, …>` exhaustiveness). */
export const FAMILY_IDS: FamilyId[] = [
"shell",
"task",
"read",
"write",
"search",
"find",
"web",
"vision",
"plan",
"subagent",
"generic",
];
/** `name` is trimmed + lowercased before lookup; unknown → `generic` (never throws). */
export function kindOf(name: unknown): FamilyId {
const key = String(name ?? "").trim().toLowerCase();
return KIND_OF[key] ?? "generic";
}
/** `mcp__slack__post` → `slack · post`; single segment → that segment; otherwise verbatim. */
export function humanName(name: unknown): string {
const raw = String(name ?? "tool");
if (raw.startsWith("mcp__")) {
const parts = raw.slice(5).split("__").filter(Boolean);
if (parts.length >= 2) return parts.join(" · ");
if (parts.length === 1) return parts[0] ?? raw;
}
return raw;
}
+36
View File
@@ -0,0 +1,36 @@
/**
* Kind → spec registry — all 11 registered kinds (prototype `core.js` registry).
*
* `web` / `vision` / `plan` / `subagent` are still owned by WS-E: until those families
* land they resolve to the `generic` spec (JSON input/result), which is the contract's
* safe fallback — never blank, never throws.
*/
import { readSpec, writeSpec } from "./families/file";
import { genericSpec } from "./families/generic";
import { findSpec, searchSpec } from "./families/search";
import { shellSpec, taskSpec } from "./families/shell";
import type { FamilyId, ToolSpec } from "./types";
export const REGISTRY: Record<FamilyId, ToolSpec> = {
shell: shellSpec,
task: taskSpec,
read: readSpec,
write: writeSpec,
search: searchSpec,
find: findSpec,
// TODO(WS-E): dedicated `web` spec — target from query/url, sources + preview body.
web: genericSpec,
// TODO(WS-E): dedicated `vision` spec — thumbnails + description body.
vision: genericSpec,
// TODO(WS-E): dedicated `plan` spec — todo list body + counts fact.
plan: genericSpec,
// TODO(WS-E): dedicated `subagent` spec — dispatch/inline modes + batch card body.
subagent: genericSpec,
generic: genericSpec,
};
/** Never throws: unknown ids fall back to the generic spec. */
export function specFor(kind: FamilyId | string | null | undefined): ToolSpec {
const key = String(kind ?? "") as FamilyId;
return REGISTRY[key] ?? REGISTRY.generic;
}
+63
View File
@@ -0,0 +1,63 @@
/**
* State normalization — one state, one meaning (design/CHAT-TOOL-RENDER.md §3).
*
* `pending`/`queued` is *not* "running": it renders with the completed tense and a
* static dot, never a spinner. Unknown or missing states degrade to `done`
* (CHG-09), never to a spinner.
*/
import type { ToolState } from "./types";
export const STATE_ALIAS: Record<string, ToolState> = {
running: "running",
spinning: "running",
in_progress: "running",
"in-progress": "running",
pending: "queued",
queued: "queued",
done: "done",
completed: "done",
success: "done",
ok: "done",
failed: "failed",
error: "failed",
err: "failed",
timeout: "timeout",
timed_out: "timeout",
interrupted: "interrupted",
aborted: "interrupted",
rejected: "rejected",
cancelled: "cancelled",
canceled: "cancelled",
stopped: "cancelled",
};
/** Canonical state → aria state word (`state.*` / `chat.meta.*` key). */
export const STATE_KEY: Record<ToolState, string> = {
running: "state.running",
queued: "state.queued",
done: "state.completed",
failed: "state.failed",
interrupted: "state.interrupted",
timeout: "chat.meta.timedOut",
rejected: "chat.meta.rejected",
cancelled: "state.stopped",
};
/** Accepts a `ToolView`-like object, a raw state string, or nothing. */
export function stateOf(tool?: { state?: string | null } | string | null): ToolState {
const raw = typeof tool === "string" ? tool : String(tool?.state ?? "");
return STATE_ALIAS[raw.trim().toLowerCase()] ?? "done";
}
export function isFailure(state: ToolState): boolean {
return state === "failed" || state === "timeout";
}
export function isRunning(state: ToolState): boolean {
return state === "running";
}
/** Interrupted / rejected / cancelled: no error line unless the tool gave a reason. */
export function isSoft(state: ToolState): boolean {
return state === "interrupted" || state === "rejected" || state === "cancelled";
}
+129
View File
@@ -0,0 +1,129 @@
/**
* Shared body slot + hover-only action strip.
*
* `ToolOps` is the one action area of a tool: it lives in the row (`.tool__row`) and
* is only visible on hover / `:focus-within` (`.tool__ops`, tool-core.css). A family
* with no actions renders nothing at all (`hidden`), so successful rows carry no
* button group at rest.
*
* `ToolBody` is the lazily populated `.tool__body`: the wrapper always exists so
* `aria-controls` resolves, but the family body is only rendered after the first
* expand, and a throwing body degrades to `.tool-empty` instead of breaking the
* message stream.
*/
import { Component, createElement, useState } from "react";
import type { ReactNode } from "react";
import { TriangleAlert } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { tr } from "./format";
import { kindOf } from "./kind";
import { specFor } from "./registry";
import type { ToolBodyProps, ToolSpec } from "./types";
/** Shared footer for bodies with a fold or a secondary action (`.tool__foot`). */
export function ToolFoot({ children }: { children: ReactNode }) {
return <div className="tool__foot">{children}</div>;
}
/**
* Shared error row (`.tool__error`): one line, `role=alert`; past 160 chars it becomes a
* focusable `role=button` that toggles the full text (prototype `core.js:355-374`).
*/
export function ToolError({ text }: { text: string }) {
const [full, setFull] = useState(false);
const long = text.length > 160;
const short = long ? `${text.slice(0, 157)}…` : text;
const toggle = () => setFull((value) => !value);
return (
<div
className="tool__error"
role={long ? "button" : "alert"}
tabIndex={long ? 0 : undefined}
onClick={long ? toggle : undefined}
onKeyDown={
long
? (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
toggle();
}
}
: undefined
}
>
<span className="tool__error-ico" aria-hidden="true">
<TriangleAlert size={12} strokeWidth={2} />
</span>
<span className="tool__error-text">{full ? text : short}</span>
</div>
);
}
/** Row actions — hover / focus-visible only. */
export function ToolOps({ tool, ctx, spec }: ToolBodyProps & { spec?: ToolSpec }) {
const { t } = useTranslation();
const resolved = spec ?? specFor(tool.kind ?? kindOf(tool.name));
const actions = (resolved.actions ? resolved.actions(tool, ctx) : []).filter(Boolean);
return (
<span className="tool__ops" hidden={actions.length === 0}>
{actions.map((action, index) => {
const ActionIcon = action.icon;
const label = t(action.labelKey);
return (
<Button
variant="ghost"
size="icon"
className={action.danger ? "tool__op is-danger" : "tool__op"}
aria-label={label}
title={label}
key={`${action.labelKey}-${index}`}
onClick={action.onAction}
>
<ActionIcon size={13} strokeWidth={1.75} aria-hidden />
</Button>
);
})}
</span>
);
}
class BodyBoundary extends Component<{ children: ReactNode }, { failed: string | null }> {
state: { failed: string | null } = { failed: null };
static getDerivedStateFromError(error: unknown): { failed: string } {
return { failed: String((error as Error)?.message ?? error) };
}
render(): ReactNode {
if (this.state.failed !== null) return <div className="tool-empty">{this.state.failed}</div>;
return this.props.children;
}
}
export interface ToolBodySlotProps extends ToolBodyProps {
spec: ToolSpec;
id: string;
hidden: boolean;
/** False until the row is opened once — keeps the body genuinely lazy. */
mounted: boolean;
}
export function ToolBody({ tool, ctx, spec, id, hidden, mounted }: ToolBodySlotProps) {
const Body = spec.Body;
return (
<div className="tool__body" id={id} hidden={hidden}>
{!mounted ? null : Body ? (
<BodyBoundary>
{createElement(Body, { tool, ctx })}
</BodyBoundary>
) : (
<div className="tool-empty">{tr("chat.meta.noOutput")}</div>
)}
</div>
);
}
+203
View File
@@ -0,0 +1,203 @@
/**
* One tool call = one row.
*
* Anatomy (design/CHAT-TOOL-RENDER.md §2): `.tool > .tool__row > .tool__head`
* with state glyph + family icon + verb + target + ≤3 facts + duration + caret, then
* an optional `.tool__error`, then the lazy `.tool__body`.
*
* Expansion is *local* state: opening one row re-renders that row only, never the
* message stream, and the body is mounted on the first expand and kept afterwards.
*/
import "@/styles/tool-core.css";
import { Fragment, useId, useState } from "react";
import { ArrowUp, Ban, ChevronDown, Circle, CircleCheck, CircleStop, Clock, TriangleAlert } from "lucide-react";
import { capFacts, defaultFacts, normalizeTool } from "./facts";
import { durShort, fileTarget, fmtNum, tr } from "./format";
import { KIND_ICON, humanName, kindOf } from "./kind";
import { specFor } from "./registry";
import { STATE_KEY, isFailure, isRunning, isSoft, stateOf } from "./state";
import { ToolBody, ToolError, ToolOps } from "./tool-body";
import { useElapsed } from "./use-elapsed";
import type { Fact, ToolIconComponent, ToolRowProps, ToolSpec, ToolState, ToolView } from "./types";
interface Glyph {
icon: ToolIconComponent;
className: string;
}
/** One glyph per canonical state; `running` renders the spinner instead (§3). */
const STATE_GLYPH: Record<Exclude<ToolState, "running">, Glyph> = {
done: { icon: CircleCheck, className: "" },
queued: { icon: Circle, className: "is-queued" },
failed: { icon: TriangleAlert, className: "is-err" },
timeout: { icon: Clock, className: "is-err" },
interrupted: { icon: ArrowUp, className: "is-warn" },
rejected: { icon: Ban, className: "is-warn" },
cancelled: { icon: CircleStop, className: "is-muted" },
};
function StateGlyph({ state }: { state: ToolState }) {
if (state === "running") {
return (
<span className="tool__state" aria-hidden="true">
<span className="spinner" />
</span>
);
}
const glyph = STATE_GLYPH[state];
const GlyphIcon = glyph.icon;
const className = glyph.className ? `tool__state-ico ${glyph.className}` : "tool__state-ico";
return (
<span className="tool__state" aria-hidden="true">
<GlyphIcon size={13} strokeWidth={2} className={className} />
</span>
);
}
function FactNode({ fact }: { fact: Fact }) {
if (fact.kind === "stat") {
return (
<span className="tool__stat">
<span className="is-add">{tr("chat.meta.added", { n: fmtNum(fact.added) })}</span>
<span className="is-del">{tr("chat.meta.removed", { n: fmtNum(fact.removed) })}</span>
</span>
);
}
if (fact.kind === "tag") return <span className="badge badge--outline">{fact.label}</span>;
return <span className="tool__fact">{fact.text}</span>;
}
/** `spec.verb` → `chat.tv.<base>.<running|done|failed>` (queued uses the done tense). */
function verbOf(tool: ToolView, spec: ToolSpec, state: ToolState): string {
const raw = typeof spec.verb === "function" ? spec.verb(tool) : spec.verb || kindOf(tool.name);
const bucket = state === "failed" ? "failed" : isRunning(state) ? "running" : "done";
return tr(`chat.tv.${raw}.${bucket}`);
}
/** Hard failures always explain themselves; soft states only with an explicit reason. */
function errorTextOf(tool: ToolView, spec: ToolSpec, state: ToolState): string | null {
if (!isFailure(state) && !isSoft(state)) return null;
const explicit = tool.result?.error || tool.result?.stderr || null;
const fromSpec = spec.error ? spec.error(tool) : null;
if (explicit) return fromSpec || String(explicit);
if (isFailure(state)) return fromSpec || tool.text?.lines?.[0] || tr(STATE_KEY[state]);
return null;
}
export function ToolRow({ tool: rawTool, ctx = {}, defaultOpen = false }: ToolRowProps) {
const tool = normalizeTool(rawTool);
const kind = tool.kind ?? kindOf(tool.name);
const spec = specFor(kind);
const state = stateOf(tool);
const running = isRunning(state);
const inline = spec.inline === true || tool.inline === true;
const [open, setOpen] = useState(Boolean(defaultOpen));
const [mounted, setMounted] = useState(Boolean(defaultOpen));
const bodyId = `tb-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
const verb = verbOf(tool, spec, state);
const target = String((spec.target ? spec.target(tool) : fileTarget(tool)) || "");
const facts = capFacts(spec.meta ? spec.meta(tool) : defaultFacts(tool));
const elapsed = useElapsed(tool.startedAt, running);
const duration =
running && elapsed
? elapsed
: tool.durationMs != null && tool.durationMs >= 1000
? durShort(tool.durationMs)
: "";
const stateLabel = tr(STATE_KEY[state]);
const factText = facts
.map((fact) => (fact.kind === "text" ? fact.text : fact.kind === "tag" ? fact.label : ""))
.filter(Boolean)
.join(" ");
const targetLabel = target || humanName(tool.name);
const baseLabel = tr("chat.meta.ariaTool", {
verb,
target: targetLabel,
state: stateLabel,
meta: factText,
})
.replace(/\s+/g, " ")
.trim();
const ariaLabel = open
? `${baseLabel} ${tr("chat.meta.ariaCollapse")}`.replace(/\s+/g, " ").trim()
: baseLabel;
const FamilyIcon = spec.icon ?? KIND_ICON[kind];
const errorText = errorTextOf(tool, spec, state);
const toggle = () => {
if (!open) setMounted(true);
setOpen((value) => !value);
};
const inner = (
<>
<StateGlyph state={state} />
<span className="tool__icon" aria-hidden="true">
<FamilyIcon size={13} strokeWidth={1.75} />
</span>
<span className={isFailure(state) ? "tool__verb is-err" : "tool__verb"} title={verb}>
{verb}
</span>
<span className="tool__target mono truncate" title={target}>
{target}
</span>
<span className="tool__meta tabular">
{facts.map((fact, index) => (
<Fragment key={index}>
{index ? (
<span className="tsep" aria-hidden="true">
·
</span>
) : null}
<FactNode fact={fact} />
</Fragment>
))}
</span>
<span className="tool__dur tabular">{duration}</span>
{inline ? null : (
<span className="tool__caret" aria-hidden="true">
<ChevronDown size={12} strokeWidth={2} />
</span>
)}
</>
);
return (
<div
className={`tool tool--${kind} tool--${state}${inline ? " is-inline" : ""}${open ? " is-open" : ""}`}
data-tool={tool.name || "tool"}
data-kind={kind}
data-state={state}
data-msg={tool.messageId}
>
<div className="tool__row">
{inline ? (
<div className="tool__head" aria-label={ariaLabel}>
{inner}
</div>
) : (
<button
className="tool__head"
type="button"
aria-expanded={open}
aria-controls={bodyId}
aria-label={ariaLabel}
onClick={toggle}
>
{inner}
</button>
)}
<ToolOps tool={tool} ctx={ctx} spec={spec} />
</div>
{errorText ? <ToolError text={errorText} /> : null}
{inline ? null : (
<ToolBody tool={tool} ctx={ctx} spec={spec} id={bodyId} hidden={!open} mounted={mounted} />
)}
</div>
);
}
+258
View File
@@ -0,0 +1,258 @@
/**
* Tool call rendering — shared types.
*
* Port of the prototype `web/js/tool-render/core.js` DTO (design/CHAT-TOOL-RENDER.md
* §2/§3/§6) to React. `FamilyId` covers all 11 registered kinds; the four kinds that
* WS-E owns (web/vision/plan/subagent) currently resolve to the `generic` spec.
*/
import type { ComponentType, ReactNode } from "react";
/** 11 registered kinds (prototype `core.js:13-36`). */
export type FamilyId =
| "shell"
| "task"
| "read"
| "write"
| "search"
| "find"
| "web"
| "vision"
| "plan"
| "subagent"
| "generic";
/** Canonical states after alias normalization (prototype `core.js:68-104`). */
export type ToolState =
| "queued"
| "running"
| "done"
| "failed"
| "timeout"
| "interrupted"
| "rejected"
| "cancelled";
/** Icon component shape — matches `@/components/icons` and Lucide's props. */
export type ToolIconComponent = ComponentType<{
size?: number | string;
strokeWidth?: number;
className?: string;
}>;
/** `tool.text` — the generic text block; legacy `details` lands here too. */
export interface ToolText {
lines?: string[] | null;
totalLines?: number | null;
truncated?: TruncatedInfo | boolean | null;
}
export interface TruncatedInfo {
headLines?: number | null;
tailLines?: number | null;
total?: number | null;
}
/** `tool.result` — at least `{ error? }`; shell/task add exit codes and streams. */
export interface ToolResult {
error?: string | null;
stderr?: string | null;
stdout?: string | null;
exitCode?: number | null;
truncated?: boolean | null;
added?: number | null;
removed?: number | null;
lines?: number | null;
taskId?: string | null;
/** Legacy: structured `output.details` (generic family renders it as JSON). */
details?: unknown;
[key: string]: unknown;
}
export interface ToolMeta {
exitCode?: number | null;
lines?: number | null;
bytes?: number | null;
matches?: number | null;
files?: number | null;
entries?: number | null;
images?: number | null;
added?: number | null;
removed?: number | null;
http?: number | string | null;
newFile?: boolean | null;
range?: number[] | null;
taskId?: string | null;
[key: string]: unknown;
}
export interface DiffLine {
/** `add` / `del` / anything else = `ctx`. */
t?: string | null;
old?: number | null;
new?: number | null;
text?: string | null;
}
export interface DiffHunk {
header?: string | null;
oldStart?: number | null;
newStart?: number | null;
lines?: DiffLine[] | null;
}
export interface DiffFile {
path?: string | null;
status?: "added" | "deleted" | "modified" | string | null;
added?: number | null;
removed?: number | null;
hunks?: DiffHunk[] | null;
}
export interface DiffPayload {
files: DiffFile[];
}
export interface SearchMatch {
path?: string | null;
line?: number | null;
col?: number | null;
text?: string | null;
}
export interface FsEntry {
name?: string | null;
type?: "file" | "dir" | "directory" | string | null;
size?: number | null;
}
export interface ToolSource {
title?: string | null;
url?: string | null;
domain?: string | null;
}
export interface ToolTodoItem {
content?: string | null;
status?: string | null;
activeForm?: string | null;
}
export interface BatchItemPayload {
ref?: string | null;
name?: string | null;
status?: string | null;
error?: string | null;
model?: string | null;
thinking?: string | null;
durationMs?: number | null;
}
export interface BatchSummaryPayload {
total?: number | null;
done?: number | null;
ok?: number | null;
failed?: number | null;
running?: number | null;
cancelled?: number | null;
}
export interface BatchPayload {
batchId?: string | null;
id?: string | null;
status?: string | null;
summary?: BatchSummaryPayload | null;
durationMs?: number | null;
items?: BatchItemPayload[] | null;
}
export interface ToolImage {
src: string;
alt?: string | null;
}
/**
* Normalized tool view — the single input of `ToolRow`.
* Built by `fromPi2Block()` (daemon DTO) or by the host (already-normalized data).
*/
export interface ToolView {
/** `toolCallId` — stable React key / `data-tool`. */
id: string;
/** Owning message id (prototype `.tool__body#tb-{msgId}`). */
messageId?: string;
name: string;
kind?: FamilyId;
/** Loose on purpose: `stateOf()` normalizes 20 aliases. */
state?: string;
startedAt?: number;
durationMs?: number;
agent?: string;
inline?: boolean;
input?: Record<string, unknown>;
/** Non-object `args` (legacy DTO) preserved for the generic family. */
raw?: unknown;
text?: ToolText;
result?: ToolResult;
/** Legacy: plain-text summary used as a target fallback. */
summary?: string;
/** Legacy: plain text, degraded to `text.lines` by `normalizeTool()`. */
details?: string;
diff?: DiffPayload;
matches?: SearchMatch[];
files?: string[];
entries?: FsEntry[];
sources?: ToolSource[];
todos?: ToolTodoItem[];
batch?: BatchPayload;
images?: ToolImage[];
meta?: ToolMeta;
}
/** One `.tool__meta` fact: plain text, `+N −M` stat or a badge tag. */
export type Fact =
| { kind: "text"; text: string }
| { kind: "stat"; added: number; removed: number }
| { kind: "tag"; label: string };
export interface ToolAction {
icon: ToolIconComponent;
labelKey: string;
onAction: () => void;
danger?: boolean;
}
export interface ToolCtx {
onOpenSubagent?: (name: string) => void;
onStopTask?: (taskId: string) => void;
onRetry?: (tool: ToolView) => void;
}
export interface ToolBodyProps {
tool: ToolView;
ctx: ToolCtx;
}
export interface ToolSpec {
id: FamilyId;
/** Family glyph; falls back to `KIND_ICON[id]`. */
icon?: ToolIconComponent;
/** No caret, no `aria-expanded`, no `.tool__body` (`<div>` head). */
inline?: boolean;
/** i18n base key, e.g. `"shell"` → `chat.tv.shell.done`, or a per-tool mapper. */
verb: string | ((tool: ToolView) => string);
target?: (tool: ToolView) => string;
meta?: (tool: ToolView) => Fact[];
error?: (tool: ToolView) => string | null;
actions?: (tool: ToolView, ctx: ToolCtx) => ToolAction[];
/**
* Lazy body render function. Called at most once per opened row and guarded by
* `try/catch`, so it must not call hooks itself — put hooks in the element it
* returns (`<ShellBody … />`).
*/
Body?: (props: ToolBodyProps) => ReactNode;
}
export interface ToolRowProps {
tool: ToolView;
ctx?: ToolCtx;
defaultOpen?: boolean;
}
@@ -0,0 +1,29 @@
/**
* Shared 1-second ticker for `.tool__dur`.
*
* The prototype runs one global `setInterval` that walks
* `.tool--running[data-started-at]` (core.js:406-420). In React the same thing is
* cheaper as a per-row hook: the interval exists only while the row is running and
* is cleaned up on unmount / state change, and rows that finish simply stop ticking.
*/
import { useEffect, useState } from "react";
import { durShort } from "./format";
/**
* Elapsed time since `startedAt`, re-rendering once per second.
* Returns `""` when the call is not running (or has no start time).
*/
export function useElapsed(startedAt: number | null | undefined, running: boolean): string {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
if (!running || !startedAt) return;
setNow(Date.now());
const timer = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(timer);
}, [running, startedAt]);
if (!running || !startedAt) return "";
return durShort(now - startedAt);
}
+165
View File
@@ -0,0 +1,165 @@
import type { WorkspaceInfo } from "@protocol/types";
import { useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { cn } from "@/lib/utils";
export interface WorkspaceSwitchProps {
/** Every workspace the daemon knows about (the menu lists all of them). */
workspaces: WorkspaceInfo[];
activeWorkspaceId?: string | null;
/** Session rows in the *active* workspace (live count beats the disk count). */
sessionCount: number;
/** Menu visibility — owned by the store so the page-wide Esc chain can close it. */
open: boolean;
onOpenChange: (open: boolean) => void;
onSelect: (workspaceId: string) => void;
className?: string;
}
function workspaceLabel(workspace: WorkspaceInfo): string {
return workspace.name?.trim() || workspace.cwd || workspace.workspaceId;
}
/**
* `.ws-switch` + `.ws-menu` (v0.1.1 Chat IA v3).
*
* The tree pane carries exactly ONE workspace, so the workspace picker is a
* button with a menu instead of a native `<select>`: it shows the name, the
* session count and a chevron that rotates while open, and each menu row is a
* `menuitemradio` with a check mark for the current workspace.
*/
export function WorkspaceSwitch({
workspaces,
activeWorkspaceId,
sessionCount,
open,
onOpenChange,
onSelect,
className,
}: WorkspaceSwitchProps) {
const { t } = useTranslation();
const rootRef = useRef<HTMLDivElement | null>(null);
const buttonRef = useRef<HTMLButtonElement | null>(null);
const menuRef = useRef<HTMLDivElement | null>(null);
const active = workspaces.find((workspace) => workspace.workspaceId === activeWorkspaceId);
const label = active ? workspaceLabel(active) : t("chat.noWorkspace");
// Click outside closes the menu. `composedPath()` (not `contains`) because a
// menu item selection re-renders and detaches the clicked node first.
useEffect(() => {
if (!open) return;
const onPointerDown = (event: Event) => {
const path = typeof event.composedPath === "function" ? event.composedPath() : [];
if (rootRef.current && path.includes(rootRef.current)) return;
onOpenChange(false);
};
document.addEventListener("pointerdown", onPointerDown, true);
return () => document.removeEventListener("pointerdown", onPointerDown, true);
}, [open, onOpenChange]);
// Opening moves focus into the menu (the checked row), like a real picker.
useEffect(() => {
if (!open) return;
const frame = requestAnimationFrame(() => {
const target =
menuRef.current?.querySelector<HTMLElement>('[aria-checked="true"]') ??
menuRef.current?.querySelector<HTMLElement>("[data-workspace-id]");
target?.focus({ preventScroll: true });
});
return () => cancelAnimationFrame(frame);
}, [open]);
function moveFocus(delta: 1 | -1 | "home" | "end") {
const items = Array.from(menuRef.current?.querySelectorAll<HTMLElement>("[data-workspace-id]") ?? []);
if (!items.length) return;
const current = items.indexOf(document.activeElement as HTMLElement);
let next = current;
if (delta === "home") next = 0;
else if (delta === "end") next = items.length - 1;
else if (delta === 1) next = current < 0 ? 0 : (current + 1) % items.length;
else next = current < 0 ? items.length - 1 : (current - 1 + items.length) % items.length;
items[next]?.focus({ preventScroll: true });
}
return (
<div className={cn("ws-switch-row", className)} ref={rootRef}>
<button
ref={buttonRef}
type="button"
className="ws-switch"
aria-haspopup="menu"
aria-expanded={open}
aria-label={t("chat.workspaceSwitchAria", { name: label })}
title={active?.cwd ?? label}
data-testid="ws-switch"
disabled={!workspaces.length}
onClick={() => onOpenChange(!open)}
>
<Icon name="folder" />
<span className="ws-switch__name truncate">{label}</span>
<span className="ws-switch__count tabular">{sessionCount}</span>
<span className="ws-switch__caret">
<Icon name="chevron-down" />
</span>
</button>
<div
ref={menuRef}
className="ws-menu"
role="menu"
aria-label={t("chat.workspaceSwitch")}
data-testid="ws-menu"
hidden={!open}
onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Home" || event.key === "End") {
event.preventDefault();
moveFocus(
event.key === "ArrowDown"
? 1
: event.key === "ArrowUp"
? -1
: event.key === "Home"
? "home"
: "end",
);
return;
}
if (event.key === "Escape" || event.key === "Tab") {
event.preventDefault();
event.stopPropagation();
onOpenChange(false);
requestAnimationFrame(() => buttonRef.current?.focus({ preventScroll: true }));
}
}}
>
<div className="ws-menu__label">{t("chat.workspaceSwitch")}</div>
{workspaces.map((workspace) => {
const checked = workspace.workspaceId === activeWorkspaceId;
const count = checked ? sessionCount : workspace.sessionCount;
return (
<button
key={workspace.workspaceId}
type="button"
role="menuitemradio"
aria-checked={checked}
className={cn("ws-menu__item", checked && "is-active")}
data-workspace-id={workspace.workspaceId}
title={workspace.cwd}
onClick={() => {
onOpenChange(false);
if (!checked) onSelect(workspace.workspaceId);
else requestAnimationFrame(() => buttonRef.current?.focus({ preventScroll: true }));
}}
>
<Icon name={checked ? "check" : "folder"} />
<span className="ws-menu__name truncate">{workspaceLabel(workspace)}</span>
<span className="ws-menu__count tabular">{count}</span>
</button>
);
})}
</div>
</div>
);
}
+45
View File
@@ -0,0 +1,45 @@
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
/**
* Brand story (left 40% at ≥900px): logo, title, one-line pitch, three
* capability bullets and the quiet "token stays on this device" badge.
*/
export function ConnectHero() {
const { t } = useTranslation();
const features = [
t("connect.featureOne", { defaultValue: "Workspaces and sessions in real time" }),
t("connect.featureTwo", { defaultValue: "Subagents and background tasks in one place" }),
t("connect.featureThree", { defaultValue: "Scoped read / steer / apply access" }),
];
return (
<section className="cn-hero" aria-labelledby="cn-hero-title">
<img className="cn-hero__logo" src="/pi2-nvim.png" alt="" />
<h1 className="cn-hero__title" id="cn-hero-title">
{t("connect.heroTitle", { defaultValue: "Connect your pi2" })}
</h1>
<p className="cn-hero__text">
{t("connect.heroText", {
defaultValue:
"One browser, one pi2 instance — continue your Neovim sessions from any device.",
})}
</p>
<ul className="cn-features">
{features.map((label) => (
<li className="cn-feature" key={label}>
<span className="cn-ico cn-feature__ico">
<Icon name="check" />
</span>
<span>{label}</span>
</li>
))}
</ul>
<div className="cn-secure">
<Icon name="plug" />
<span>{t("connect.secureBadge", { defaultValue: "Token stays on this device" })}</span>
</div>
</section>
);
}
+47 -14
View File
@@ -1,4 +1,4 @@
import { useId, useRef, useState, type RefObject } from "react";
import { useEffect, useId, useRef, useState, type RefObject } from "react";
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
@@ -21,6 +21,20 @@ export interface ManualConnectFormProps {
defaultDeviceName: string;
/** Prefill from `/connect?code=…` or the `/pair/$code` redirect. */
initialCode?: string;
/** Host/port prefill, e.g. the origin a pairing link was opened from. */
initialHost?: string;
initialPort?: string;
/**
* Port default derived from the loaded daemon info (the port this console
* was served from), never a hard-coded literal.
*/
defaultPort?: string;
/** Stable id of the collapsible container (the toggle's `aria-controls`). */
id?: string;
/** Collapsed by default; the parent owns the state so it can arbitrate the primary. */
expanded?: boolean;
/** True when the submit button is the page's single primary action. */
primary?: boolean;
}
/** Wrong/expired codes come back as 401 `E_UNAUTHORIZED`; the code rail is the useful message. */
@@ -33,11 +47,22 @@ export function pairErrorMessage(error: unknown): string {
}
/** Inline manual pairing form: host/port, 8-character pairing code, optional device name. */
export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName, initialCode }: ManualConnectFormProps) {
export function ManualConnectForm({
onConnect,
hostInputRef,
defaultDeviceName,
initialCode,
initialHost,
initialPort,
defaultPort = "",
id: formId,
expanded = true,
primary = false,
}: ManualConnectFormProps) {
const { t } = useTranslation();
const id = useId();
const [host, setHost] = useState("");
const [port, setPort] = useState("4321");
const [host, setHost] = useState(() => initialHost ?? "");
const [port, setPort] = useState(() => initialPort ?? defaultPort);
const [code, setCode] = useState(() => normalizePairCode(initialCode ?? ""));
const [deviceName, setDeviceName] = useState("");
const [hostError, setHostError] = useState<string | null>(null);
@@ -46,6 +71,19 @@ export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName,
const [formError, setFormError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const submitting = useRef(false);
const portEdited = useRef(false);
// Expanding the manual form moves focus to the host field (prototype focusHost).
useEffect(() => {
if (expanded) hostInputRef.current?.focus();
}, [expanded, hostInputRef]);
// The daemon port arrives with `/info`: an untouched field adopts it instead of
// keeping the endpoint-derived value the form mounted with.
useEffect(() => {
if (portEdited.current || initialPort) return;
setPort(defaultPort);
}, [defaultPort, initialPort]);
async function submit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
@@ -101,13 +139,7 @@ export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName,
}
return (
<section className="card cn-card">
<h2 className="cn-card__title">
<span className="cn-ico">
<Icon name="server" />
</span>
{t("connect.addTitle")}
</h2>
<div className="cn-manual" id={formId} hidden={!expanded} data-testid="connect-manual-panel">
<form className="cn-form" noValidate onSubmit={(event) => void submit(event)}>
<div className="cn-row">
<Field label={t("connect.host")} htmlFor={`${id}-host`} error={hostError}>
@@ -135,10 +167,11 @@ export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName,
type="text"
inputMode="numeric"
autoComplete="off"
placeholder="4321"
placeholder={defaultPort || undefined}
value={port}
onChange={(event) => {
setPort(event.target.value);
portEdited.current = true;
setPortError(null);
}}
/>
@@ -194,7 +227,7 @@ export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName,
<div className="cn-form__foot">
<Button
variant="primary"
variant={primary ? "primary" : "default"}
type="submit"
className="cn-submit"
disabled={busy}
@@ -205,6 +238,6 @@ export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName,
</Button>
</div>
</form>
</section>
</div>
);
}
+2 -2
View File
@@ -13,10 +13,10 @@ export interface StatusCardProps {
children: ReactNode;
}
/** `.card.status-card` with the design's icon + title + right-side meta. */
/** `.card.card--quiet.status-card` — 1px --border-subtle, --radius-lg, 18px padding. */
export function StatusCard({ title, icon, headExtra, className, children }: StatusCardProps) {
return (
<section className={className ? `card status-card ${className}` : "card status-card"}>
<section className={className ? `card card--quiet status-card ${className}` : "card card--quiet status-card"}>
<div className="card__head">
<div className="card__title">
<Icon name={icon} />
+97 -99
View File
@@ -6,7 +6,7 @@ import { ConfirmDialog } from "@/components/shared/confirm-dialog";
import { RelativeTime } from "@/components/shared/relative-time";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { KV, KVList } from "@/components/ui/kv";
import { KV } from "@/components/ui/kv";
import { toast } from "@/components/ui/toast";
import { drawQr } from "@/features/status/qr";
import type { PairCodeResponse } from "@/features/status/queries";
@@ -14,13 +14,6 @@ import type { ServerIdentity } from "@/features/status/server";
import { ErrorBlock, LoadingBlock, StatusCard } from "./card-parts";
function scopeTone(scope: string): "default" | "info" | "ok" {
if (scope === "read") return "default";
if (scope === "steer") return "info";
if (scope === "apply") return "ok";
return "default";
}
function CopyButton({ value, label }: { value: string; label: string }) {
const { t } = useTranslation();
@@ -48,12 +41,13 @@ function CopyButton({ value, label }: { value: string; label: string }) {
);
}
function AddressBlock({ label, value }: { label: string; value: string }) {
/** `.addr` — a labelled address that wraps instead of truncating. */
function Address({ label, value }: { label: string; value: string }) {
return (
<div className="addr-block">
<div className="addr-label muted">{label}</div>
<div className="addr-row">
<code className="mono truncate grow">{value}</code>
<div className="addr">
<div className="addr__label">{label}</div>
<div className="addr__row">
<code className="addr__value">{value}</code>
<CopyButton value={value} label={label} />
</div>
</div>
@@ -101,53 +95,11 @@ export function pairMinutesLeft(expiresAt: number | null | undefined, now = Date
}
/**
* The live pairing code block: code, expiry, pairing URL and the QR drawn from
* that URL. Failures are retried in place instead of showing `—`.
* Card 7 — two internal columns: addresses / mDNS / endpoint / device / scopes
* / pairing code / security notes on the left, the square QR with the pairing
* hint and the expiry on the right. Both actions are non-primary (the status
* page carries 0 primary buttons).
*/
function PairingBlock({
pairCode,
loading,
error,
fallbackUrl,
onRetry,
}: {
pairCode: PairCodeResponse | undefined;
loading: boolean;
error: string | null;
fallbackUrl: string;
onRetry: () => void;
}) {
const { t } = useTranslation();
const code = String(pairCode?.code ?? "").trim();
const url = String(pairCode?.url ?? "").trim() || (code ? `${fallbackUrl}/#pair=${code}` : "");
const minutes = pairMinutesLeft(pairCode?.expiresAt);
if (error) return <ErrorBlock message={error} onRetry={onRetry} />;
if (loading) return <LoadingBlock rows={3} />;
if (!code) return <ErrorBlock message={t("connect.pairFailed")} onRetry={onRetry} />;
return (
<div className="qr-wrap">
<QrCanvas seed={url || code} label={t("status.qrAria")} />
<div className="pair-code" data-testid="pairing-code">
{code}
</div>
{minutes != null ? <div className="pair-expiry muted">{t("status.securityExpiry", { n: minutes })}</div> : null}
{url ? (
<div className="addr-row" data-testid="pairing-url">
<code className="mono truncate grow">{url}</code>
<CopyButton value={url} label={t("connect.pairingLink")} />
</div>
) : null}
<div className="pair-hint muted">
<Icon name="phone" />
<span>{t("status.pairHint")}</span>
</div>
</div>
);
}
/** Card 7 — addresses, mDNS, pairing code/QR, scopes, last connection, actions. */
export function ConnectionCard({
server,
deviceName,
@@ -164,6 +116,9 @@ export function ConnectionCard({
}: ConnectionCardProps) {
const { t } = useTranslation();
const [confirmOpen, setConfirmOpen] = useState(false);
const code = String(pairCode?.code ?? "").trim();
const url = String(pairCode?.url ?? "").trim() || (code ? `${server.networkAddress}/#pair=${code}` : "");
const minutes = pairMinutesLeft(pairCode?.expiresAt);
return (
<StatusCard title={t("status.connection")} icon="qr">
@@ -173,56 +128,99 @@ export function ConnectionCard({
<LoadingBlock rows={6} />
) : (
<>
<div className="connect-grid">
<div className="connect-addr">
<AddressBlock label={t("status.local")} value={server.localAddress} />
<AddressBlock label={t("status.network")} value={server.networkAddress} />
<KV label={t("status.mdns")} mono>
{server.mdns}
</KV>
<KV label={t("connect.endpoint")} valueClassName="status-endpoint">
<span className="mono truncate">{server.endpoint}</span>
<CopyButton value={server.endpoint} label={t("connect.endpoint")} />
</KV>
<KV label={t("connect.device")}>{deviceName || "—"}</KV>
<KV label={t("status.tokenScopes")} valueClassName="status-kv-val">
{scopes.length ? (
<span className="status-scopes">
{scopes.map((scope) => (
<Badge key={scope} tone={scopeTone(scope)}>
{scope}
</Badge>
))}
</span>
<div className="conn-grid">
<div className="conn-left">
<Address label={t("status.local")} value={server.localAddress} />
<Address label={t("status.network")} value={server.networkAddress} />
<div className="kv-list conn-kv">
<KV label={t("status.mdns")} mono>
{server.mdns}
</KV>
<KV
label={t("connect.endpoint")}
className="status-kv--copy status-kv--wide"
valueClassName="status-kv__val"
>
<span className="mono status-kv__mono">{server.endpoint}</span>
<CopyButton value={server.endpoint} label={t("connect.endpoint")} />
</KV>
<KV label={t("connect.device")}>{deviceName || "—"}</KV>
<KV label={t("status.tokenScopes")} valueClassName="status-scopes__wrap">
{scopes.length ? (
<span className="status-scopes">
{scopes.map((scope) => (
<Badge key={scope} className="badge--outline">
{scope}
</Badge>
))}
</span>
) : (
<span className="faint">—</span>
)}
</KV>
<KV label={t("status.lastConnected")}>
<RelativeTime ts={connectedAt} />
</KV>
</div>
<div className="pair-code-block">
<div className="section-label">
{t("status.pairingTitle", { defaultValue: "Pairing" })}
</div>
{pairError ? (
<ErrorBlock message={pairError} onRetry={onRetryPair} />
) : pairLoading ? (
<LoadingBlock rows={1} />
) : (
<span className="muted">—</span>
<div className="pair-code mono" data-testid="pairing-code">
{code || "—"}
</div>
)}
</KV>
<KV label={t("status.lastConnected")}>
<RelativeTime ts={connectedAt} />
</KV>
</div>
<div className="security-note">
<div className="security-item">{t("status.securityLocal")}</div>
<div className="security-item">{t("status.securityToken")}</div>
{minutes != null ? (
<div className="security-item">
{t("status.securityExpiry", { n: minutes })}
</div>
) : null}
</div>
</div>
<PairingBlock
pairCode={pairCode}
loading={pairLoading}
error={pairError}
fallbackUrl={server.networkAddress}
onRetry={onRetryPair}
/>
<div className="conn-right">
<div className="qr-wrap">
{code ? <QrCanvas seed={url || code} label={t("status.qrAria")} /> : null}
<div className="pair-hint faint">
<Icon name="phone" />
<span>{t("status.pairHint")}</span>
</div>
{minutes != null ? (
<div className="pair-expiry faint">
{t("status.pairingExpires", {
n: minutes,
defaultValue: "Expires in {n} min",
})}
</div>
) : null}
</div>
</div>
</div>
<KVList className="security-note">
<div className="security-item">{t("status.securityLocal")}</div>
<div className="security-item">{t("status.securityToken")}</div>
</KVList>
<div className="status-conn-actions">
<a className="btn btn--sm" href="/connect?next=%2Fstatus">
<a className="btn btn--ghost btn--sm" href="/connect?next=%2Fstatus">
<Icon name="refresh" />
{t("connect.reconnect")}
</a>
<Button variant="danger" size="sm" onClick={() => setConfirmOpen(true)}>
<span className="spacer" />
<Button
variant="ghost"
size="sm"
className="btn--danger"
onClick={() => setConfirmOpen(true)}
>
<Icon name="plug" />
{t("connect.disconnect")}
</Button>
+12 -17
View File
@@ -16,13 +16,6 @@ const KIND_ICON: Record<string, IconName> = {
laptop: "laptop",
};
function scopeTone(scope: string): "default" | "info" | "ok" {
if (scope === "read") return "default";
if (scope === "steer") return "info";
if (scope === "apply") return "ok";
return "default";
}
export function deviceKey(device: DeviceEntry): string {
return device.id || device.deviceId || device.name;
}
@@ -76,26 +69,28 @@ export function DevicesCard({ devices, loading, error, onRetry, onRevoke }: Devi
</span>
<div className="grow device-main">
<div className="device-name truncate">{device.name}</div>
<div className="device-badges">
{scopes.map((scope) => (
<Badge key={scope} tone={scopeTone(scope)}>
{scope}
</Badge>
))}
<div className="device-meta">
<span className="status-scopes">
{scopes.map((scope) => (
<Badge key={scope} className="badge--outline">
{scope}
</Badge>
))}
</span>
</div>
</div>
<span className="device-time muted">
<span className="device-time faint">
<RelativeTime ts={deviceLastActive(device)} />
</span>
<Button
variant="ghost"
size="sm"
className="status-revoke"
size="icon"
className="status-icon-btn"
aria-label={`${t("status.revoke")} ${device.name}`}
title={t("status.revoke")}
onClick={() => setTarget(device)}
>
<Icon name="revoke" />
{t("status.revoke")}
</Button>
</div>
);
+25 -12
View File
@@ -15,23 +15,36 @@ export interface HealthCardProps {
onRetry: () => void;
}
/** Card 2 — per-check ✓/✗ list with an overall healthy/degraded badge. */
/** Card 2 — per-check ✓ / ! list with an overall "all passed" / "N failed" badge. */
export function HealthCard({ health, checkedAt, loading, error, onRetry }: HealthCardProps) {
const { t } = useTranslation();
const items = health?.items ?? [];
const allOk = items.length > 0 && items.every((item) => item.ok);
const failed = items.filter((item) => !item.ok).length;
return (
<StatusCard
title={t("status.health")}
icon="status"
headExtra={
<div className="status-health-meta">
{items.length ? (
<Badge tone={allOk ? "ok" : "warn"}>{t(allOk ? "status.healthy" : "state.degraded")}</Badge>
) : null}
{checkedAt ? <span className="card__sub"><RelativeTime ts={checkedAt} /></span> : null}
</div>
items.length ? (
<div className="status-health-meta">
<Badge tone={failed ? "err" : "ok"}>
{failed === 0
? t("status.healthOk", { defaultValue: "All checks passed" })
: failed === 1
? t("status.healthFail.one", { n: 1, defaultValue: "{n} check failed" })
: t("status.healthFail.other", {
n: failed,
defaultValue: "{n} checks failed",
})}
</Badge>
{checkedAt ? (
<span className="card__sub">
<RelativeTime ts={checkedAt} />
</span>
) : null}
</div>
) : null
}
>
{error ? (
@@ -49,11 +62,11 @@ export function HealthCard({ health, checkedAt, loading, error, onRetry }: Healt
title={t(item.ok ? "status.pass" : "status.fail")}
aria-label={t(item.ok ? "status.pass" : "status.fail")}
>
<Icon name={item.ok ? "check" : "x"} size={15} />
<Icon name={item.ok ? "check" : "alert"} size={14} />
</span>
<div className="grow">
<div className="health-name">{item.name}</div>
{item.detail ? <div className="health-detail muted">{item.detail}</div> : null}
<div className="grow health-main">
<div className="health-name truncate">{item.name}</div>
{item.detail ? <div className="health-detail faint truncate">{item.detail}</div> : null}
</div>
</div>
))}
+152
View File
@@ -0,0 +1,152 @@
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { RelativeTime } from "@/components/shared/relative-time";
import type { ResourcesResponse } from "@/lib/api";
import { formatUptime, type ServerIdentity } from "@/features/status/server";
import { ErrorBlock } from "./card-parts";
/** `.meter` — a 3px hairline under each tile value. */
function Meter({ value, label }: { value: number | null; label: string }) {
const pct = value == null ? 0 : Math.max(0, Math.min(100, Math.round(value)));
const tone = pct > 90 ? "is-err" : pct > 80 ? "is-warn" : "";
return (
<div
className="meter"
role="progressbar"
aria-label={`${label} ${pct}%`}
aria-valuenow={pct}
aria-valuemin={0}
aria-valuemax={100}
>
{/* The only inline value is geometry: the width of the 3px fill. */}
<i className={tone} style={{ width: `${pct}%` }} />
</div>
);
}
function percent(part: number | null): number | null {
return part == null || !Number.isFinite(part) ? null : Math.max(0, Math.min(100, part));
}
function readable(pct: number | null): string {
return pct == null ? "—" : `${Math.round(pct)}%`;
}
export interface MetricsBlockProps {
server: ServerIdentity;
resources: ResourcesResponse | undefined;
workspaceCount: number;
sessionCount: number;
instanceCount: number;
liveSessionCount: number;
error: string | null;
onRetry: () => void;
}
/**
* Metrics block: CPU / memory / disk / uptime tiles, then a single quiet line
* of counts (workspaces · sessions · instances · live sessions). The soft-limit
* banner of `/resources` rides along instead of a second progress list.
*/
export function MetricsBlock({
server,
resources,
workspaceCount,
sessionCount,
instanceCount,
liveSessionCount,
error,
onRetry,
}: MetricsBlockProps) {
const { t } = useTranslation();
const cpu = percent(server.cpu);
// `/info` may not carry a memory percentage; `/resources` gives RSS and the
// physical total, so derive the ratio instead of showing "—".
const mem =
server.mem != null
? percent(server.mem)
: resources && resources.physicalMemoryBytes > 0
? percent((resources.totalRssBytes / resources.physicalMemoryBytes) * 100)
: null;
const disk = percent(server.disk);
const live = t("status.live", { defaultValue: "Live" });
const counts: Array<[string, string]> = [
[t("status.workspaces"), String(workspaceCount)],
[t("status.sessions"), String(sessionCount)],
[t("status.instances"), String(instanceCount)],
[t("status.liveSessions"), String(liveSessionCount)],
];
return (
<div className="status-block">
<div className="section-label">{t("status.resources")}</div>
<div className="status-tiles">
<div className="tile status-tile" data-res="cpu">
<div className="tile__label">CPU</div>
<div className="tile__value">{readable(cpu)}</div>
<div className="tile__bar">
<Meter value={cpu} label="CPU" />
</div>
<div className="tile__meta">{live}</div>
</div>
<div className="tile status-tile" data-res="mem">
<div className="tile__label">{t("status.memory")}</div>
<div className="tile__value">{readable(mem)}</div>
<div className="tile__bar">
<Meter value={mem} label={t("status.memory")} />
</div>
<div className="tile__meta">{live}</div>
</div>
<div className="tile status-tile" data-res="disk">
<div className="tile__label">{t("status.disk")}</div>
<div className="tile__value">{readable(disk)}</div>
<div className="tile__bar">
<Meter value={disk} label={t("status.disk")} />
</div>
<div className="tile__meta">{live}</div>
</div>
<div className="tile status-tile" data-res="uptime">
<div className="tile__label">{t("status.uptime")}</div>
<div className="tile__value">{formatUptime(server.uptimeSec)}</div>
<div className="tile__meta">
<span>{t("status.lastHeartbeat")}</span>
<RelativeTime ts={server.lastHeartbeatAt} live={false} />
</div>
</div>
</div>
<div className="status-line status-counts">
{counts.map(([label, value], index) => (
<span className="status-count" key={label}>
{index ? (
<span className="sep" aria-hidden="true">
·
</span>
) : null}
<span className="status-count__label">{label}</span>
<b className="tabular">{value}</b>
</span>
))}
</div>
{error ? <ErrorBlock message={error} onRetry={onRetry} /> : null}
{resources?.warn ? (
<div className="status-warn" role="status">
<Icon name="alert" />
<div>
<span>{t("status.resourceWarn")}</span>
{resources.reason ? <span className="muted"> {resources.reason}</span> : null}
</div>
</div>
) : null}
</div>
);
}
+8 -5
View File
@@ -66,6 +66,7 @@ export function ModelsCard({ providers, loading, error, onRetry }: ModelsCardPro
<Icon name="search" />
<Input
type="search"
className="model-search__input"
placeholder={t("status.modelSearchPlaceholder")}
aria-label={t("status.modelSearchAria")}
value={query}
@@ -85,13 +86,13 @@ export function ModelsCard({ providers, loading, error, onRetry }: ModelsCardPro
<div className={expanded ? "model-group open" : "model-group"} key={group.provider}>
<button
type="button"
className="panel__head model-group__head"
className="model-group__head"
aria-expanded={expanded}
onClick={() => toggle(group.provider)}
>
<Icon name="chevron-right" />
<span className="model-provider">{group.provider}</span>
<span className="badge model-count">{group.models.length}</span>
<span className="model-provider truncate">{group.provider}</span>
<span className="model-count faint tabular">{group.models.length}</span>
<span className="spacer" />
</button>
{expanded ? (
@@ -99,11 +100,13 @@ export function ModelsCard({ providers, loading, error, onRetry }: ModelsCardPro
{group.models.map((model) => (
<div className="model-row" key={model.id}>
<span className="model-id mono truncate grow">{model.id}</span>
<span className="model-ctx muted">
<span className="model-ctx faint tabular">
{formatContextWindow(model.contextWindow)}
</span>
{model.reasoning ? (
<Badge tone="info">{t("status.reasoning")}</Badge>
<Badge className="badge--outline">
{t("status.reasoning")}
</Badge>
) : null}
{group.provider === "cliproxyapi" ? (
<Badge>{t("status.scoped")}</Badge>
-107
View File
@@ -1,107 +0,0 @@
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { Progress } from "@/components/ui/progress";
import { KV, KVList } from "@/components/ui/kv";
import type { ResourcesResponse } from "@/lib/api";
import type { ServerIdentity } from "@/features/status/server";
import { formatBytes } from "@/features/status/server";
import { ErrorBlock, LoadingBlock, StatusCard, StatusEmpty } from "./card-parts";
function toneFor(pct: number | null): "default" | "warn" | "err" {
if (pct == null) return "default";
if (pct > 90) return "err";
if (pct > 80) return "warn";
return "default";
}
function percent(part: number, total: number): number | null {
if (!Number.isFinite(part) || !Number.isFinite(total) || total <= 0) return null;
return Math.max(0, Math.min(100, Math.round((part / total) * 100)));
}
export interface ResourcesCardProps {
resources: ResourcesResponse | undefined;
server: ServerIdentity;
loading: boolean;
error: string | null;
onRetry: () => void;
workspaceCount: number;
sessionCount: number;
}
/** Card 3 — CPU/mem/disk rows, instance/session counts, soft-limit banner. */
export function ResourcesCard({
resources,
server,
loading,
error,
onRetry,
workspaceCount,
sessionCount,
}: ResourcesCardProps) {
const { t } = useTranslation();
const memPct =
resources != null ? percent(resources.totalRssBytes, resources.physicalMemoryBytes) : null;
const cpuPct = server.cpu;
const diskPct = server.disk;
const instanceCount = resources?.instances.length ?? 0;
const liveSessions = resources?.instances.reduce((total, item) => total + (item.sessions || 0), 0) ?? 0;
function row(key: string, label: string, pct: number | null, detail?: string) {
return (
<div className="res-row" data-res={key}>
<div className="res-top">
<span className="res-label">{label}</span>
<span className="spacer" />
<b className="res-val">{pct == null ? "—" : `${pct}%`}</b>
</div>
<Progress value={pct ?? 0} tone={toneFor(pct)} size="lg" label={label} />
{detail ? <div className="res-sub muted">{detail}</div> : null}
</div>
);
}
return (
<StatusCard title={t("status.resources")} icon="cpu">
{error ? (
<ErrorBlock message={error} onRetry={onRetry} />
) : loading ? (
<LoadingBlock rows={5} />
) : !resources ? (
<StatusEmpty icon="cpu" title={t("status.noResourcesTitle")} text={t("status.noResourcesText")} />
) : (
<>
<div className="res-list">
{row("cpu", "CPU", cpuPct)}
{row(
"mem",
t("status.memory"),
memPct,
`${formatBytes(resources.totalRssBytes)} / ${formatBytes(resources.physicalMemoryBytes)}`,
)}
{row("disk", t("status.disk"), diskPct)}
</div>
{resources.warn ? (
<div className="status-warn" role="status">
<Icon name="alert" />
<div>
<span>{t("status.resourceWarn")}</span>
{resources.reason ? <span className="muted"> {resources.reason}</span> : null}
</div>
</div>
) : null}
<KVList className="res-kv">
<KV label={t("status.workspaces")}>{workspaceCount}</KV>
<KV label={t("status.instances")}>{instanceCount}</KV>
<KV label={t("status.sessions")}>{sessionCount}</KV>
<KV label={t("status.liveSessions")}>{liveSessions}</KV>
</KVList>
</>
)}
</StatusCard>
);
}
+10 -10
View File
@@ -43,16 +43,16 @@ export function TasksCard({ tasks, loading = false, error = null, onRetry }: Tas
<div className="task-row" key={`${task.sessionId}-${task.id}`} title={task.command}>
<StatusDot status={TASK_DOT[task.status] ?? "idle"} />
<span className="task-cmd mono truncate grow">{task.command}</span>
<span className="task-dur muted">{formatDuration(task.durationMs)}</span>
<span className="task-exit">
{task.exitCode == null ? (
<span className="badge badge--info">{t("state.running")}</span>
) : (
<span className={task.exitCode === 0 ? "badge badge--ok" : "badge badge--err"}>
exit {task.exitCode}
</span>
)}
</span>
<span className="task-dur faint tabular">{formatDuration(task.durationMs)}</span>
{task.exitCode != null ? (
<span className={task.exitCode === 0 ? "task-state mono is-ok" : "task-state mono is-err"}>
exit {task.exitCode}
</span>
) : (
<span className={task.status === "running" ? "task-state is-run" : "task-state"}>
{t(`state.${task.status}`, { defaultValue: task.status })}
</span>
)}
</div>
))}
</div>
@@ -0,0 +1,76 @@
import { Link } from "@tanstack/react-router";
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { RelativeTime } from "@/components/shared/relative-time";
import { Empty } from "@/components/ui/empty";
import { StatusDot } from "@/components/ui/status-dot";
import { plural } from "@/lib/i18n";
import type { WorkspaceInfo } from "@/lib/protocol";
import { workspaceName, workspaceSessionCount } from "./commands";
import { instanceState } from "./workspace-card";
/** The design lists the newest 5 entries. */
export const ACTIVITY_LIMIT = 5;
export interface ActivityColumnProps {
workspaces: readonly WorkspaceInfo[];
}
/**
* "Recent activity" column (pi2-web-ui-design v0.1.1 §5.1): the newest
* `ACTIVITY_LIMIT` entries by `lastActiveAt`, dot + name + meta + relative
* time, each row linking into the chat UI.
*
* The prototype derives it from `MOCK.sessions`; the daemon exposes no
* cross-workspace session feed (only `/workspaces/<id>/sessions`), so the rows
* are workspace-level and the meta slot carries the session count instead of
* the owning workspace name.
*/
export function ActivityColumn({ workspaces }: ActivityColumnProps) {
const { t } = useTranslation();
const recent = [...workspaces]
.filter((workspace) => typeof workspace.lastActiveAt === "number" && Number.isFinite(workspace.lastActiveAt))
.sort((a, b) => (b.lastActiveAt ?? 0) - (a.lastActiveAt ?? 0))
.slice(0, ACTIVITY_LIMIT);
return (
<aside className="ws-activity" aria-label={t("workspaces.activity")} data-testid="workspaces-activity">
<div className="ws-activity__head">
<span className="section-label ws-activity__label">{t("workspaces.activity")}</span>
{recent.length > 0 ? <span className="ws-activity__count tabular">{recent.length}</span> : null}
</div>
{recent.length > 0 ? (
<div className="ws-activity__list">
{recent.map((workspace) => {
const state = instanceState(workspace);
return (
<Link
key={workspace.workspaceId}
to="/chat"
search={{ workspace: workspace.workspaceId }}
className="ws-activity__row"
data-workspace-id={workspace.workspaceId}
data-testid="workspace-activity-row"
>
<StatusDot status={state.status} title={t(state.labelKey)} />
<span className="ws-activity__main">
<span className="ws-activity__name">
{workspaceName(workspace, t("workspaces.unnamed"))}
</span>
<span className="ws-activity__ws">
{plural("workspaces.sessionCount", workspaceSessionCount(workspace))}
</span>
</span>
<RelativeTime ts={workspace.lastActiveAt} className="ws-activity__rel" />
</Link>
);
})}
</div>
) : (
<Empty icon={<Icon name="clock" size={22} />} title={t("workspaces.activityEmpty")} />
)}
</aside>
);
}
@@ -95,10 +95,14 @@ export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspac
id="new-workspace-name"
autoComplete="off"
placeholder={t("workspaces.defaultNamePlaceholder")}
aria-label={t("workspaces.displayName")}
value={name}
onChange={(event) => setName(event.target.value)}
/>
</Field>
<div className="ws-modal-example mono" aria-hidden="true">
~/Workspace/Misc/my-project
</div>
{formError ? (
<div className="ws-form__error" role="alert">
<Icon name="alert" />
@@ -0,0 +1,67 @@
import { Link } from "@tanstack/react-router";
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { StatusDot, type DotStatus } from "@/components/ui/status-dot";
import type { ServerIdentity } from "@/features/status/server";
import { plural } from "@/lib/i18n";
function serverDot(status: ServerIdentity["status"]): DotStatus {
if (status === "online") return "ok";
if (status === "degraded") return "attention";
return "exited";
}
export interface WorkspaceStatusLineProps {
server: ServerIdentity;
workspaceCount: number;
sessionCount: number;
runningCount: number;
}
/**
* Single-server identity as one quiet `.status-line` (pi2-web-ui-design v0.1.1
* §5.1): dot + name + hostname:port + workspace count + session/running
* summary + the status link. No card, no border — a surface-1 strip only.
*/
export function WorkspaceStatusLine({ server, workspaceCount, sessionCount, runningCount }: WorkspaceStatusLineProps) {
const { t } = useTranslation();
const hostPort = `${server.hostname}${server.port != null ? `:${server.port}` : ""}`;
const statusLabel = t(`state.${server.status}`);
return (
<section
className="status-line ws-status-line"
role="group"
aria-label={t("workspaces.contextAria")}
data-testid="workspaces-status-line"
>
<StatusDot status={serverDot(server.status)} className="dot--lg" title={statusLabel} />
<span className="status-line__name">{server.name}</span>
<span className="sep ws-sep-host" aria-hidden="true">
·
</span>
<span className="mono ws-status-host">{hostPort}</span>
<span className="sep ws-sep-count" aria-hidden="true">
·
</span>
<span className="tabular ws-status-count">{plural("workspaces.count", workspaceCount)}</span>
<span className="sep ws-sep-summary" aria-hidden="true">
·
</span>
<span className="tabular ws-status-summary">
{t("workspaces.serverSummary", { sessions: sessionCount, running: runningCount })}
</span>
<span className="spacer" />
<Link
to="/status"
className="ws-status-link"
title={t("workspaces.openStatus")}
aria-label={`${t("workspaces.openStatus")}: ${server.name}`}
>
<span>{t("workspaces.openStatus")}</span>
<Icon name="chevron-right" />
</Link>
</section>
);
}
@@ -0,0 +1,120 @@
import { Link } from "@tanstack/react-router";
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { RelativeTime } from "@/components/shared/relative-time";
import { Badge } from "@/components/ui/badge";
import { StatusDot, type DotStatus } from "@/components/ui/status-dot";
import { plural } from "@/lib/i18n";
import type { WorkspaceInfo } from "@/lib/protocol";
import { workspaceName, workspaceSessionCount } from "./commands";
import { isSecondary, reasonLabelKey } from "./visibility";
/**
* Aggregate row state → the card's "dot + text" pair (pi2-web-ui-design v0.1.1
* §5.1: state is never colour-only). `/api/v1/workspaces` carries no session
* list, so the workspace instance state is the whole aggregate here; the
* prototype derives it from `MOCK.sessions`.
*/
export function instanceState(workspace: WorkspaceInfo): { status: DotStatus; labelKey: string } {
if (!workspace.exists) return { status: "err", labelKey: "workspaces.instanceMissing" };
switch (workspace.instance?.status) {
case "ready":
return { status: "ok", labelKey: "workspaces.instanceReady" };
case "starting":
return { status: "busy", labelKey: "workspaces.instanceStarting" };
case "degraded":
return { status: "attention", labelKey: "workspaces.instanceDegraded" };
case "stopping":
return { status: "attention", labelKey: "workspaces.instanceStopping" };
case "unmanaged":
return { status: "idle", labelKey: "workspaces.instanceUnmanaged" };
case "stopped":
default:
return { status: "exited", labelKey: "workspaces.instanceStopped" };
}
}
export interface WorkspaceCardProps {
workspace: WorkspaceInfo;
}
/**
* One quiet card. The whole card is the link (native `<a>` from TanStack
* `Link`, so Enter/Space and focus-visible come for free) — there is no
* in-row primary "enter" button any more (§1.3).
*/
export function WorkspaceCard({ workspace }: WorkspaceCardProps) {
const { t } = useTranslation();
const name = workspaceName(workspace, t("workspaces.unnamed"));
const state = instanceState(workspace);
const stateLabel = t(state.labelKey);
const count = workspaceSessionCount(workspace);
const countLabel = plural("workspaces.sessionCount", count);
// Secondary rows stay dimmed and carry the policy reason; the page decides
// *whether* they render at all (see features/workspaces/visibility.ts).
const secondary = isSecondary(workspace);
const reasonKey = secondary ? reasonLabelKey(workspace) : null;
return (
<Link
to="/chat"
search={{ workspace: workspace.workspaceId }}
className={secondary ? "ws-card card--quiet ws-card--secondary" : "ws-card card--quiet"}
aria-label={`${name} — ${workspace.cwd} — ${countLabel}`}
title={workspace.cwd}
data-workspace-id={workspace.workspaceId}
data-testid="workspace-row"
data-visibility={secondary ? "secondary" : "default"}
data-visibility-reason={reasonKey ? (workspace.visibilityReason ?? "hidden") : undefined}
>
<div className="ws-card__head">
<span className="ico ws-card__icon" aria-hidden="true">
<Icon name="folder" />
</span>
<span className="ws-card__name truncate">{name}</span>
<span className="ws-card__state">
<StatusDot status={state.status} title={stateLabel} />
<span>{stateLabel}</span>
</span>
</div>
<div className="ws-card__cwd mono truncate">{workspace.cwd}</div>
<div className="ws-card__last">
{count > 0 ? (
<>
<span className="ws-card__last-label">{t("workspaces.lastSession")}</span>
<RelativeTime ts={workspace.lastActiveAt} className="ws-card__last-rel" />
</>
) : (
<span className="ws-card__last-title faint">{t("workspaces.noSessions")}</span>
)}
</div>
<div className="ws-card__foot">
{reasonKey ? (
<Badge className="ws-card__reason" data-testid="workspace-reason">
{t(reasonKey)}
</Badge>
) : null}
<span className="ws-card__count tabular">{countLabel}</span>
<span className="ws-card__open">
<span>{t("workspaces.openWorkspace")}</span>
<Icon name="chevron-right" />
</span>
</div>
</Link>
);
}
/** Loading placeholder sized like a card (same 14px padding, same gaps). */
export function WorkspacesSkeleton() {
const { t } = useTranslation();
return (
<div className="ws-skeleton" role="status" aria-label={t("common.loading")}>
<span className="skeleton skeleton--icon" />
<span className="skeleton skeleton--name" />
<span className="skeleton skeleton--cwd" />
<span className="skeleton skeleton--meta" />
</div>
);
}
@@ -1,139 +0,0 @@
import { Link } from "@tanstack/react-router";
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { RelativeTime } from "@/components/shared/relative-time";
import { Badge } from "@/components/ui/badge";
import { StatusDot, type DotStatus } from "@/components/ui/status-dot";
import type { ServerIdentity } from "@/features/status/server";
import { plural } from "@/lib/i18n";
import type { WorkspaceInfo } from "@/lib/protocol";
import { workspaceName } from "./commands";
import { isSecondary, reasonLabelKey } from "./visibility";
function serverDot(status: ServerIdentity["status"]): DotStatus {
if (status === "online") return "ok";
if (status === "degraded") return "attention";
return "exited";
}
export interface ServerContextBarProps {
server: ServerIdentity;
workspaceCount: number;
sessionCount: number;
}
/** Single-server identity bar: dot + name + hostname:port + counts + status link. */
export function ServerContextBar({ server, workspaceCount, sessionCount }: ServerContextBarProps) {
const { t } = useTranslation();
const hostPort = `${server.hostname}${server.port != null ? `:${server.port}` : ""}`;
return (
<section className="ws-context" aria-label={t("workspaces.contextAria")}>
<StatusDot status={serverDot(server.status)} title={t(`state.${server.status}`)} />
<span className="ws-context__name truncate">{server.name}</span>
<span className="ws-context__host mono muted">{hostPort}</span>
<Badge tone="info">{plural("workspaces.count", workspaceCount)}</Badge>
<Badge>{plural("workspaces.sessionCount", sessionCount)}</Badge>
<span className="spacer" />
<Link
to="/status"
className="ws-context__link"
title={t("workspaces.contextAria")}
aria-label={`${t("workspaces.contextAria")}: ${server.name} — ${t("workspaces.openStatus")}`}
>
{t("workspaces.openStatus")}
<Icon name="chevron-right" />
</Link>
</section>
);
}
function instanceDot(workspace: WorkspaceInfo): { status: DotStatus; labelKey: string } {
if (!workspace.exists) return { status: "err", labelKey: "workspaces.instanceMissing" };
const status = workspace.instance?.status;
switch (status) {
case "ready":
return { status: "ok", labelKey: "workspaces.instanceReady" };
case "starting":
return { status: "busy", labelKey: "workspaces.instanceStarting" };
case "degraded":
return { status: "attention", labelKey: "workspaces.instanceDegraded" };
case "stopping":
return { status: "attention", labelKey: "workspaces.instanceStopping" };
case "unmanaged":
return { status: "idle", labelKey: "workspaces.instanceUnmanaged" };
case "stopped":
default:
return { status: "exited", labelKey: "workspaces.instanceStopped" };
}
}
export interface WorkspaceRowProps {
workspace: WorkspaceInfo;
}
/** One flat workspace row (folder + name + full cwd + count + rel + dot + enter). */
export function WorkspaceRow({ workspace }: WorkspaceRowProps) {
const { t } = useTranslation();
const dot = instanceDot(workspace);
const count = Math.max(workspace.liveCount || 0, workspace.sessionCount || 0);
// Secondary rows are dimmed and carry the policy reason; the page decides
// *whether* they render (see features/workspaces/visibility.ts).
const secondary = isSecondary(workspace);
const reasonKey = secondary ? reasonLabelKey(workspace) : null;
return (
<div
className={secondary ? "list-row list-row--secondary" : "list-row"}
style={secondary ? { opacity: 0.55 } : undefined}
data-workspace-id={workspace.workspaceId}
data-testid="workspace-row"
data-visibility={secondary ? "secondary" : "default"}
data-visibility-reason={reasonKey ? workspace.visibilityReason ?? "hidden" : undefined}
>
<span className="ico list-row__icon">
<Icon name="folder" />
</span>
<div className="list-row__main">
<div className="list-row__name">{workspaceName(workspace, t("workspaces.unnamed"))}</div>
<div className="list-row__cwd mono muted truncate">{workspace.cwd}</div>
</div>
{reasonKey ? (
<Badge className="list-row__count" data-testid="workspace-reason">
{t(reasonKey)}
</Badge>
) : null}
<Badge tone="info" className="list-row__count">
{plural("workspaces.sessionCount", count)}
</Badge>
<RelativeTime ts={workspace.lastActiveAt} className="list-row__rel muted" />
<StatusDot status={dot.status} title={t(dot.labelKey)} />
<a
className="btn btn--sm btn--primary list-row__go"
data-testid="workspace-enter"
href={`/chat?workspace=${encodeURIComponent(workspace.workspaceId)}`}
>
{t("workspaces.enter")}
</a>
</div>
);
}
export function WorkspacesSkeleton() {
const { t } = useTranslation();
return (
<div className="list-row list-row--skeleton" role="status" aria-label={t("common.loading")}>
<span className="skeleton skeleton--icon" />
<div className="list-row__main">
<span className="skeleton skeleton--name" />
<span className="skeleton skeleton--cwd" />
</div>
<span className="skeleton skeleton--badge" />
<span className="skeleton skeleton--time" />
<span className="skeleton skeleton--dot" />
<span className="skeleton skeleton--go" />
</div>
);
}