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

+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);
}