Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(trace): draw turns as a Claude/Codex-style timeline
rubenluetke10-beep031eea7a291f
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsxindex ff6e9e8cf4..14cc72c813 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx@@ -16,8 +16,9 @@ it("replays persisted events through the new shared trace", () => {expect(screen.getByTestId("work-trace")).toBeTruthy();// A finished turn writes its work as a report; with no answer to read,// the report stands open.- expect(screen.getByRole("button", { name: /1 step/ }).getAttribute("aria-expanded")).toBe("true");- expect(screen.getByTestId("trace-report").textContent).toContain("Listed src.");+ expect(screen.getByRole("button", { name: /^Worked/ }).getAttribute("aria-expanded")).toBe("true");+ expect(screen.getByTestId("work-trace").textContent).toContain("Worked·Listed a folder");+ expect(screen.getByRole("button", { name: /^Explored/ }).parentElement?.textContent).toContain("Listsrc");});describe("the person's turn with files", () => {const SHOT = {diff --git a/jarvis/ui/web/frontend/src/components/agentchat/TraceReport.tsx b/jarvis/ui/web/frontend/src/components/agentchat/TraceReport.tsxdeleted file mode 100644index 909badb298..0000000000--- a/jarvis/ui/web/frontend/src/components/agentchat/TraceReport.tsx+++ /dev/null@@ -1,145 +0,0 @@-import { useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";-import { Check, ChevronRight, Copy } from "lucide-react";-import ReactMarkdown from "react-markdown";-import remarkGfm from "remark-gfm";-import { useT } from "@/i18n";-import { robustCopy } from "@/lib/clipboard";-import { cn } from "@/lib/utils";-import type { ToolBlock, TurnBlock, TurnStatus } from "./reduce";-import { narrateTurn, narrativeMarkdown, proseDuration, type NarrativeStep, type StepOutcome, type TraceNarrative } from "./traceNarrative";--/**- * A finished turn's work as a written report (see traceNarrative.ts for the- * wording rules): one overview paragraph, then every step as a numbered- * sentence on a quiet thread — the model's reason above it in its own words,- * what came of it below, the raw call one tap away. "Copy as text" puts the- * same report on the clipboard as Markdown, so it can be kept or shared.- */-/** The narrative of a turn's work, recomputed when the blocks or the language change. */-export function useTraceNarrative(blocks: TurnBlock[], status: TurnStatus, durationMs: number | null, model?: string): TraceNarrative {- const t = useT();- // The locale's own tag, read through the dictionary: plurals and lists- // follow the language the sentences are written in.- const lang = t("trace_report.locale");- return useMemo(- () => narrateTurn(blocks, { t, lang, status, durationMs, model }),- [blocks, t, lang, status, durationMs, model],- );-}--export function TraceReport({ narrative, renderDetails, className }: {- narrative: TraceNarrative;- /** The raw call (input, diff, output) for a step's "Details". */- renderDetails?: (block: ToolBlock) => ReactNode;- className?: string;-}) {- const t = useT();- let number = 0;- return (- <section data-testid="trace-report" aria-label={t("trace_report.title")} className={cn("min-w-0 pb-1 pt-0.5", className)}>- {narrative.overview ? <p data-trace-overview className="text-sm leading-6 text-foreground-secondary [overflow-wrap:anywhere]">- <Inline text={narrative.overview} />- </p> : null}- {narrative.steps.length ? <ol className="trace-report-steps mt-3">- {narrative.steps.map((step) => {- if (step.kind === "action") number += 1;- return <Step key={step.id} step={step} number={step.kind === "action" ? number : null} renderDetails={renderDetails} />;- })}- </ol> : null}- <CopyReport text={() => narrativeMarkdown(narrative, t)} />- </section>- );-}--const PROBLEM: ReadonlySet<StepOutcome> = new Set(["failed", "denied"]);--function Step({ step, number, renderDetails }: { step: NarrativeStep; number: number | null; renderDetails?: (block: ToolBlock) => ReactNode }) {- const problem = PROBLEM.has(step.outcome);- return (- <li className="trace-report-step" data-outcome={step.outcome} data-kind={step.kind}>- <span aria-hidden className="trace-report-marker">- {number !== null ? <span className="trace-report-num">{number}</span> : <span className="trace-dot" />}- </span>- <div className="min-w-0 flex-1 space-y-1">- {step.why.map((text, i) => <Why key={i} text={text} />)}- {step.sentence ? <p className="text-sm leading-6 text-foreground [overflow-wrap:anywhere]">- <Inline text={step.sentence} />- {step.durationMs !== null && step.durationMs > 0- ? <span className="ml-2 whitespace-nowrap text-xs tabular-nums text-muted-foreground">{proseDuration(step.durationMs)}</span> : null}- </p> : null}- {step.result ? <p data-trace-result className={cn("text-sm leading-6 [overflow-wrap:anywhere]", problem ? "text-destructive" : "text-muted-foreground")}>- <Inline text={step.result} />- </p> : null}- {step.block && renderDetails ? <StepDetails>{renderDetails(step.block)}</StepDetails> : null}- </div>- </li>- );-}--/** Markdown inside a sentence: inline code and emphasis, never HTML or blocks. */-function Inline({ text }: { text: string }) {- return <ReactMarkdown- allowedElements={["p", "code", "em", "strong"]}- unwrapDisallowed- components={{- p: ({ children }) => <>{children}</>,- code: ({ children }) => <code className="rounded bg-muted/70 px-1 py-0.5 font-mono text-[0.85em] text-foreground">{children}</code>,- }}- >{text}</ReactMarkdown>;-}--/** The model's own words before a step — read in full, folded when long. */-function Why({ text }: { text: string }) {- const t = useT();- const ref = useRef<HTMLDivElement>(null);- const [open, setOpen] = useState(false);- const [overflows, setOverflows] = useState(false);- useLayoutEffect(() => {- const el = ref.current;- if (el && !open) setOverflows(el.scrollHeight > el.clientHeight + 1);- }, [text, open]);- return <div data-trace-why>- <div ref={ref} className={cn(- "prose prose-sm max-w-none text-sm leading-6 text-foreground-secondary dark:prose-invert [overflow-wrap:anywhere]",- "prose-p:my-1 prose-p:text-foreground-secondary prose-li:text-foreground-secondary prose-strong:text-foreground prose-pre:overflow-auto",- "[&>:first-child]:mt-0 [&>:last-child]:mb-0",- !open && "max-h-48 overflow-hidden",- !open && overflows && "trace-report-fade",- )}>- <ReactMarkdown remarkPlugins={[remarkGfm]}>{text}</ReactMarkdown>- </div>- {overflows || open ? <button type="button" onClick={() => setOpen(!open)}- className="mt-0.5 rounded-sm text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">- {t(open ? "trace_report.show_less" : "trace_report.show_more")}- </button> : null}- </div>;-}--function StepDetails({ children }: { children: ReactNode }) {- const t = useT();- const [open, setOpen] = useState(false);- return <div>- <button type="button" aria-expanded={open} onClick={() => setOpen(!open)}- className="group/details inline-flex items-center gap-1 rounded-sm text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">- <ChevronRight aria-hidden className={cn("h-3 w-3 transition-transform", open && "rotate-90")} />- {t("trace_report.details")}- </button>- {open ? <div className="min-w-0 pt-1">{children}</div> : null}- </div>;-}--function CopyReport({ text }: { text: () => string }) {- const t = useT();- const [state, setState] = useState<"idle" | "copied" | "failed">("idle");- const copy = async () => {- const ok = await robustCopy(text());- setState(ok ? "copied" : "failed");- window.setTimeout(() => setState("idle"), 2000);- };- const Icon = state === "copied" ? Check : Copy;- return <button type="button" onClick={() => void copy()}- className="mt-3 inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">- <Icon aria-hidden className="h-3.5 w-3.5" />- <span aria-live="polite">{t(state === "copied" ? "trace_report.copied" : state === "failed" ? "trace_report.copy_failed" : "trace_report.copy")}</span>- </button>;-}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/TraceReport.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/TraceTimeline.test.tsxsimilarity index 50%rename from jarvis/ui/web/frontend/src/components/agentchat/TraceReport.test.tsxrename to jarvis/ui/web/frontend/src/components/agentchat/TraceTimeline.test.tsxindex 78fa767b6d..af9b46cbd0 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/TraceReport.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/TraceTimeline.test.tsx@@ -9,7 +9,7 @@ const step = (over: Partial<ThinkingStep>): ThinkingStep => ({id: "s", kind: "tool", labelKey: "thinking.step_tool", status: "done", startedTs: 1000, ...over,});-it("reopens a stored voice turn as a written report, not as rows", () => {+it("reopens a stored voice turn as a Claude/Codex-style timeline", () => {const steps: ThinkingStep[] = [step({ id: "b", kind: "brain", labelKey: "thinking.step_brain", detail: "grok · grok-4.3", durationMs: 900 }),step({ id: "p", kind: "thought", labelKey: "thinking.step_thought", detail: "I'll check the **wiki** first." }),@@ -17,30 +17,28 @@ it("reopens a stored voice turn as a written report, not as rows", () => {step({ id: "x", detail: "run-app-action", status: "error", denied: true, error: "blacklist: <tool-declared-block>" }),];render(<VoiceWorkTrace steps={steps} durationMs={2400} />);- // Folded: the toggle names the time, the step count and the trouble.- const toggle = screen.getByRole("button", { name: /^Thought for 2\.4s.*2 steps.*1 not done/ });- expect(screen.queryByTestId("trace-report")).toBeNull();- // The turn is not called failed because one step was refused.+ // Folded to one line that says what happened.+ const toggle = screen.getByRole("button", { name: /^Worked for 2\.4s.*Used the wiki.*1 failed/ });+ // The turn is not called failed because one call was refused.expect(screen.getByRole("status").textContent).toContain("Done");fireEvent.click(toggle);- const report = screen.getByTestId("trace-report");- expect(within(report).getByText(/This answer took 2\.4 s and 2 steps\./).textContent).toContain("Model: grok · grok-4.3.");- const [wiki, refused] = Array.from(report.querySelectorAll<HTMLElement>("li[data-kind='action']"));- // The reason in the model's words, rendered as Markdown, sits above its step.- expect(within(wiki).getByText("wiki").tagName).toBe("STRONG");- expect(wiki.textContent).toContain("Looked up “Urlaub 2026” in the wiki.");- expect(wiki.textContent).toContain("49 ms");- expect(wiki.textContent).toContain("It returned one entry in pages.");- expect(refused.getAttribute("data-outcome")).toBe("denied");- expect(refused.textContent).toContain("It did not run: a safety rule blocks this action.");- // The raw call is one tap further.- fireEvent.click(within(wiki).getByRole("button", { name: "Details" }));+ // The model's own words read as prose, Markdown and all.+ const thought = document.querySelector<HTMLElement>("[data-trace-entry='thought']")!;+ expect(within(thought).getByText("wiki").tagName).toBe("STRONG");+ // Each call is one line, with what came of it underneath.+ const [wiki, refused] = Array.from(document.querySelectorAll<HTMLElement>("[data-trace-entry='tool']"));+ expect(wiki.textContent).toContain("Searched the wikiUrlaub 2026");+ expect(wiki.textContent).toContain("49ms");+ expect(wiki.textContent).toContain("1 result");+ expect(refused.textContent).toContain("Blocked: a safety rule blocks this action");+ // The raw call is one tap away.+ fireEvent.click(within(wiki).getByRole("button"));expect(within(wiki).getByText("Input")).toBeTruthy();- expect(screen.getByRole("button", { name: "Copy as text" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Copy" })).toBeTruthy();});-it("shows no report for a turn with nothing to tell", () => {+it("draws nothing for a turn whose only step is the brain call", () => {render(<VoiceWorkTrace steps={[step({ id: "b", kind: "brain", labelKey: "thinking.step_brain", detail: "m" })]} durationMs={0} />);expect(screen.queryByTestId("conversation-work-fold")).toBeNull();});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/TraceTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentchat/TraceTimeline.tsxnew file mode 100644index 0000000000..2b32dbecf4--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/TraceTimeline.tsx@@ -0,0 +1,222 @@+import { useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { Check, ChevronRight, CircleAlert, Copy, FilePenLine, FilePlus2, FolderSearch, ShieldX, Terminal } from "lucide-react";+import ReactMarkdown from "react-markdown";+import remarkGfm from "remark-gfm";+import { useT } from "@/i18n";+import { robustCopy } from "@/lib/clipboard";+import { cn } from "@/lib/utils";+import type { ToolBlock, TurnBlock, TurnStatus } from "./reduce";+import { ToolChoiceIcon } from "./ToolChoiceChips";+import { toolIdentityStyle } from "./toolIdentity";+import { traceToolIdentity } from "./traceActivity";+import {+ buildTimeline, plural, tr, traceDuration,+ type CommandEntry, type EditEntry, type EntryStatus, type ExploreEntry, type ThoughtEntry, type Timeline, type TimelineEntry, type ToolEntry,+} from "./traceEntries";++/**+ * The renderer of a turn's timeline (model: traceEntries.ts), drawn the+ * way Claude and Codex draw their traces: the model's words as prose, each+ * call one quiet line on the rail with what came of it underneath — the+ * first lines a command printed, the files an exploration read, the size of+ * an edit — and the raw call one tap away. Live pieces (a running call, an+ * approval, a question card, a streaming thought, a reply) are drawn by the+ * caller, so the live turn and its finished record read as one timeline.+ */++/** One item on a rail; `rail: false` breaks the thread (replies, question cards). */+export type RailItem = { key: string; node: ReactNode; rail: boolean };++export interface TimelineRenderers {+ /** A live piece: running call, approval, question card, streaming thought, reply. */+ renderLive: (block: TurnBlock) => ReactNode;+ /** Whether a live piece hangs on the thread (replies and question cards do not). */+ liveOnRail: (block: TurnBlock) => boolean;+ /** The raw call — input, diff, output — under a line's disclosure. */+ renderDetails: (block: ToolBlock) => ReactNode;+}++/** The timeline of a turn, recomputed when its blocks, state or language change. */+export function useTimeline(blocks: TurnBlock[], status: TurnStatus, live: boolean): Timeline {+ const t = useT();+ // The locale's own tag, read through the dictionary: plurals and lists+ // follow the language the lines are written in.+ const lang = t("trace_report.locale");+ return useMemo(() => buildTimeline(blocks, { t, lang, status, live }), [blocks, t, lang, status, live]);+}++export function timelineItems(timeline: Timeline, renderers: TimelineRenderers): RailItem[] {+ return timeline.entries.map((entry): RailItem => {+ if (entry.kind === "live") {+ return { key: entry.id, rail: renderers.liveOnRail(entry.block), node: renderers.renderLive(entry.block) };+ }+ return { key: entry.id, rail: true, node: <EntryView entry={entry} renderDetails={renderers.renderDetails} /> };+ });+}++function EntryView({ entry, renderDetails }: { entry: Exclude<TimelineEntry, { kind: "live" }>; renderDetails: (block: ToolBlock) => ReactNode }) {+ switch (entry.kind) {+ case "thought": return <ThoughtView entry={entry} />;+ case "explore": return <ExploreView entry={entry} renderDetails={renderDetails} />;+ case "command": return <CommandView entry={entry} renderDetails={renderDetails} />;+ case "edit": return <EditView entry={entry} renderDetails={renderDetails} />;+ case "tool": return <ToolView entry={entry} renderDetails={renderDetails} />;+ }+}++const rowButton = "group/trace flex w-full min-w-0 items-start gap-3 rounded-md py-1 text-left text-sm leading-6 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring enabled:hover:text-foreground disabled:cursor-default";+const glyph = "h-3.5 w-3.5 shrink-0";++/** One line on the rail: glyph, words, time; what came of it underneath; the raw call on tap. */+function Line({ icon, label, trailing, below, details, problem = false, testId }: {+ icon: ReactNode; label: ReactNode; trailing?: ReactNode; below?: ReactNode; details?: ReactNode; problem?: boolean; testId: string;+}) {+ const [open, setOpen] = useState(false);+ return <div className={cn("min-w-0", problem ? "text-destructive" : "text-muted-foreground")} data-trace-entry={testId}>+ <button type="button" className={rowButton} disabled={!details} aria-expanded={details ? open : undefined} onClick={() => setOpen(!open)}>+ <span aria-hidden className="trace-node">{icon}</span>+ <span className="flex min-w-0 flex-1 items-baseline gap-2">{label}</span>+ {trailing ? <span className="shrink-0 text-xs leading-6 tabular-nums text-muted-foreground">{trailing}</span> : null}+ {details ? <ChevronRight aria-hidden className={cn("mt-[5px] h-3.5 w-3.5 shrink-0 opacity-0 transition group-hover/trace:opacity-70 group-focus-visible/trace:opacity-70", open && "rotate-90 opacity-70")} /> : null}+ </button>+ {below ? <div className="min-w-0 pb-1 pl-7">{below}</div> : null}+ {details && open ? <div className="min-w-0 pb-1.5 pl-7">{details}</div> : null}+ </div>;+}++/** The verb of a line, then its object in the mono face. */+function Words({ verb, object, problem = false }: { verb: string; object?: string; problem?: boolean }) {+ return <>+ <span className={cn("shrink-0", problem ? "text-destructive" : "text-foreground-secondary")}>{verb}</span>+ {object ? <span className="min-w-0 truncate font-mono text-[12.5px] text-muted-foreground" title={object}>{object}</span> : null}+ </>;+}++function problemGlyph(status: EntryStatus): ReactNode | null {+ if (status === "blocked" || status === "declined") return <ShieldX className={glyph} />;+ if (status === "failed" || status === "interrupted") return <CircleAlert className={glyph} />;+ return null;+}++/** "Failed: …", "Blocked: a safety rule …" — said once, under the line. */+function Problem({ status, reason }: { status: EntryStatus; reason: string }) {+ const t = useT();+ if (status === "done") return null;+ return <p className={cn("text-xs leading-5 [overflow-wrap:anywhere]", status === "failed" || status === "blocked" ? "text-destructive" : "text-muted-foreground")}>+ {tr(t, `status.${status}`)}{reason ? `: ${reason}` : ""}+ </p>;+}++function duration(ms: number | null | undefined): string | undefined {+ return ms !== null && ms !== undefined && ms > 0 ? traceDuration(ms) : undefined;+}++function ThoughtView({ entry }: { entry: ThoughtEntry }) {+ const t = useT();+ const ref = useRef<HTMLDivElement>(null);+ const [open, setOpen] = useState(false);+ const [overflows, setOverflows] = useState(false);+ useLayoutEffect(() => {+ const el = ref.current;+ if (el && !open) setOverflows(el.scrollHeight > el.clientHeight + 1);+ }, [entry.text, open]);+ return <div className="flex min-w-0 gap-3 py-1" data-trace-entry="thought">+ <span aria-hidden className="trace-node"><span className="trace-dot" /></span>+ <div className="min-w-0 flex-1">+ <div ref={ref} className={cn(+ "prose prose-sm max-w-none text-sm leading-6 text-foreground-secondary dark:prose-invert [overflow-wrap:anywhere]",+ "prose-p:my-1 prose-p:text-foreground-secondary prose-li:text-foreground-secondary prose-strong:text-foreground prose-pre:overflow-auto",+ "[&>:first-child]:mt-0 [&>:last-child]:mb-0",+ !open && "max-h-36 overflow-hidden",+ !open && overflows && "trace-thought-fade",+ )}>+ <ReactMarkdown remarkPlugins={[remarkGfm]}>{entry.text}</ReactMarkdown>+ </div>+ {overflows || open ? <button type="button" onClick={() => setOpen(!open)}+ className="mt-0.5 rounded-sm text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {t(open ? "trace_report.show_less" : "trace_report.show_more")}+ </button> : null}+ </div>+ </div>;+}++function ExploreView({ entry, renderDetails }: { entry: ExploreEntry; renderDetails: (block: ToolBlock) => ReactNode }) {+ const t = useT();+ return <Line testId="explore" icon={<FolderSearch className={glyph} />}+ label={<Words verb={tr(t, "entry.explored")} />}+ trailing={duration(entry.durationMs)}+ below={<ul className="space-y-0.5 text-xs leading-5">+ {entry.lines.map((line, i) => <li key={i} className="flex min-w-0 gap-2">+ <span className="shrink-0 text-muted-foreground">{tr(t, `entry.${line.verb}`)}</span>+ <span className="min-w-0 truncate font-mono text-foreground-secondary" title={line.targets.join(", ")}>{line.targets.join(", ")}</span>+ </li>)}+ </ul>}+ details={<div className="space-y-3">{entry.blocks.map((block) => <div key={block.callId}>{renderDetails(block)}</div>)}</div>} />;+}++function CommandView({ entry, renderDetails }: { entry: CommandEntry; renderDetails: (block: ToolBlock) => ReactNode }) {+ const t = useT();+ const problem = entry.status === "failed" || entry.status === "blocked";+ return <Line testId="command" problem={problem}+ icon={problemGlyph(entry.status) ?? <Terminal className={glyph} />}+ label={<Words verb={tr(t, "entry.ran")} object={entry.command} problem={problem} />}+ trailing={duration(entry.block.durationMs)}+ below={entry.output || entry.status !== "done" ? <>+ {entry.output ? <div data-trace-output className="min-w-0 font-mono text-xs leading-5 text-muted-foreground">+ {entry.output.lines.map((line, i) => <div key={i} className="truncate whitespace-pre" title={line}>{line}</div>)}+ {entry.output.more ? <div className="text-muted-foreground/70">{tr(t, `entry.more_${plural("en", entry.output.more)}`, { count: entry.output.more })}</div> : null}+ </div> : null}+ <Problem status={entry.status} reason={entry.reason} />+ </> : undefined}+ details={renderDetails(entry.block)} />;+}++function EditView({ entry, renderDetails }: { entry: EditEntry; renderDetails: (block: ToolBlock) => ReactNode }) {+ const t = useT();+ const problem = entry.status === "failed" || entry.status === "blocked";+ return <Line testId="edit" problem={problem}+ icon={problemGlyph(entry.status) ?? (entry.verb === "write" ? <FilePlus2 className={glyph} /> : <FilePenLine className={glyph} />)}+ label={<>+ <Words verb={tr(t, entry.verb === "edit" ? "entry.edited" : "entry.created")} object={entry.path} problem={problem} />+ {entry.added || entry.removed ? <span className="shrink-0 font-mono text-xs tabular-nums">+ <span className="diff-count-add">+{entry.added}</span>{" "}<span className="diff-count-del">−{entry.removed}</span>+ </span> : null}+ </>}+ trailing={duration(entry.block.durationMs)}+ below={entry.status !== "done" ? <Problem status={entry.status} reason={entry.reason} /> : undefined}+ details={renderDetails(entry.block)} />;+}++function ToolView({ entry, renderDetails }: { entry: ToolEntry; renderDetails: (block: ToolBlock) => ReactNode }) {+ const view = traceToolIdentity(entry.block);+ const problem = entry.status === "failed" || entry.status === "blocked";+ const Glyph = view.identity.Glyph;+ const icon = problemGlyph(entry.status) ?? (view.identity.logo+ ? <span className="tool-identity inline-flex" style={toolIdentityStyle(view.row)} data-trace-brand={view.identity.key}><ToolChoiceIcon row={view.row} size={14} /></span>+ : <Glyph className={glyph} />);+ return <Line testId="tool" problem={problem} icon={icon}+ label={<Words verb={entry.label} object={entry.detail} problem={problem} />}+ trailing={duration(entry.block.durationMs)}+ below={entry.result || entry.status !== "done" ? <>+ {entry.result ? <p data-trace-result className="truncate text-xs leading-5 text-muted-foreground" title={entry.result}>{entry.result}</p> : null}+ <Problem status={entry.status} reason={entry.reason} />+ </> : undefined}+ details={renderDetails(entry.block)} />;+}++/** "Copy" — the timeline as Markdown on the clipboard. */+export function CopyTimeline({ text }: { text: () => string }) {+ const t = useT();+ const [state, setState] = useState<"idle" | "copied" | "failed">("idle");+ const copy = async () => {+ const ok = await robustCopy(text());+ setState(ok ? "copied" : "failed");+ window.setTimeout(() => setState("idle"), 2000);+ };+ const Icon = state === "copied" ? Check : Copy;+ return <button type="button" onClick={() => void copy()}+ className="ml-7 mt-1 inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <Icon aria-hidden className="h-3.5 w-3.5" />+ <span aria-live="polite">{t(state === "copied" ? "trace_report.copied" : state === "failed" ? "trace_report.copy_failed" : "trace_report.copy")}</span>+ </button>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/VoiceWorkTrace.tsx b/jarvis/ui/web/frontend/src/components/agentchat/VoiceWorkTrace.tsxindex 2d0ac34136..0024ed1c93 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/VoiceWorkTrace.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/VoiceWorkTrace.tsx@@ -1,6 +1,6 @@import { useMemo } from "react";import { useT } from "@/i18n";-import { traceModel, type ThinkingStep } from "@/lib/thinkingSteps";+import type { ThinkingStep } from "@/lib/thinkingSteps";import type { ToolBlock, TurnBlock } from "./reduce";import { WorkTrace } from "./WorkTrace";@@ -57,5 +57,5 @@ export function VoiceWorkTrace({ steps, live = false, durationMs, className }: {// calling it "Failed" because one tool did would misreport a turn that// went on to answer.return <WorkTrace blocks={blocks} status={live ? "running" : "done"}- startedMs={steps[0]?.startedTs ?? Date.now()} durationMs={durationMs ?? null} className={className} model={traceModel(steps)} companion />;+ startedMs={steps[0]?.startedTs ?? Date.now()} durationMs={durationMs ?? null} className={className} companion />;}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.css b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.cssindex 0309394090..9f18477fc9 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.css+++ b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.css@@ -145,70 +145,16 @@}}-/* ── The written report of a finished turn (TraceReport.tsx) ────────────- Numbered steps on the same hairline thread as the live rail: each step's- marker is a small numbered ring centred on its first line, the thread- runs from below one marker to the next. A step that failed or was refused- draws its ring in the destructive colour; nothing else gets a frame. */-.trace-report-steps {- display: flex;- min-width: 0;- flex-direction: column;- margin-bottom: 0;- padding: 0;- list-style: none;-}-.trace-report-step {- position: relative;- display: flex;- min-width: 0;- gap: 0.75rem;- padding-bottom: 0.875rem;-}-.trace-report-step:last-child {- padding-bottom: 0;-}-.trace-report-step::after {- content: "";- position: absolute;- left: 9.5px;- top: 25px;- bottom: 3px;- width: 1px;- background: hsl(var(--border-strong));- pointer-events: none;-}-.trace-report-step:last-child::after {- display: none;-}-.trace-report-marker {- display: flex;- height: 1.5rem;- width: 1.25rem;- flex-shrink: 0;- align-items: center;- justify-content: center;- color: hsl(var(--muted-foreground));-}-.trace-report-num {- display: flex;- height: 1.25rem;- width: 1.25rem;- align-items: center;- justify-content: center;- border: 1px solid hsl(var(--border-strong));- border-radius: 9999px;- font-size: 11px;- font-variant-numeric: tabular-nums;- line-height: 1;+/* ── The timeline of a turn (TraceTimeline.tsx) ───────────────────────+ Lines hang on the same thread as the live rail. Edit sizes wear the diff+ colours; a long thought folds with a fade at its foot. */+.diff-count-add {+ color: hsl(var(--diff-add));}-.trace-report-step[data-outcome="failed"] .trace-report-num,-.trace-report-step[data-outcome="denied"] .trace-report-num {- border-color: hsl(var(--destructive));- color: hsl(var(--destructive));+.diff-count-del {+ color: hsl(var(--diff-del));}-/* A long reason folds with a fade at its foot, so it reads as "more below". */-.trace-report-fade {+.trace-thought-fade {-webkit-mask-image: linear-gradient(to bottom, black calc(100% - 2.5rem), transparent 100%);mask-image: linear-gradient(to bottom, black calc(100% - 2.5rem), transparent 100%);}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.test.tsxindex d4f4171b6c..918f7a774c 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.test.tsx@@ -41,7 +41,7 @@ describe("work trace", () => {it("keeps live mixed activity open, then folds it at completion", () => {const blocks = [tool("a",{name:"linear/get_issue"}),tool("b",{name:"exec_command"})];- const {rerender} = render(<WorkTrace {...props} status="running" blocks={blocks} />);+ const {rerender} = render(<WorkTrace {...rows} status="running" blocks={blocks} />);expect(screen.getByRole("button",{name:"Using Linear Running commands"}).getAttribute("aria-expanded")).toBe("true");rerender(<WorkTrace {...rows} blocks={blocks} />);expect(screen.getByRole("button",{name:"Used Linear Ran commands"}).getAttribute("aria-expanded")).toBe("false");@@ -59,7 +59,7 @@ describe("work trace", () => {it("preserves reasoning, call, next step and final answer order", () => {const blocks = [thought, tool("a"), { kind: "text" as const, id: "next", text: "Next, check the tests." }, tool("b"), { kind: "text" as const, id: "final", text: "Everything is ready." }];render(<WorkTrace {...props} blocks={blocks} />);- fireEvent.click(screen.getByRole("button", { name: /^Thought for 12s/ }));+ fireEvent.click(screen.getByRole("button", { name: /^Worked for 12s/ }));const text = screen.getByTestId("work-trace").textContent!;expect(text.indexOf("Check the input")).toBeLessThan(text.indexOf("a.ts"));expect(text.indexOf("a.ts")).toBeLessThan(text.indexOf("Next, check"));@@ -88,7 +88,7 @@ describe("work trace", () => {it("automatically collapses completed groups even after live interaction", () => {const blocks = [tool("a"), tool("b")];- const { rerender } = render(<WorkTrace {...props} status="running" blocks={blocks} />);+ const { rerender } = render(<WorkTrace {...rows} status="running" blocks={blocks} />);const group = screen.getByRole("button", { name: "Read 2 files" });fireEvent.click(group); fireEvent.click(group);expect(group.getAttribute("aria-expanded")).toBe("true");@@ -102,8 +102,8 @@ describe("work trace", () => {// already says that a step went wrong.expect(screen.getByText("Delete generated files?")).toBeTruthy();expect(screen.getByRole("button", { name: "Approve" })).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: /^Thought for 12s.*4 steps.*1 not done/ }));- expect(screen.getByText("It failed: Permission denied.")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: /^Worked for 12s.*1 failed/ }));+ expect(screen.getByText("Failed: Permission denied")).toBeTruthy();expect(screen.getByRole("button", { name: "Approve" })).toBeTruthy();});@@ -123,15 +123,17 @@ describe("work trace", () => {it("shows a denied action without a running indicator", () => {const {container} = render(<WorkTrace {...props} status="running" blocks={[tool("a",{output:null,approval:{approvalId:"ap",summary:"Delete?",decision:"deny"}})]} />);- expect(container.querySelector('[data-state="denied"]')).toBeTruthy();+ expect(screen.getByText("You declined it")).toBeTruthy();+ expect(container.querySelector('[data-trace-tool][data-state="running"]')).toBeNull();expect(screen.queryByRole("button", {name:"Approve"})).toBeNull();});it("renders edit input, a diff and output on demand", () => {render(<WorkTrace {...props} blocks={[tool("edit",{name:"Edit",input:{file_path:"app.ts",old_string:"oldValue",new_string:"newValue"},output:"File updated"})]} />);- fireEvent.click(screen.getByRole("button", { name: /^Thought for 12s/ }));- expect(screen.getByText(/Added 1 lines and removed 1\./)).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: "Details" }));+ fireEvent.click(screen.getByRole("button", { name: /^Worked for 12s/ }));+ // Codex-style: the edit is one line with its size; the diff is one tap away.+ const edit = screen.getByRole("button", { name: /^Edited app\.ts \+1 −1/ });+ fireEvent.click(edit);expect(screen.getByLabelText("Changes").textContent).toContain("− oldValue");expect(screen.getByLabelText("Changes").textContent).toContain("+ newValue");expect(screen.getByText("File updated")).toBeTruthy();@@ -140,10 +142,10 @@ describe("work trace", () => {it.each(["cancelled", "error"] as const)("does not leave tools spinning after %s", status => {const {container, rerender} = render(<WorkTrace {...rows} status={status} blocks={[tool("a",{output:null})]} />);expect(container.querySelector('[data-state="interrupted"]')).toBeTruthy();- expect(container.querySelector('[data-state="running"]')).toBeNull();+ expect(container.querySelector('[data-trace-tool][data-state="running"]')).toBeNull();rerender(<WorkTrace {...props} status={status} blocks={[tool("a",{output:null})]} />);- fireEvent.click(screen.getByRole("button", { name: /^Thought for 12s/ }));- expect(screen.getByText("It stopped before it returned a result.")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: /^Worked for 12s/ }));+ expect(screen.getByText("Stopped before it finished")).toBeTruthy();});it("updates the live clock and releases timers at completion", () => {@@ -157,13 +159,13 @@ describe("work trace", () => {it("does not interpret tool output as HTML", () => {const {container} = render(<WorkTrace {...props} blocks={[tool("a",{name:"run_shell",input:{command:"<b>echo</b>"},output:'<img src=x onerror=alert(1)>'})]} />);- fireEvent.click(screen.getByRole("button", { name: /^Thought for 12s/ }));- // Neither the sentence nor the result turns runtime text into markup.+ fireEvent.click(screen.getByRole("button", { name: /^Worked for 12s/ }));+ // Neither the command line nor its printed output turns into markup.expect(container.querySelector('img, b')).toBeNull();- expect(screen.getByTestId("trace-report").textContent).toContain('It returned “<img src=x onerror=alert(1)>”.');- fireEvent.click(screen.getByRole("button", { name: "Details" }));+ expect(container.querySelector("[data-trace-output]")?.textContent).toBe("<img src=x onerror=alert(1)>");+ fireEvent.click(screen.getByRole("button", { name: /^Ran <b>echo<\/b>/ }));expect(container.querySelector('img')).toBeNull();- expect(screen.getByText('<img src=x onerror=alert(1)>')).toBeTruthy();+ expect(screen.getAllByText('<img src=x onerror=alert(1)>').length).toBeGreaterThan(0);});it("formats durations without a 60-second remainder", () => {@@ -180,8 +182,8 @@ describe("work trace", () => {expect(screen.getByRole("button", { name: /Run command.*49ms/ })).toBeTruthy();expect(screen.queryByText("0.0s")).toBeNull();rerender(<WorkTrace {...props} blocks={[tool("shell", { name, input: { command: "read skill instructions" }, durationMs: 49 })]} />);- fireEvent.click(screen.getByRole("button", { name: /^Thought for 12s/ }));- expect(screen.getByText("49 ms")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: /^Worked for 12s/ }));+ expect(screen.getByRole("button", { name: /^Ran read skill instructions 49ms/ })).toBeTruthy();});it("keeps the last reply visible and treats earlier text as foldable work", () => {@@ -264,7 +266,7 @@ describe("rail look", () => {it("shows the services a folded conversation turn used on its toggle", () => {const blocks = [tool("linear", { name: "mcp__codex_apps__linear_list_issues" }), reply("done", "Three issues are open.")];render(<WorkTrace {...props} conversation blocks={blocks} />);- const toggle = screen.getByRole("button", { name: /^Thought for 12s/ });+ const toggle = screen.getByRole("button", { name: /^Worked for 12s/ });expect(toggle.querySelector("img, [data-logo]")).toBeTruthy();});});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsxindex 668661af85..67c5cea727 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx@@ -16,8 +16,8 @@ import { activityParts, traceToolIdentity, traceToolName } from "./traceActivityimport { ToolChoiceIcon } from "./ToolChoiceChips";import type { ToolChoice } from "./toolChoices";import { toolIdentityStyle } from "./toolIdentity";-import { TraceReport, useTraceNarrative } from "./TraceReport";-import type { TraceNarrative } from "./traceNarrative";+import { CopyTimeline, timelineItems, useTimeline, type TimelineRenderers } from "./TraceTimeline";+import { headerLabel, timelineMarkdown, traceDuration, type Timeline } from "./traceEntries";import "./WorkTrace.css";export type Decide = (id: string, decision: ApprovalDecision) => void | Promise<void>;@@ -36,14 +36,7 @@ export type TraceLook = "rail" | "classic";const TraceLookContext = createContext<TraceLook>("rail");const useRail = () => useContext(TraceLookContext) === "rail";-export function traceDuration(ms: number): string {- // Keep short, measured calls visible instead of rounding 49 ms to "0.0s".- if (ms > 0 && ms < 100) return `${Math.ceil(ms)}ms`;- const seconds = Math.max(0, ms) / 1000;- if (seconds < 10) return `${seconds.toFixed(1)}s`;- if (seconds < 60) return `${Math.floor(seconds)}s`;- return `${Math.floor(seconds / 60)}m ${String(Math.floor(seconds % 60)).padStart(2, "0")}s`;-}+export { traceDuration };function useClock(start: number, live: boolean) {const [now, setNow] = useState(Date.now);@@ -527,12 +520,12 @@ function traceLogos(blocks: TurnBlock[]): ToolChoice[] {}/** Small chevron that hides finished work so the reply can stand alone. */-function ConversationWorkFold({ durationMs, attention, blocks, children, narrative, initiallyOpen = false }: {+function ConversationWorkFold({ durationMs, attention, blocks, children, timeline, initiallyOpen = false }: {durationMs: number | null; attention?: ReactNode; blocks: TurnBlock[]; children: ReactNode;/** Start open — the work is the turn's only outcome (it answered nothing). */initiallyOpen?: boolean;- /** Rail look: the written report's tally, shown on the pill. */- narrative?: TraceNarrative;+ /** Rail look: the timeline behind the fold, for its "Worked for …" line. */+ timeline?: Timeline;}) {const t = useT();const rail = useRail();@@ -541,9 +534,10 @@ function ConversationWorkFold({ durationMs, attention, blocks, children, narrati// Counts openings so inner disclosures expand all at once, every time.const [seq, setSeq] = useState(initiallyOpen ? 1 : 0);const logos = useMemo(() => rail ? traceLogos(blocks) : [], [rail, blocks]);- const label = durationMs !== null && durationMs > 0- ? t("work_trace.thought_for").replace("{duration}", traceDuration(durationMs))- : t("work_trace.thought");+ const label = timeline ? headerLabel(timeline, durationMs, t)+ : durationMs !== null && durationMs > 0+ ? t("work_trace.thought_for").replace("{duration}", traceDuration(durationMs))+ : t("work_trace.thought");const toggle = () => {if (!open) setSeq((s) => s + 1);setOpen(!open);@@ -551,20 +545,17 @@ function ConversationWorkFold({ durationMs, attention, blocks, children, narratireturn (<div className="min-w-0" data-testid="conversation-work-fold" data-open={open ? "true" : "false"}>{rail ? <button type="button" aria-expanded={open} aria-controls={id} onClick={toggle}- className="group/fold mb-1.5 inline-flex max-w-full items-center gap-2 rounded-full border border-border py-1 pl-2.5 pr-2 text-left text-xs leading-5 text-muted-foreground transition-colors hover:border-border-strong hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ className="group/fold mb-0.5 flex max-w-full min-w-0 items-center gap-2 rounded-md py-1 text-left text-sm leading-6 text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">{logos.length ? <span aria-hidden className="flex shrink-0 items-center">{logos.map((row, i) => <span key={i} className={cn("tool-identity inline-flex rounded-full bg-background ring-2 ring-background", i > 0 && "-ml-1")} style={toolIdentityStyle(row)}><ToolChoiceIcon row={row} size={14} /></span>)}- </span> : <span aria-hidden className="trace-dot shrink-0" />}- <span className="truncate">{label}</span>- {narrative && narrative.actionCount > 0 ? <span className="shrink-0 tabular-nums">- <span aria-hidden className="mr-1.5 text-muted-foreground/50">·</span>- {t(`trace_report.steps_${narrative.actionCount === 1 ? "one" : "other"}`).replace("{count}", String(narrative.actionCount))}</span> : null}- {narrative && narrative.problemCount > 0 ? <span className="shrink-0 tabular-nums text-destructive">- <span aria-hidden className="mr-1.5 text-muted-foreground/50">·</span>- {t("trace_report.problems").replace("{count}", String(narrative.problemCount))}+ <span className="shrink-0 text-foreground-secondary group-hover/fold:text-foreground">{label}</span>+ {timeline?.summary ? <span className="min-w-0 truncate"><span aria-hidden className="mr-2 text-muted-foreground/50">·</span>{timeline.summary}</span> : null}+ {timeline && timeline.problemCount > 0 ? <span className="shrink-0 text-destructive">+ <span aria-hidden className="mr-2 text-muted-foreground/50">·</span>+ {t("trace_report.failed_count").replace("{count}", String(timeline.problemCount))}</span> : null}- <ChevronRight aria-hidden className={cn("h-3 w-3 shrink-0 opacity-60 transition-transform group-hover/fold:opacity-100", open && "rotate-90")} />+ <ChevronRight aria-hidden className={cn("h-3.5 w-3.5 shrink-0 opacity-60 transition-transform group-hover/fold:opacity-100", open && "rotate-90")} /></button> : <button type="button" aria-expanded={open} aria-controls={id}className="group/fold mb-1 inline-flex max-w-full items-center gap-1 rounded-md px-1.5 py-1 text-left text-xs leading-5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"onClick={toggle}>@@ -624,11 +615,17 @@ function traceGroupItems({ groups, live, status, onDecide, renderText, conversatcontinue;}if (!first.text.trim()) continue;- items.push({ key: group.id, rail: false, node: <div className={cn("min-w-0 py-2", conversation && "w-fit max-w-[min(85%,42rem)] rounded-2xl rounded-bl-md bg-secondary px-4 py-2.5")}>{renderText ? renderText(first.text, first.id) : <div className="prose prose-sm max-w-none text-foreground dark:prose-invert [overflow-wrap:anywhere]"><ChatMarkdown text={first.text} /></div>}</div> });+ items.push({ key: group.id, rail: false, node: replyNode(first, conversation, renderText) });}return items;}+function replyNode(block: TextBlock, conversation: boolean, renderText?: (text: string, id: string) => ReactNode): ReactNode {+ return <div className={cn("min-w-0 py-2", conversation && "w-fit max-w-[min(85%,42rem)] rounded-2xl rounded-bl-md bg-secondary px-4 py-2.5")}>+ {renderText ? renderText(block.text, block.id) : <div className="prose prose-sm max-w-none text-foreground dark:prose-invert [overflow-wrap:anywhere]"><ChatMarkdown text={block.text} /></div>}+ </div>;+}+/*** An agent's question shows as its card; the tool calls that only wait on* that card (``wait_for`` polls, jarvis/society/ask_tool.py) are plumbing@@ -649,8 +646,6 @@ type WorkTraceProps = {blocks: TurnBlock[]; status: TurnStatus; startedMs: number; durationMs: number | null; error?: string | null;onDecide?: Decide; renderText?: (text: string, id: string) => ReactNode; className?: string;receipt?: ReactNode; completionLabel?: string; conversation?: boolean;- /** The model that answered, named in the finished turn's written report. */- model?: string;/*** The trace is Jarvis's own (the front-page chat, a voice turn): the live* line shows the user's pet at work instead of a spinning circle. Agent@@ -659,15 +654,16 @@ type WorkTraceProps = {companion?: boolean;};-function WorkTraceBody({ blocks: rawBlocks, status, startedMs, durationMs, error, onDecide, renderText, className, receipt, completionLabel, conversation = false, companion = false, model }: WorkTraceProps) {+function WorkTraceBody({ blocks: rawBlocks, status, startedMs, durationMs, error, onDecide, renderText, className, receipt, completionLabel, conversation = false, companion = false }: WorkTraceProps) {const t = useT();const rail = useRail();const blocks = useMemo(() => withoutQuestionPolls(rawBlocks), [rawBlocks]);const live = status === "running";const elapsed = useClock(startedMs, live);- // The rail look folds every finished turn, conversation or not: the work- // becomes a written report behind the toggle (TraceReport), the reply- // stands alone. The classic look folds conversation turns only, as before.+ // The rail look folds every finished turn, conversation or not, the way+ // Claude and Codex do: "Worked for …" opens the turn's timeline+ // (TraceTimeline), the reply stands alone. The classic look folds+ // conversation turns only, as before.const split = useMemo(() => (conversation || rail) && !live ? splitConversationTurn(blocks) : null, [blocks, conversation, rail, live]);// A finished conversation turn shows the reply and nothing else. All work// — tools, thoughts, intermediate replies, failures, interruptions, and@@ -686,7 +682,9 @@ function WorkTraceBody({ blocks: rawBlocks, status, startedMs, durationMs, error}, [split]);const groups = useMemo(() => conversation ? groupConversationTrace(fold ? fold.workAll : blocks) : groupActivityTrace(blocks), [blocks, conversation, fold]);const restGroups = useMemo(() => fold ? groupConversationTrace(fold.answer) : null, [fold]);- const narrative = useTraceNarrative(fold && rail ? fold.workAll : NO_BLOCKS, status, durationMs, model);+ // A live turn keeps its replies and streaming pieces in place; a folded+ // one tells its narration as the timeline's prose.+ const timeline = useTimeline(rail ? (fold ? fold.workAll : blocks) : NO_BLOCKS, status, !fold);const asking = blocks.some(isOpenQuestion);const pending = asking || blocks.some(block => block.kind === "tool" && block.approval?.decision === null);const outcome = asking ? "question" : pending ? "approval" : live ? "working" : status === "error" ? "failed" : status === "cancelled" ? "stopped" : "done";@@ -724,20 +722,25 @@ function WorkTraceBody({ blocks: rawBlocks, status, startedMs, durationMs, errorconst statusItem: RailItem = { key: "trace:status", node: statusLine, rail: statusOnRail };const errorItem = (text: string, key: string): RailItem => ({ key, rail: false,node: <p role="alert" className="py-1.5 pl-7 text-sm text-destructive [overflow-wrap:anywhere]">{text}</p> });- const main = traceGroupItems({ groups, ...groupProps });+ const renderers: TimelineRenderers = {+ renderLive: (block) => block.kind === "tool" ? <TraceTool block={block} status={status} onDecide={onDecide} />+ : block.kind === "reasoning" ? <ReasoningTrace block={block} turnLive={live} compact={conversation} />+ : replyNode(block, conversation, renderText),+ liveOnRail: (block) => block.kind === "reasoning" || (block.kind === "tool" && !block.question),+ renderDetails: (block) => <ToolDetails block={block} />,+ };+ const steps = timelineItems(timeline, renderers);const rest = restGroups ? traceGroupItems({ groups: restGroups, ...groupProps }) : [];const items: RailItem[] = fold- ? [{ key: "trace:fold", rail: false, node: <ConversationWorkFold durationMs={durationMs} blocks={fold.workAll} narrative={narrative}+ ? [{ key: "trace:fold", rail: false, node: <ConversationWorkFold durationMs={durationMs} blocks={fold.workAll} timeline={timeline}// A turn that ended without an answer (TurnTrace names it so) has- // nothing to read but its work: the report stands open.+ // nothing to read but its work: the timeline stands open.initiallyOpen={!answered && Boolean(completionLabel)}attention={<div className="trace-fold-open"><Rail items={fold.approvals.map(block => ({ key: block.callId, rail: !block.question, node: <TraceTool block={block} status={status} onDecide={onDecide} /> }))} /></div>}>- <TraceReport narrative={narrative} renderDetails={(block) => <ToolDetails block={block} />} />- {/* A pending approval asks for a tap: the report names it, the card stays actionable. */}- {fold.approvals.length ? <div className="trace-fold-open pt-2"><Rail items={fold.approvals.map(block => ({ key: block.callId, rail: !block.question, node: <TraceTool block={block} status={status} onDecide={onDecide} /> }))} /></div> : null}- {foldedError ? <p role="alert" className="py-1.5 text-sm text-destructive [overflow-wrap:anywhere]">{foldedError}</p> : null}+ <Rail items={[...steps, ...(foldedError ? [errorItem(foldedError, "trace:folded-error")] : [])]} />+ <CopyTimeline text={() => timelineMarkdown(timeline, headerLabel(timeline, durationMs, t), t)} /></ConversationWorkFold> }, ...rest]- : main;+ : steps;if (visibleError) items.push(errorItem(visibleError, "trace:error"));items.push(statusItem);return <div className={cn("min-w-0", conversation && "w-full max-w-[44rem] self-start", className)} data-testid="work-trace" data-look="rail" data-state={status} {...(conversation ? { "data-conversation": "" } : {})}>@@ -770,7 +773,6 @@ export function TurnTrace({ turn, ...props }: { turn: TurnItem; onDecide?: Decidconst tokens = outputTokens(turn.usage ?? turn.liveUsage);const answered = turn.blocks.some(block => block.kind === "text" && block.text.trim());return <WorkTrace {...props} blocks={turn.blocks} status={turn.status} startedMs={turn.startedMs} durationMs={turn.durationMs} error={turn.error}- model={turn.model || undefined}completionLabel={!answered ? t("agent_chat.turn_no_answer") : undefined}receipt={tokens !== null && tokens > 0 || turn.costUsd !== null && turn.costUsd > 0 ? <>{tokens !== null && tokens > 0 ? <span aria-live="off" className="tabular-nums">{formatTokens(tokens)} {t("agent_chat.tokens")}</span> : null}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/traceEntries.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/traceEntries.test.tsnew file mode 100644index 0000000000..1c886c2d25--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/traceEntries.test.ts@@ -0,0 +1,210 @@+import { describe, expect, it } from "vitest";+import en from "@/i18n/locales/en.json";+import de from "@/i18n/locales/de.json";+import es from "@/i18n/locales/es.json";+import { reduceThinkingSteps, type ThinkingStep } from "@/lib/thinkingSteps";+import type { ToolBlock, TurnBlock } from "./reduce";+import { buildTimeline, headerLabel, previewOutput, shortPath, timelineMarkdown, traceDuration, type TimelineOptions } from "./traceEntries";+import { stepsToBlocks } from "./VoiceWorkTrace";++type Dict = Record<string, unknown>;+function translator(dict: Dict) {+ return (key: string): string => {+ let cur: unknown = dict;+ for (const part of key.split(".")) cur = cur && typeof cur === "object" ? (cur as Dict)[part] : undefined;+ return typeof cur === "string" ? cur : key;+ };+}+const t = translator(en as Dict);+const opts = (over: Partial<TimelineOptions> = {}): TimelineOptions => ({ t, lang: "en", status: "done", live: false, ...over });++const tool = (id: string, over: Partial<ToolBlock> = {}): ToolBlock => ({+ kind: "tool", callId: id, name: "Bash", input: { command: "ls" }, output: "a.ts", isError: false,+ durationMs: 300, approval: null, startedMs: 0, ...over,+});+const text = (id: string, body: string): TurnBlock => ({ kind: "text", id, text: body });+const thinking = (id: string, body: string, durationMs = 1000): TurnBlock => ({ kind: "reasoning", id, text: body, durationMs, live: false, startedMs: 0 });++function replay(events: Array<[string, Record<string, unknown>]>): ThinkingStep[] {+ let steps: ThinkingStep[] = [];+ events.forEach(([name, payload], i) => {+ steps = reduceThinkingSteps(steps, name, payload, 1000 + i * 10) ?? steps;+ });+ return steps.map((s) => (s.status === "active" ? { ...s, status: "done" } : s));+}++describe("trace timeline", () => {+ it("merges reads, listings and searches into one Codex-style Explored entry", () => {+ const line = buildTimeline([+ tool("r1", { name: "Read", input: { file_path: "C:/repo/src/app/main.ts" }, output: "1→a" }),+ tool("r2", { name: "Read", input: { file_path: "README.md" }, output: "x" }),+ tool("l", { name: "LS", input: { path: "src" }, output: "a\nb" }),+ tool("g", { name: "Grep", input: { pattern: "TODO", path: "src/lib" }, output: "src/lib/a.ts:3" }),+ tool("r3", { name: "Read", input: { file_path: "package.json" }, output: "{}" }),+ ], opts());+ expect(line.entries).toHaveLength(1);+ const explore = line.entries[0];+ expect(explore.kind).toBe("explore");+ if (explore.kind !== "explore") return;+ expect(explore.lines).toEqual([+ { verb: "read", targets: ["…/src/app/main.ts", "README.md"] },+ { verb: "list", targets: ["src"] },+ { verb: "search", targets: ["TODO in src/lib"] },+ { verb: "read", targets: ["package.json"] },+ ]);+ expect(explore.durationMs).toBe(1500);+ expect(line.summary).toBe("Read 3 files, listed a folder, and ran a search");+ });++ it("shows a command with the first lines it printed", () => {+ const line = buildTimeline([+ tool("c", { input: { command: "npm test\n--watch=false" }, output: "PASS a\nPASS b\n\nPASS c\nPASS d\nPASS e" }),+ ], opts());+ expect(line.entries[0]).toMatchObject({+ kind: "command", command: "npm test", status: "done",+ output: { lines: ["PASS a", "PASS b", "PASS c"], more: 2 },+ });+ expect(previewOutput("")).toBeNull();+ });++ it("tells a wrapped command by what it printed", () => {+ const line = buildTimeline([+ tool("j", { name: "mcp__jarvis__cli_jarvisctl", input: { command: "jarvisctl outputs list" },+ output: JSON.stringify({ exit_code: 0, stdout: "a.md\nb.md\n", stderr: "", duration_ms: 12 }) }),+ ], opts());+ expect(line.entries[0]).toMatchObject({ kind: "tool", result: "a.md" });+ });++ it("sizes an edit and names a created file", () => {+ const line = buildTimeline([+ tool("e", { name: "Edit", input: { file_path: "src/app.ts", old_string: "a\nb", new_string: "c" }, output: "ok" }),+ tool("w", { name: "Write", input: { file_path: "src/new.ts", content: "x\ny" }, output: "ok" }),+ ], opts());+ expect(line.entries[0]).toMatchObject({ kind: "edit", verb: "edit", path: "src/app.ts", added: 1, removed: 2 });+ expect(line.entries[1]).toMatchObject({ kind: "edit", verb: "write", path: "src/new.ts" });+ expect(line.summary).toBe("Edited a file and created a file");+ });++ it("keeps the model's words as prose and drops wordless thinking and plumbing", () => {+ const line = buildTimeline([+ thinking("r1", "", 820),+ text("n", "The repo has 85 stars. I'll fetch the timestamps."),+ tool("s", { name: "ToolSearch", input: { query: "select:mcp__jarvis__create_artifact" }, output: "[]" }),+ tool("a", { name: "mcp__jarvis__create_artifact", input: { title: "GitHub Stars" }, output: "The artifact is being built." }),+ thinking("r2", "**Checking** the result."),+ ], opts());+ expect(line.entries.map((e) => e.kind)).toEqual(["thought", "tool", "thought"]);+ expect(line.entries[1]).toMatchObject({ label: "Created an artifact", detail: "GitHub Stars", result: "The artifact is being built." });+ expect(line.thinkingMs).toBe(820);+ expect(line.actionCount).toBe(1);+ });++ it("names refusals, declines, failures and interruptions in plain words", () => {+ const line = buildTimeline([+ tool("b", { output: "blacklist: <tool-declared-block>", isError: true }),+ tool("d", { output: null, approval: { approvalId: "x", summary: "", decision: "deny" } }),+ tool("f", { output: "Error: 2 tests failed\n at run", isError: true }),+ tool("i", { output: null }),+ ], opts({ status: "cancelled" }));+ expect(line.entries.map((e) => e.kind === "command" ? [e.status, e.reason] : null)).toEqual([+ ["blocked", "a safety rule blocks this action"],+ ["declined", ""],+ ["failed", "Error: 2 tests failed"],+ ["interrupted", ""],+ ]);+ expect(line.problemCount).toBe(4);+ });++ it("leaves running calls, approvals and replies to the live rows while a turn runs", () => {+ const blocks: TurnBlock[] = [+ tool("done"),+ tool("running", { output: null }),+ tool("approve", { output: null, approval: { approvalId: "a", summary: "Delete?", decision: null } }),+ text("reply", "Halfway there."),+ { kind: "reasoning", id: "live", text: "thinking…", durationMs: null, live: true, startedMs: 0 },+ ];+ const line = buildTimeline(blocks, opts({ status: "running", live: true }));+ expect(line.entries.map((e) => e.kind)).toEqual(["command", "live", "live", "live", "live"]);+ });++ it("tells a stored Jarvis voice turn with registry names, a cut result and a refusal", () => {+ const steps = replay([+ ["ActionProposed", { tool_name: "find-app-action", args: { query: "computers" } }],+ ["ActionExecuted", { tool_name: "find-app-action", success: true, duration_ms: 4, output_preview: '{"actions": [{"action_id": "add_computer"' }],+ ["AnnouncementRequested", { kind: "preamble", text: "I'll check the computers you set up." }],+ ["ActionDenied", { tool_name: "run-app-action", reason: "blacklist: <tool-declared-block>" }],+ ["BrainTurnStarted", { provider: "grok", model: "grok-4.3" }],+ ["BrainTurnCompleted", { provider: "grok", model: "grok-4.3" }],+ ]);+ const line = buildTimeline(stepsToBlocks(steps, false, t), opts());+ expect(line.entries.map((e) => e.kind)).toEqual(["tool", "thought", "tool"]);+ expect(line.entries[0]).toMatchObject({ label: "Find App Action", detail: "computers" });+ expect(line.entries[1]).toMatchObject({ text: "I'll check the computers you set up." });+ expect(line.entries[2]).toMatchObject({ label: "Run App Action", status: "blocked", reason: "a safety rule blocks this action" });+ expect(headerLabel(line, 2400, t)).toBe("Worked for 2.4s");+ });++ it("says Thought for … when the turn only thought", () => {+ const line = buildTimeline([thinking("r", "Plan the answer.")], opts());+ expect(headerLabel(line, 3000, t)).toBe("Thought for 3.0s");+ expect(headerLabel(line, null, t)).toBe("Thought");+ });++ it("copies as Markdown in the timeline's own order", () => {+ const line = buildTimeline([+ text("n", "First the port."),+ tool("c", { durationMs: 1200, output: "8080" }),+ tool("r", { name: "Read", input: { file_path: "a.ts" }, output: "x" }),+ tool("f", { name: "Edit", input: { file_path: "b.ts", old_string: "a", new_string: "b" }, output: "boom", isError: true }),+ ], opts());+ expect(timelineMarkdown(line, headerLabel(line, 4200, t), t)).toBe([+ "**Worked for 4.2s** — Read a file, ran a command, and edited a file",+ "",+ "First the port.",+ "",+ "- Ran `ls` (1.2s)",+ " ```",+ " 8080",+ " ```",+ "",+ "- Explored",+ " - Read a.ts",+ "",+ "- Edited `b.ts` (+1 −1) (0.3s)",+ " Failed: boom",+ ].join("\n"));+ });++ it("formats durations and paths the way a trace line shows them", () => {+ expect(traceDuration(49)).toBe("49ms");+ expect(traceDuration(4200)).toBe("4.2s");+ expect(traceDuration(125_000)).toBe("2m 05s");+ expect(shortPath("C:\\Users\\me\\repo\\src\\a.ts")).toBe("…/repo/src/a.ts");+ });++ it.each([["de", de], ["es", es]] as const)("fills every %s line", (lang, dict) => {+ const tl = translator(dict as Dict);+ const line = buildTimeline([+ text("n", "Why."),+ tool("a", { name: "search_web", input: { query: "Wetter" }, output: '{"results": []}' }),+ tool("b", { isError: true, output: "boom" }),+ tool("c", { name: "Grep", input: { pattern: "x", path: "src" }, output: "y" }),+ tool("d", { output: "1\n2\n3\n4\n5" }),+ ], { t: tl, lang, status: "done", live: false });+ const all = [line.summary, headerLabel(line, 9000, tl), timelineMarkdown(line, headerLabel(line, 9000, tl), tl)].join("\n");+ expect(all).not.toMatch(/\{\w+\}|trace_report\./);+ });+});++describe("trace_report locale parity", () => {+ function keys(obj: Dict, prefix = ""): string[] {+ return Object.entries(obj).flatMap(([k, v]) => (v && typeof v === "object" ? keys(v as Dict, `${prefix}${k}.`) : [`${prefix}${k}`]));+ }+ const base = keys((en as Dict).trace_report as Dict).sort();+ it.each([["de", de], ["es", es]] as const)("%s carries exactly the English keys", (_lang, dict) => {+ expect(keys((dict as Dict).trace_report as Dict).sort()).toEqual(base);+ });+ it("never uses {name}, which the i18n layer fills with the assistant's name", () => {+ expect(JSON.stringify((en as Dict).trace_report)).not.toContain("{name}");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/traceEntries.ts b/jarvis/ui/web/frontend/src/components/agentchat/traceEntries.tsnew file mode 100644index 0000000000..f7b03eb84c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/traceEntries.ts@@ -0,0 +1,458 @@+/**+ * A turn's work as a timeline, in the shape Claude and Codex draw it.+ *+ * Both tools read the same way: the model's own words carry the story (its+ * narration between calls, its reasoning summaries) as plain prose, and the+ * calls between them are terse single lines — "Explored" with the files it+ * read and the patterns it searched, "Ran `npm test`" with the first lines+ * the command printed, "Edited src/app.ts +3 −1". A finished turn folds to+ * one line, "Worked for 4m 07s", and opens to exactly that timeline.+ *+ * This module is the pure model behind it: blocks → entries, the header's+ * one-line summary, and the same timeline as Markdown for copying. The+ * renderer is TraceTimeline.tsx.+ *+ * What it never does: invent a reason the model did not give, draw a row for+ * wordless (redacted) thinking — its time goes to the header — or draw+ * plumbing (loading a tool's schema, polling a question card).+ *+ * Placeholders never use `{name}`: the i18n layer fills that token with the+ * assistant's name before any string reaches this module.+ */++import { fill } from "@/i18n";+import { describeToolStep } from "@/lib/toolStepLabel";+import { isQuestionTool, type ReasoningBlock, type TextBlock, type ToolBlock, type TurnBlock, type TurnStatus } from "./reduce";+import { toolDiff } from "./toolDiff";+import { traceToolIdentity, traceToolName } from "./traceActivity";++export type Translate = (key: string) => string;++/** How a finished call ended. */+export type EntryStatus = "done" | "failed" | "blocked" | "declined" | "interrupted";++/** What the model said: its reasoning text, or narration between calls. */+export interface ThoughtEntry { kind: "thought"; id: string; text: string; block: ReasoningBlock | TextBlock }+/** Live work the classic row draws (running call, approval, question card, streaming thought, reply). */+export interface LiveEntry { kind: "live"; id: string; block: TurnBlock }+/** Consecutive reads, listings and searches, merged Codex-style. */+export interface ExploreEntry { kind: "explore"; id: string; lines: ExploreLine[]; blocks: ToolBlock[]; durationMs: number }+export interface ExploreLine { verb: "read" | "list" | "search"; targets: string[] }+export interface CommandEntry {+ kind: "command"; id: string; block: ToolBlock; command: string; status: EntryStatus;+ /** The first lines it printed (or the error), and how many more there were. */+ output: OutputPreview | null; reason: string;+}+export interface EditEntry {+ kind: "edit"; id: string; block: ToolBlock; verb: "edit" | "write"; path: string;+ added: number; removed: number; status: EntryStatus; reason: string;+}+export interface ToolEntry {+ kind: "tool"; id: string; block: ToolBlock; label: string; detail: string;+ /** A terse result ("3 results", the first line it said); "" when none. */+ result: string; status: EntryStatus; reason: string;+ /** A failed read, listing or search: counted as that, not as a tool used. */+ explore?: "read" | "list" | "search";+ /** How the header's "used …" names it: "the wiki", "GitHub · Create Issue". */+ subject: string;+}+export interface OutputPreview { lines: string[]; more: number }++export type TimelineEntry = ThoughtEntry | LiveEntry | ExploreEntry | CommandEntry | EditEntry | ToolEntry;++export interface Timeline {+ entries: TimelineEntry[];+ /** Calls told (live ones included). */+ actionCount: number;+ /** Calls that failed, were blocked, declined or cut off. */+ problemCount: number;+ /** Wordless thinking, summed. */+ thinkingMs: number;+ /** "Explored 3 files, ran 2 commands" — the folded header's tail. */+ summary: string;+}++export interface TimelineOptions {+ t: Translate;+ /** UI language tag, for plurals and lists. */+ lang: string;+ status: TurnStatus;+ /**+ * Live turns keep their replies and streaming pieces as live entries;+ * a finished turn's fold tells narration as thoughts.+ */+ live: boolean;+}++const KEY = "trace_report";+export const tr = (t: Translate, key: string, vars: Record<string, string | number> = {}) => fill(t(`${KEY}.${key}`), vars);++/** "49ms", "0.4s", "12s", "4m 07s" — the duration on a trace line. */+export function traceDuration(ms: number): string {+ // Keep short, measured calls visible instead of rounding 49 ms to "0.0s".+ if (ms > 0 && ms < 100) return `${Math.ceil(ms)}ms`;+ const seconds = Math.max(0, ms) / 1000;+ if (seconds < 10) return `${seconds.toFixed(1)}s`;+ if (seconds < 60) return `${Math.floor(seconds)}s`;+ return `${Math.floor(seconds / 60)}m ${String(Math.floor(seconds % 60)).padStart(2, "0")}s`;+}++export function plural(lang: string, count: number): "one" | "other" {+ try {+ return new Intl.PluralRules(lang).select(count) === "one" ? "one" : "other";+ } catch {+ return count === 1 ? "one" : "other";+ }+}++export function joinList(lang: string, items: string[]): string {+ if (items.length <= 1) return items[0] ?? "";+ try {+ return new Intl.ListFormat(lang, { style: "long", type: "conjunction" }).format(items);+ } catch {+ return items.join(", ");+ }+}++function oneLine(text: string, max: number): string {+ const clean = text.replace(/\s+/g, " ").trim();+ return clean.length > max ? `${clean.slice(0, max - 1).trimEnd()}…` : clean;+}++function inputRecord(block: ToolBlock): Record<string, unknown> {+ return block.input && typeof block.input === "object" && !Array.isArray(block.input)+ ? block.input as Record<string, unknown> : {};+}++function firstString(record: Record<string, unknown>, keys: string[]): string {+ for (const key of keys) {+ const value = record[key];+ if (typeof value === "string" && value.trim()) return value.trim();+ }+ return "";+}++/** The last two or three segments of a path — what a person recognises. */+export function shortPath(path: string): string {+ const parts = path.replace(/\\/g, "/").split("/").filter(Boolean);+ return parts.length > 3 ? `…/${parts.slice(-3).join("/")}` : path;+}++/** Plumbing calls draw nothing: loading a tool's schema, polling a question card. */+function isPlumbing(block: ToolBlock): boolean {+ if (isQuestionTool(block.name) && !block.question) return true;+ if (block.name.replace(/^mcp__[^_]+__/, "") === "ToolSearch") {+ return firstString(inputRecord(block), ["query"]).startsWith("select:");+ }+ return false;+}++/** Still asks for something or still running: the live row draws it. */+function isLiveBlock(block: ToolBlock, status: TurnStatus): boolean {+ if (block.question) return true;+ if (block.approval && block.approval.decision === null) return true;+ return block.output === null && status === "running" && block.approval?.decision !== "deny";+}++/** Drop the "… (+N more chars)" cap marker the backend appends. */+function stripCapMarker(text: string): string {+ return text.replace(/…\s*\(\+\d+ more chars\)\s*$/, "").trimEnd();+}++/** What a wrapped command printed ({exit_code, stdout, stderr}), or null. */+function printedOutput(output: string): string | null {+ if (!output.trimStart().startsWith("{")) return null;+ try {+ const record = JSON.parse(output) as Record<string, unknown>;+ if (!record || typeof record !== "object" || typeof record.stdout !== "string") return null;+ return record.stdout.trim() || (typeof record.stderr === "string" ? record.stderr : "");+ } catch {+ return null;+ }+}++const PREVIEW_LINES = 3;++/** The first lines of an output, the way Codex and Claude Code show them. */+export function previewOutput(output: string, max = PREVIEW_LINES): OutputPreview | null {+ const lines = output.split(/\r?\n/).map((line) => line.replace(/\s+$/, "")).filter((line) => line.trim());+ if (!lines.length) return null;+ return { lines: lines.slice(0, max).map((line) => (line.length > 160 ? `${line.slice(0, 159)}…` : line)), more: Math.max(0, lines.length - max) };+}++/** A refusal reason in plain words, when it is one of the system's own. */+function refusalReason(reason: string, t: Translate): string | null {+ const text = reason.trim();+ if (/^blacklist\b/i.test(text) || /tool-declared-block/i.test(text)) return tr(t, "reason.rule");+ if (/^plan mode/i.test(text)) return tr(t, "reason.plan_mode");+ if (/^cancelled\b/i.test(text)) return tr(t, "reason.cancelled");+ if (/^timeout$/i.test(text) || /approval timed out/i.test(text)) return tr(t, "reason.timeout");+ if (/approval[_ ]unavailable|no approval channel/i.test(text)) return tr(t, "reason.no_approver");+ return null;+}++/** How a finished call ended, and why when it did not succeed. */+function outcome(block: ToolBlock, t: Translate): { status: EntryStatus; reason: string } {+ if (block.approval?.decision === "deny") {+ const rule = refusalReason(block.approval.summary || block.output || "", t);+ return rule ? { status: "blocked", reason: rule } : { status: "declined", reason: "" };+ }+ if (block.output === null) return { status: "interrupted", reason: "" };+ if (block.isError) {+ const raw = stripCapMarker(block.output);+ const rule = refusalReason(raw, t);+ if (rule) return { status: "blocked", reason: rule };+ const first = raw.split(/\r?\n/).find((line) => line.trim()) ?? "";+ return { status: "failed", reason: oneLine(first, 200) };+ }+ return { status: "done", reason: "" };+}++/** Argument keys that name what a coding action touched. */+const ACTION_KEYS: Record<string, string[]> = {+ command: ["command", "cmd", "CommandLine", "commandLine", "script"],+ read: ["file_path", "path", "notebook_path", "filename"],+ edit: ["file_path", "path", "notebook_path"],+ write: ["file_path", "path", "filename"],+ list: ["path", "directory", "dir", "pattern"],+ search: ["pattern", "query", "regex", "q"],+};++/** Families of Jarvis's own tools that have a past-tense label. */+const FAMILY_LABELS = new Set([+ "wiki", "wiki_write", "artifact", "skill", "skill_create", "web", "screen", "screen_recall",+ "control", "navigate", "app", "memory", "memory_update", "profile", "contact", "call",+ "worker", "model", "mcp_admin", "settings", "verify",+]);++/** Keys whose string value says what a structured result was about. */+const GIST_KEYS = ["summary", "message", "result", "status", "title", "answer", "text", "detail", "description"];++/** A terse result for a generic tool: a count, its message, or its first line. */+function terseResult(block: ToolBlock, t: Translate, lang: string): string {+ let output = stripCapMarker(block.output ?? "");+ const printed = printedOutput(output);+ if (printed !== null) output = printed;+ const text = output.trim();+ if (!text) return "";+ if (text.startsWith("{") || text.startsWith("[")) {+ let parsed: unknown;+ try { parsed = JSON.parse(text); } catch { parsed = undefined; }+ if (Array.isArray(parsed)) {+ return parsed.length ? tr(t, `result.items_${plural(lang, parsed.length)}`, { count: parsed.length }) : tr(t, "result.none");+ }+ if (parsed && typeof parsed === "object") {+ const record = parsed as Record<string, unknown>;+ for (const key of GIST_KEYS) {+ const value = record[key];+ if (typeof value === "string" && value.trim()) return oneLine(value, 140);+ }+ for (const value of Object.values(record)) {+ if (Array.isArray(value)) {+ return value.length ? tr(t, `result.items_${plural(lang, value.length)}`, { count: value.length }) : tr(t, "result.none");+ }+ }+ return "";+ }+ // Cut by the preview cap: the top level still says a little.+ if (/^\{\s*["'][\w-]+["']\s*:\s*\[\s*\]/.test(text)) return tr(t, "result.none");+ const nested = text.slice(1).search(/[[{]/);+ const top = nested < 0 ? text : text.slice(0, nested + 1);+ const gist = new RegExp(`["'](?:${GIST_KEYS.join("|")})["']\\s*:\\s*["']([^"']{2,})["']`).exec(top);+ return gist ? oneLine(gist[1], 140) : "";+ }+ return oneLine(text.split(/\r?\n/).find((line) => line.trim()) ?? "", 140);+}++function diffSize(block: ToolBlock): { added: number; removed: number } {+ let added = 0;+ let removed = 0;+ for (const file of toolDiff(block.name, block.input, block.output) ?? []) {+ for (const line of file.lines) {+ if (line.kind === "add") added += 1;+ else if (line.kind === "del") removed += 1;+ }+ }+ return { added, removed };+}++/** One finished call as its entry (explore calls come back as a line to merge). */+function entryOf(block: ToolBlock, t: Translate, lang: string): ExploreLine | CommandEntry | EditEntry | ToolEntry {+ const view = traceToolIdentity(block);+ const record = inputRecord(block);+ const { status, reason } = outcome(block, t);+ const action = view.action === "memory" ? null : view.action;+ const name = traceToolName(block.name);+ const own = /^jarvis\//i.test(name) ? describeToolStep(name.slice("jarvis/".length), block.input) : null;+ const description = own && (FAMILY_LABELS.has(own.family) || own.family === "shell") ? own : view.description;++ if (action === "read" || action === "list" || action === "search") {+ if (status === "done") {+ const target = firstString(record, ACTION_KEYS[action]) || description.detail;+ const where = action === "search" ? firstString(record, ["path", "glob", "include"]) : "";+ const text = action === "search" && where+ ? tr(t, "entry.search_in", { pattern: oneLine(target, 60), path: shortPath(where) })+ : oneLine(action === "search" ? target : shortPath(target), 80);+ return { verb: action, targets: text ? [text] : [] };+ }+ }+ if (action === "command" || description.family === "shell") {+ let command = firstString(record, ACTION_KEYS.command) || (typeof block.input === "string" ? block.input : "") || description.detail;+ command = (command.split(/\r?\n/).find((line) => line.trim()) ?? "").trim();+ const raw = stripCapMarker(block.output ?? "");+ const printed = printedOutput(raw);+ return {+ kind: "command", id: block.callId, block, command: oneLine(command, 160), status, reason,+ output: status === "done" ? previewOutput(printed ?? raw) : null,+ };+ }+ if (action === "edit" || action === "write") {+ const path = shortPath(firstString(record, ACTION_KEYS[action]) || description.detail);+ return { kind: "edit", id: block.callId, block, verb: action, path, ...diffSize(block), status, reason };+ }+ const family = description.family;+ const label = FAMILY_LABELS.has(family) ? tr(t, `family.${family}`)+ : (() => {+ const raw = description.label || view.service || block.name;+ return /[A-Z]/.test(raw) ? raw : raw.split(/[-_\s.]+/).filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");+ })();+ if (action === "read" || action === "list" || action === "search") {+ // A failed read is told like any failed call.+ return { kind: "tool", id: block.callId, block, label: tr(t, `entry.${action}`), detail: oneLine(description.detail, 100), result: "", status, reason, explore: action, subject: "" };+ }+ return {+ kind: "tool", id: block.callId, block, label, detail: oneLine(description.detail, 100),+ result: status === "done" ? terseResult(block, t, lang) : "", status, reason,+ subject: FAMILY_LABELS.has(family) ? tr(t, `subject.${family}`) : label,+ };+}++/** Lay out a turn's blocks as its timeline. */+export function buildTimeline(blocks: TurnBlock[], options: TimelineOptions): Timeline {+ const { t, lang, status, live } = options;+ const entries: TimelineEntry[] = [];+ let thinkingMs = 0;+ const tally = { read: 0, list: 0, search: 0, command: 0, edit: 0, write: 0 };+ const used: string[] = [];+ let actionCount = 0;+ let problemCount = 0;++ for (const block of blocks) {+ if (block.kind === "reasoning") {+ if (live && status === "running" && block.live) {+ entries.push({ kind: "live", id: block.id, block });+ continue;+ }+ const text = block.text.trim();+ if (text) entries.push({ kind: "thought", id: block.id, text, block });+ else thinkingMs += block.durationMs ?? 0;+ continue;+ }+ if (block.kind === "text") {+ if (!block.text.trim()) continue;+ if (live) entries.push({ kind: "live", id: block.id, block });+ else entries.push({ kind: "thought", id: block.id, text: block.text.trim(), block });+ continue;+ }+ if (isPlumbing(block)) continue;+ actionCount += 1;+ if (isLiveBlock(block, status)) {+ entries.push({ kind: "live", id: block.callId, block });+ continue;+ }+ const entry = entryOf(block, t, lang);+ if ("verb" in entry && !("kind" in entry)) {+ tally[entry.verb] += 1;+ const previous = entries[entries.length - 1];+ if (previous?.kind === "explore") {+ const last = previous.lines[previous.lines.length - 1];+ if (last && last.verb === entry.verb && entry.verb === "read") last.targets.push(...entry.targets);+ else previous.lines.push(entry);+ previous.blocks.push(block);+ previous.durationMs += block.durationMs ?? 0;+ } else {+ entries.push({ kind: "explore", id: block.callId, lines: [entry], blocks: [block], durationMs: block.durationMs ?? 0 });+ }+ continue;+ }+ const full = entry as CommandEntry | EditEntry | ToolEntry;+ if (full.status !== "done") problemCount += 1;+ if (full.kind === "command") tally.command += 1;+ else if (full.kind === "edit") tally[full.verb] += 1;+ else if (full.explore) tally[full.explore] += 1;+ else if (full.status === "done" && !used.includes(full.subject)) used.push(full.subject);+ entries.push(full);+ }++ const parts: string[] = [];+ const count = (key: string, n: number) => { if (n) parts.push(tr(t, `sum.${key}_${plural(lang, n)}`, { count: n })); };+ count("read", tally.read);+ count("list", tally.list);+ count("search", tally.search);+ count("command", tally.command);+ count("edit", tally.edit);+ count("write", tally.write);+ if (used.length) parts.push(tr(t, "sum.used", { list: joinList(lang, used.slice(0, 3)) }));+ const joined = joinList(lang, parts);+ return {+ entries,+ actionCount,+ problemCount,+ thinkingMs,+ summary: joined ? joined.charAt(0).toUpperCase() + joined.slice(1) : "",+ };+}++/** The folded header: "Worked for 4m 07s" when calls ran, "Thought for 3.0s" otherwise. */+export function headerLabel(timeline: Timeline, durationMs: number | null, t: Translate): string {+ const worked = timeline.actionCount > 0;+ if (durationMs === null || durationMs <= 0) return tr(t, worked ? "worked" : "thought");+ return tr(t, worked ? "worked_for" : "thought_for", { duration: traceDuration(durationMs) });+}++function statusLine(entry: CommandEntry | EditEntry | ToolEntry, t: Translate): string {+ if (entry.status === "done") return "";+ const label = tr(t, `status.${entry.status}`);+ return entry.reason ? `${label}: ${entry.reason}` : label;+}++function codeSpan(text: string): string {+ const fence = text.includes("`") ? "``" : "`";+ const pad = fence === "``" ? " " : "";+ return `${fence}${pad}${text}${pad}${fence}`;+}++/** The timeline as Markdown — what "Copy" puts on the clipboard. */+export function timelineMarkdown(timeline: Timeline, header: string, t: Translate): string {+ const out: string[] = [`**${header}**${timeline.summary ? ` — ${timeline.summary}` : ""}`];+ for (const entry of timeline.entries) {+ out.push("");+ if (entry.kind === "thought") {+ out.push(entry.text);+ continue;+ }+ if (entry.kind === "live") continue;+ if (entry.kind === "explore") {+ out.push(`- ${tr(t, "entry.explored")}`);+ for (const line of entry.lines) out.push(` - ${tr(t, `entry.${line.verb}`)} ${line.targets.join(", ")}`);+ continue;+ }+ const time = entry.block.durationMs ? ` (${traceDuration(entry.block.durationMs)})` : "";+ const problem = statusLine(entry, t);+ if (entry.kind === "command") {+ out.push(`- ${tr(t, "entry.ran")} ${codeSpan(entry.command)}${time}`);+ if (entry.output) {+ out.push(" ```", ...entry.output.lines.map((line) => ` ${line}`));+ if (entry.output.more) out.push(` ${tr(t, `entry.more_${plural("en", entry.output.more)}`, { count: entry.output.more })}`);+ out.push(" ```");+ }+ } else if (entry.kind === "edit") {+ const size = entry.added || entry.removed ? ` (+${entry.added} −${entry.removed})` : "";+ out.push(`- ${tr(t, entry.verb === "edit" ? "entry.edited" : "entry.created")} ${codeSpan(entry.path)}${size}${time}`);+ } else {+ out.push(`- ${entry.label}${entry.detail ? ` — ${entry.detail}` : ""}${time}${entry.result ? `: ${entry.result}` : ""}`);+ }+ if (problem) out.push(` ${problem}`);+ }+ return out.join("\n").replace(/\n{3,}/g, "\n\n").trim();+}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/traceNarrative.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/traceNarrative.test.tsdeleted file mode 100644index 3d3d35b982..0000000000--- a/jarvis/ui/web/frontend/src/components/agentchat/traceNarrative.test.ts+++ /dev/null@@ -1,204 +0,0 @@-import { describe, expect, it } from "vitest";-import en from "@/i18n/locales/en.json";-import de from "@/i18n/locales/de.json";-import es from "@/i18n/locales/es.json";-import { reduceThinkingSteps, type ThinkingStep } from "@/lib/thinkingSteps";-import type { ToolBlock, TurnBlock } from "./reduce";-import { narrateTurn, narrativeMarkdown, proseDuration, type NarrateOptions } from "./traceNarrative";-import { stepsToBlocks } from "./VoiceWorkTrace";--type Dict = Record<string, unknown>;-function translator(dict: Dict) {- return (key: string): string => {- let cur: unknown = dict;- for (const part of key.split(".")) cur = cur && typeof cur === "object" ? (cur as Dict)[part] : undefined;- return typeof cur === "string" ? cur : key;- };-}-const t = translator(en as Dict);-const opts = (over: Partial<NarrateOptions> = {}): NarrateOptions => ({ t, lang: "en", status: "done", durationMs: 4200, ...over });--const tool = (id: string, over: Partial<ToolBlock> = {}): ToolBlock => ({- kind: "tool", callId: id, name: "Bash", input: { command: "ls" }, output: "a.ts", isError: false,- durationMs: 300, approval: null, startedMs: 0, ...over,-});-const text = (id: string, body: string): TurnBlock => ({ kind: "text", id, text: body });-const thinking = (id: string, body: string, durationMs = 1000): TurnBlock => ({ kind: "reasoning", id, text: body, durationMs, live: false, startedMs: 0 });--/** The steps a stored trace replays into, the way history and voice build them. */-function replay(events: Array<[string, Record<string, unknown>]>): ThinkingStep[] {- let steps: ThinkingStep[] = [];- events.forEach(([name, payload], i) => {- steps = reduceThinkingSteps(steps, name, payload, 1000 + i * 10) ?? steps;- });- return steps.map((s) => (s.status === "active" ? { ...s, status: "done" } : s));-}--describe("trace narrative", () => {- it("tells a stored Jarvis turn — registry names, a cut JSON result, a refusal — as prose", () => {- // The shape of a real stored turn (chats.db, 2026-10-02): no rationale,- // a result cut inside its first object, a call refused by a rule before- // it was ever proposed, and the brain call published after the tools.- const steps = replay([- ["ActionProposed", { tool_name: "find-app-action", args: { query: "computers", area: "computers" }, rationale: "" }],- ["ActionExecuted", { tool_name: "find-app-action", success: true, duration_ms: 4, output_preview: '{"actions": [{"action_id": "add_computer_api_computers_post", "title": "Add Computer"' }],- ["ActionDenied", { tool_name: "run-app-action", reason: "blacklist: <tool-declared-block>" }],- ["BrainTurnStarted", { provider: "grok", model: "grok-4.3" }],- ["BrainTurnCompleted", { provider: "grok", model: "grok-4.3" }],- ]);- const blocks = stepsToBlocks(steps, false, t);- // The brain call is the turn, not a step — no empty "Thought" row.- expect(blocks.map((b) => b.kind)).toEqual(["tool", "tool"]);- const story = narrateTurn(blocks, opts({ model: "grok · grok-4.3" }));- expect(story.steps.map((s) => s.sentence)).toEqual([- "Used the tool Find App Action with “computers”.",- "Used the tool Run App Action.",- ]);- expect(story.steps[0].result).toBe("It returned a list of actions.");- expect(story.steps[1].result).toBe("It did not run: a safety rule blocks this action.");- expect(story.steps[1].outcome).toBe("denied");- expect(story.overview).toBe(- "This answer took 4.2 s and 2 steps. Along the way it used Find App Action and Run App Action. "- + "One step was not allowed to run. Model: grok · grok-4.3.",- );- });-- it("puts the model's own words before the step they explain and drops plumbing", () => {- const blocks: TurnBlock[] = [- thinking("r1", "", 820),- tool("c1", { input: { command: "gh repo list --limit 50\nhead -50" }, output: "[]" }),- text("n1", "The repo has 85 stars. I'll fetch the timestamps."),- tool("c2", { input: { command: "gh api repos/x/stargazers" }, output: "85 /tmp/stars.txt\n2 2026-07-23\n1 2026-07-24" }),- thinking("r2", "", 541),- tool("c3", { name: "ToolSearch", input: { query: "select:mcp__jarvis__create_artifact" }, output: "[]" }),- tool("c4", { name: "mcp__jarvis__create_artifact", input: { title: "GitHub Stars", request: "Build it" }, output: "The artifact is being built in the background." }),- ];- const story = narrateTurn(blocks, opts({ durationMs: 28_518 }));- expect(story.actionCount).toBe(3);- expect(story.steps.map((s) => s.sentence)).toEqual([- "Ran the command `gh repo list --limit 50`.",- "Ran the command `gh api repos/x/stargazers`.",- "Created the artifact “GitHub Stars”.",- ]);- expect(story.steps[0].why).toEqual([]);- expect(story.steps[1].why).toEqual(["The repo has 85 stars. I'll fetch the timestamps."]);- expect(story.steps[0].result).toBe("It returned no results.");- expect(story.steps[1].result).toBe("It returned 3 lines, starting with “85 /tmp/stars.txt”.");- // A quote that ends its own sentence keeps one stop.- expect(story.steps[2].result).toBe("It returned “The artifact is being built in the background.”");- // Wordless thinking is time in the overview, never a step.- expect(story.thinkingMs).toBe(1361);- expect(story.overview).toContain("This answer took 29 s and 3 steps.");- expect(story.overview).toContain("1.4 s of that went into thinking.");- expect(story.overview).toContain("Along the way it ran 2 commands and used artifacts.");- expect(story.overview).toContain("Every step succeeded.");- });-- it("measures edits, reads, searches and failures in their own words", () => {- const story = narrateTurn([- tool("e", { name: "Edit", input: { file_path: "src/app.ts", old_string: "a\nb", new_string: "c" }, output: "ok" }),- tool("r", { name: "Read", input: { file_path: "src/app.ts" }, output: "1→one\n2→two\n3→three" }),- tool("g", { name: "Grep", input: { pattern: "TODO" }, output: "src/a.ts:3\nsrc/b.ts:9" }),- tool("f", { input: { command: "npm test" }, isError: true, output: "Error: 2 tests failed\n at run" }),- tool("i", { output: null }),- ], opts({ status: "cancelled" }));- expect(story.steps.map((s) => [s.sentence, s.result])).toEqual([- ["Edited `src/app.ts`.", "Added 1 lines and removed 2."],- ["Read `src/app.ts`.", "It was 3 lines long."],- ["Searched the files for `TODO`.", "It found 2 matches."],- ["Ran the command `npm test`.", "It failed: Error: 2 tests failed."],- ["Ran the command `ls`.", "It stopped before it returned a result."],- ]);- expect(story.problemCount).toBe(2);- expect(story.overview).toContain("One step failed. One step stopped before it returned a result.");- expect(story.overview).toContain("The turn was stopped before it finished.");- });-- it("tells a wrapped command by what it printed", () => {- const story = narrateTurn([- tool("j", { name: "mcp__jarvis__cli_jarvisctl", input: { command: "jarvisctl outputs list" },- output: JSON.stringify({ exit_code: 0, stdout: "a.md\nb.md\n", stderr: "", duration_ms: 12 }) }),- ], opts());- expect(story.steps[0].result).toBe("It returned 2 lines, starting with “a.md”.");- });-- it("tells approvals, declines and questions honestly", () => {- const story = narrateTurn([- tool("p", { output: null, approval: { approvalId: "a", summary: "Delete?", decision: null } }),- tool("d", { output: null, approval: { approvalId: "b", summary: "", decision: "deny" } }),- tool("q", {- name: "ask_user", input: {}, output: "", question: {- questionId: "q", asker: "Scout", questions: [{ question: "Which repo?", options: [], recommendationReason: "" }],- answers: [{ text: "PersonalJarvis", optionIndex: 0, source: "user" }], expiresMs: null, closed: true,- } as unknown as ToolBlock["question"],- }),- ], opts({ status: "running", durationMs: null }));- expect(story.steps.map((s) => s.result)).toEqual([- "It is waiting for your approval.",- "You declined it, so it did not run.",- "You answered “PersonalJarvis”.",- ]);- expect(story.steps[2].sentence).toBe("Asked you: “Which repo?”");- expect(story.steps[1].outcome).toBe("declined");- });-- it("keeps a closing thought as a note and escapes runtime text", () => {- const story = narrateTurn([- tool("w", { name: "search_web", input: { query: "*bold* [link](x)" }, output: "<b>hi</b>" }),- thinking("r", "**Check** the answer."),- ], opts());- expect(story.steps[0].sentence).toBe("Searched the web for “\\*bold\\* \\[link\\](x)”.");- expect(story.steps[0].result).toBe("It returned “\\<b\\>hi\\</b\\>”.");- expect(story.steps[1]).toMatchObject({ kind: "note", why: ["**Check** the answer."] });- expect(story.actionCount).toBe(1);- expect(story.overview).toBe("This answer took 4.2 s and one step. The step succeeded.");- });-- it("says only how long a turn thought when it took no step", () => {- expect(narrateTurn([thinking("r", "", 3000)], opts()).overview).toBe("This answer took 4.2 s of thinking.");- expect(narrateTurn([], opts({ durationMs: null })).overview).toBe("");- });-- it("copies as Markdown: overview, the model's words quoted, numbered steps", () => {- const story = narrateTurn([text("n", "First the port."), tool("c", { durationMs: 1200 })], opts());- expect(narrativeMarkdown(story, t)).toBe([- "### How this answer came about",- "",- "This answer took 4.2 s and one step. The step succeeded.",- "",- "> First the port.",- "",- "1. Ran the command `ls`. (1.2 s) It returned “a.ts”.",- ].join("\n"));- });-- it("formats prose durations without rounding a short call to zero", () => {- expect(proseDuration(49)).toBe("49 ms");- expect(proseDuration(4200)).toBe("4.2 s");- expect(proseDuration(28_518)).toBe("29 s");- expect(proseDuration(125_000)).toBe("2 min 05 s");- });-- it.each([["de", de], ["es", es]] as const)("writes whole %s sentences with every placeholder filled", (lang, dict) => {- const tl = translator(dict as Dict);- const story = narrateTurn([- text("n", "Why."),- tool("a", { name: "search_web", input: { query: "Wetter" }, output: '{"results": []}' }),- tool("b", { isError: true, output: "boom" }),- tool("c", { name: "mcp__github__create_issue", input: { title: "Bug" }, output: "#12" }),- ], { t: tl, lang, status: "done", durationMs: 9000, model: "m" });- const all = [story.overview, ...story.steps.flatMap((s) => [s.sentence, s.result]), narrativeMarkdown(story, tl)].join("\n");- expect(all).not.toMatch(/\{\w+\}|trace_report\./);- expect(story.overview).not.toContain("This answer");- });-});--describe("trace_report locale parity", () => {- function keys(obj: Dict, prefix = ""): string[] {- return Object.entries(obj).flatMap(([k, v]) => (v && typeof v === "object" ? keys(v as Dict, `${prefix}${k}.`) : [`${prefix}${k}`]));- }- const base = keys((en as Dict).trace_report as Dict).sort();- it.each([["de", de], ["es", es]] as const)("%s carries exactly the English keys", (_lang, dict) => {- expect(keys((dict as Dict).trace_report as Dict).sort()).toEqual(base);- });-});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/traceNarrative.ts b/jarvis/ui/web/frontend/src/components/agentchat/traceNarrative.tsdeleted file mode 100644index 1ade1e4e65..0000000000--- a/jarvis/ui/web/frontend/src/components/agentchat/traceNarrative.ts+++ /dev/null@@ -1,503 +0,0 @@-/**- * A finished turn's work, told as prose.- *- * The live rail shows a turn while it happens: a node per tool call, a- * shimmer on the step that is working. Read afterwards, that list was a poor- * record — "Thought for 0.8s" rows with nothing inside, registry names- * ("find-app-action"), a result cut to `{'actions': [{'...`, and the model's- * own explanation (its narration between calls, the sentence next to a call)- * scattered between rows or dropped. Nobody could look back at it and say- * what happened.- *- * This module turns the same blocks into a report a person can read and- * keep: one overview paragraph (how long, how many steps, what kinds of- * work, how it ended, which model), then every step as a full sentence —- * the model's reason for it first, in its own words, then what it did, then- * what came of it. `narrativeMarkdown` renders the same report as Markdown- * for copying.- *- * Rules the narrative keeps:- * - nothing is invented: a step without a reason has none, a result that- * cannot be read says so and points at the details;- * - redacted (wordless) thinking is never a step; its time is summed into- * the overview;- * - plumbing (loading a tool's definition, polling a question card) is not- * a step;- * - every sentence comes from `trace_report.*` keys, so all locales read- * as their own language; runtime text (commands, paths, queries) is- * inserted verbatim, Markdown-escaped or as inline code.- *- * Placeholders never use `{name}`: the i18n layer fills that token with the- * assistant's name before any sentence sees it.- *- * Pure: no React, no store — `t` and the UI language come in as arguments.- */--import { fill } from "@/i18n";-import { isQuestionTool, type ToolBlock, type TurnBlock, type TurnStatus } from "./reduce";-import { toolDiff } from "./toolDiff";-import { describeToolStep } from "@/lib/toolStepLabel";-import { traceToolIdentity, traceToolName } from "./traceActivity";--export type Translate = (key: string) => string;--/** How a step ended, in the words the report uses. */-export type StepOutcome = "done" | "failed" | "denied" | "declined" | "interrupted" | "pending";--export interface NarrativeStep {- id: string;- /** "action": a tool call. "note": the model's words with no call after them. */- kind: "action" | "note";- /** Markdown sentence of what was done; empty for a note. */- sentence: string;- /** The model's own words that led to this step, oldest first (Markdown). */- why: string[];- /** Markdown sentence of what came of it; empty when there is nothing to say. */- result: string;- outcome: StepOutcome;- durationMs: number | null;- /** The call itself, for its details; null for a note. */- block: ToolBlock | null;-}--export interface TraceNarrative {- /** The overview paragraph (Markdown). */- overview: string;- steps: NarrativeStep[];- /** Tool calls told as steps. */- actionCount: number;- /** Steps that did not succeed (failed, refused, declined, interrupted). */- problemCount: number;- /** Time spent in wordless thinking, summed. */- thinkingMs: number;-}--export interface NarrateOptions {- t: Translate;- /** UI language, for list joining and plurals ("en", "de", "es"). */- lang: string;- status: TurnStatus;- durationMs: number | null;- /** The model that answered, when the turn said. */- model?: string;-}--const KEY = "trace_report";-/**- * Fill a sentence and tidy its end: a quoted value that closes with its own- * stop ("It returned “Done.”.") keeps one, the way a person writes it.- */-const tr = (t: Translate, key: string, vars: Record<string, string | number> = {}) =>- fill(t(`${KEY}.${key}`), vars).replace(/([.!?…])([”“»"])\.$/, "$1$2");--/** A duration the way a sentence says it: "49 ms", "0.4 s", "12 s", "2 min 05 s". */-export function proseDuration(ms: number): string {- // A measured short call stays measured instead of rounding to "0.0 s".- if (ms > 0 && ms < 100) return `${Math.ceil(ms)} ms`;- const seconds = Math.max(0, ms) / 1000;- if (seconds < 10) return `${seconds.toFixed(1)} s`;- if (seconds < 60) return `${Math.round(seconds)} s`;- return `${Math.floor(seconds / 60)} min ${String(Math.floor(seconds % 60)).padStart(2, "0")} s`;-}--function plural(lang: string, count: number): "one" | "other" {- try {- return new Intl.PluralRules(lang).select(count) === "one" ? "one" : "other";- } catch {- return count === 1 ? "one" : "other";- }-}--function joinList(lang: string, items: string[]): string {- if (items.length <= 1) return items[0] ?? "";- try {- return new Intl.ListFormat(lang, { style: "long", type: "conjunction" }).format(items);- } catch {- return `${items.slice(0, -1).join(", ")} & ${items[items.length - 1]}`;- }-}--/** Escape free text so it reads as text inside a Markdown sentence. */-export function escapeMarkdown(text: string): string {- return text.replace(/([\\`*_[\]<>#|~])/g, "\\$1");-}--/** Inline code that survives backticks inside the value. */-function code(text: string): string {- const fence = text.includes("`") ? "``" : "`";- const pad = fence === "``" ? " " : "";- return `${fence}${pad}${text}${pad}${fence}`;-}--function oneLine(text: string, max: number): string {- const clean = text.replace(/\s+/g, " ").trim();- return clean.length > max ? `${clean.slice(0, max - 1).trimEnd()}…` : clean;-}--function inputRecord(block: ToolBlock): Record<string, unknown> {- return block.input && typeof block.input === "object" && !Array.isArray(block.input)- ? block.input as Record<string, unknown> : {};-}--function firstString(record: Record<string, unknown>, keys: string[]): string {- for (const key of keys) {- const value = record[key];- if (typeof value === "string" && value.trim()) return value.trim();- }- return "";-}--/** Plumbing calls draw no step: loading a tool's schema, polling a question card. */-function isPlumbing(block: ToolBlock): boolean {- if (isQuestionTool(block.name) && !block.question) return true;- const name = block.name.replace(/^mcp__[^_]+__/, "");- if (name === "ToolSearch") {- const query = firstString(inputRecord(block), ["query"]);- return query.startsWith("select:");- }- return false;-}--/** Families of Jarvis's own tools that have their own sentence. */-const FAMILY_SENTENCES = new Set([- "wiki", "wiki_write", "artifact", "skill", "skill_create", "web", "screen", "screen_recall",- "control", "navigate", "app", "memory", "memory_update", "profile", "contact", "call",- "worker", "model", "mcp_admin", "settings", "verify",-]);--/** Argument keys that name what a coding action touched. */-const ACTION_DETAIL: Record<string, string[]> = {- command: ["command", "cmd", "CommandLine", "commandLine", "script"],- read: ["file_path", "path", "notebook_path", "filename"],- edit: ["file_path", "path", "notebook_path"],- write: ["file_path", "path", "filename"],- list: ["path", "pattern", "directory", "dir"],- search: ["pattern", "query", "regex", "q"],-};--/** What a step is about, for its sentence and for the overview's tally. */-interface StepSubject {- /** Sentence key under trace_report.step.* (without the _plain suffix). */- key: string;- /** Detail already formatted for Markdown (code or escaped text); "" when none. */- detail: string;- /** Variables besides the detail ({tool}). */- vars: Record<string, string>;- /** Tally bucket for the overview: an action kind, or "used:<name>". */- tally: string;-}--function subjectOf(block: ToolBlock, t: Translate): StepSubject {- const view = traceToolIdentity(block);- const record = inputRecord(block);- // Memory tools speak through their Jarvis family ("Remembered …"), not as- // a file action.- if (view.action && view.action !== "memory") {- const action = view.action;- let raw = firstString(record, ACTION_DETAIL[action] ?? []);- if (!raw && typeof block.input === "string") raw = block.input;- if (!raw) raw = view.description.detail;- // A command is one line in prose; the full text stays in the details.- const firstLine = raw.split(/\r?\n/).find((line) => line.trim()) ?? "";- const text = oneLine(firstLine, action === "command" ? 120 : 100);- return { key: action, detail: text ? code(text) : "", vars: {}, tally: action };- }- // Jarvis's own tools reached through its MCP server- // ("mcp__jarvis__create_artifact") are the tools of its own loop and read- // the same way.- const name = traceToolName(block.name);- const own = /^jarvis\//i.test(name) ? describeToolStep(name.slice("jarvis/".length), block.input) : null;- const description = own && (FAMILY_SENTENCES.has(own.family) || own.family === "shell") ? own : view.description;- const family = description.family;- if (family === "shell") {- const text = oneLine(firstString(record, ACTION_DETAIL.command) || description.detail, 120);- return { key: "command", detail: text ? code(text) : "", vars: {}, tally: "command" };- }- const detailText = oneLine(description.detail, 100);- const detail = detailText ? escapeMarkdown(detailText) : "";- if (FAMILY_SENTENCES.has(family)) {- return { key: family, detail, vars: {}, tally: `used:${t(`${KEY}.subject.${family}`)}` };- }- if (view.integration || family === "mcp" || family === "service") {- const label = view.description.label || view.service;- return { key: "service", detail, vars: { tool: escapeMarkdown(label) }, tally: `used:${view.service || label}` };- }- // A registry name ("find-app-action") reads as a name: "Find App Action".- const raw = view.description.label || block.name;- const label = /[A-Z]/.test(raw) ? raw- : raw.split(/[-_\s.]+/).filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");- return { key: "tool", detail, vars: { tool: escapeMarkdown(label) }, tally: `used:${label}` };-}--function sentenceOf(subject: StepSubject, t: Translate): string {- const key = subject.detail ? `step.${subject.key}` : `step.${subject.key}_plain`;- return tr(t, key, { ...subject.vars, detail: subject.detail });-}--// ── Results ──────────────────────────────────────────────────────────────--/** Keys whose string value says what a structured result was about. */-const GIST_KEYS = ["summary", "message", "result", "status", "title", "answer", "text", "detail", "description"];--/** Drop the "… (+N more chars)" cap marker the backend appends. */-function stripCapMarker(text: string): string {- return text.replace(/…\s*\(\+\d+ more chars\)\s*$/, "").trimEnd();-}--/** Free text quoted the way the UI language quotes. */-function quote(t: Translate, text: string, max = 160): string {- return tr(t, "quote", { text: escapeMarkdown(oneLine(text, max)) });-}--/** A sentence for structured output, or null when it is not structured. */-function structuredResult(output: string, t: Translate, lang: string): string | null {- const text = output.trim();- if (!text.startsWith("{") && !text.startsWith("[")) return null;- let parsed: unknown;- try { parsed = JSON.parse(text); } catch { parsed = undefined; }- if (Array.isArray(parsed)) {- return parsed.length === 0 ? tr(t, "result.none")- : tr(t, `result.items_${plural(lang, parsed.length)}`, { count: parsed.length });- }- if (parsed && typeof parsed === "object") {- const record = parsed as Record<string, unknown>;- for (const key of GIST_KEYS) {- const value = record[key];- if (typeof value === "string" && value.trim()) return tr(t, "result.text", { text: quote(t, value) });- }- for (const [key, value] of Object.entries(record)) {- if (!Array.isArray(value)) continue;- const what = escapeMarkdown(key.replace(/_/g, " "));- return value.length === 0 ? tr(t, "result.named_none", { what })- : tr(t, `result.named_items_${plural(lang, value.length)}`, { count: value.length, what });- }- const fields = Object.keys(record).slice(0, 4).map(code);- if (fields.length) return tr(t, "result.fields", { fields: joinList(lang, fields) });- }- // Cut or Python-shaped: the leading key still tells what it was about.- const list = /^\{\s*["']([\w-]+)["']\s*:\s*\[(\s*\])?/.exec(text);- if (list) {- const what = escapeMarkdown(list[1].replace(/_/g, " "));- return list[2] ? tr(t, "result.named_none", { what }) : tr(t, "result.named_list", { what });- }- // Only the top level speaks for the whole: stop at the first nested value.- const nested = text.slice(1).search(/[[{]/);- const top = nested < 0 ? text : text.slice(0, nested + 1);- const gist = new RegExp(`["'](?:${GIST_KEYS.join("|")})["']\\s*:\\s*["']([^"']{2,})["']`).exec(top);- if (gist) return tr(t, "result.text", { text: quote(t, gist[1]) });- return tr(t, "result.data");-}--/** What a wrapped command printed (stdout, else stderr), or null when not wrapped. */-function printedOutput(output: string): string | null {- if (!output.trimStart().startsWith("{")) return null;- try {- const record = JSON.parse(output) as Record<string, unknown>;- if (!record || typeof record !== "object" || typeof record.stdout !== "string") return null;- return record.stdout.trim() || (typeof record.stderr === "string" ? record.stderr : "");- } catch {- return null;- }-}--function lineCount(text: string): number {- return text.split(/\r?\n/).filter((line) => line.trim()).length;-}--/** Edits read as their size; everything else by what the output says. */-function successResult(block: ToolBlock, action: string | null, t: Translate, lang: string): string {- const diff = toolDiff(block.name, block.input, block.output);- if (diff) {- let added = 0;- let removed = 0;- for (const file of diff) for (const line of file.lines) {- if (line.kind === "add") added += 1;- else if (line.kind === "del") removed += 1;- }- if (added || removed) return tr(t, "result.diff", { added, removed });- }- let output = stripCapMarker(block.output ?? "");- // A command runner that wraps its output ({exit_code, stdout, stderr})- // is told by what it printed.- const printed = printedOutput(output);- if (printed !== null) output = printed;- if (!output.trim()) return "";- if (action === "edit" || action === "write") return "";- const structured = structuredResult(output, t, lang);- if (structured) return structured;- const lines = lineCount(output);- if (action === "read") return tr(t, `result.read_${plural(lang, lines)}`, { count: lines });- if (action === "search" || action === "list") {- return tr(t, `result.found_${plural(lang, lines)}`, { count: lines });- }- const first = output.split(/\r?\n/).find((line) => line.trim()) ?? "";- if (lines <= 1) return tr(t, "result.text", { text: quote(t, first, 200) });- return tr(t, "result.lines", { count: lines, text: quote(t, first, 120) });-}--/** A refusal reason in plain words, when it is one of the system's own. */-function refusalReason(reason: string, t: Translate): string | null {- const text = reason.trim();- if (/^blacklist\b/i.test(text) || /tool-declared-block/i.test(text)) return tr(t, "reason.rule");- if (/^plan mode/i.test(text)) return tr(t, "reason.plan_mode");- if (/^cancelled\b/i.test(text)) return tr(t, "reason.cancelled");- if (/^timeout$/i.test(text) || /approval timed out/i.test(text)) return tr(t, "reason.timeout");- if (/approval[_ ]unavailable|no approval channel/i.test(text)) return tr(t, "reason.no_approver");- if (/^(user|denied|deny|declined|rejected)\b/i.test(text)) return tr(t, "reason.declined");- return null;-}--function resultOf(block: ToolBlock, status: TurnStatus, t: Translate, lang: string): { result: string; outcome: StepOutcome } {- if (block.question) {- const answers = block.question.answers.filter((answer) => answer && answer.text.trim());- if (answers.length) {- return { result: tr(t, "result.answered", { text: quote(t, answers.map((a) => a!.text).join(" · ")) }), outcome: "done" };- }- return block.question.closed ? { result: tr(t, "result.unanswered"), outcome: "interrupted" }- : { result: tr(t, "result.waiting_answer"), outcome: "pending" };- }- if (block.approval && block.approval.decision === null) return { result: tr(t, "result.pending"), outcome: "pending" };- if (block.approval?.decision === "deny") {- const why = refusalReason(block.approval.summary || block.output || "", t);- return why && why !== tr(t, "reason.declined")- ? { result: tr(t, "result.refused", { reason: why }), outcome: "denied" }- : { result: tr(t, "result.declined"), outcome: "declined" };- }- if (block.output === null) {- return status === "running" ? { result: "", outcome: "pending" } : { result: tr(t, "result.interrupted"), outcome: "interrupted" };- }- if (block.isError) {- const raw = stripCapMarker(block.output);- const why = refusalReason(raw, t);- if (why) return { result: tr(t, "result.refused", { reason: why }), outcome: "denied" };- const first = raw.split(/\r?\n/).find((line) => line.trim()) ?? "";- // The reason is the tool's own first line; it closes the sentence.- const reason = escapeMarkdown(oneLine(first, 200));- return first ? { result: tr(t, "result.failed", { reason: /[.!?…:]$/.test(reason) ? reason : `${reason}.` }), outcome: "failed" }- : { result: tr(t, "result.failed_plain"), outcome: "failed" };- }- return { result: successResult(block, traceToolIdentity(block).action, t, lang), outcome: "done" };-}--// ── The narrative ────────────────────────────────────────────────────────--/** Tell a turn's work. `blocks` is the work only — the final reply stays out. */-export function narrateTurn(blocks: TurnBlock[], options: NarrateOptions): TraceNarrative {- const { t, lang, status } = options;- const steps: NarrativeStep[] = [];- const tally = new Map<string, number>();- let pendingWhy: string[] = [];- let thinkingMs = 0;- let firstNoteId = "";-- for (const block of blocks) {- if (block.kind === "reasoning") {- const text = block.text.trim();- if (text) {- if (!pendingWhy.length) firstNoteId = block.id;- pendingWhy.push(text);- } else thinkingMs += block.durationMs ?? 0;- continue;- }- if (block.kind === "text") {- const text = block.text.trim();- if (text) {- if (!pendingWhy.length) firstNoteId = block.id;- pendingWhy.push(text);- }- continue;- }- if (isPlumbing(block)) continue;- const subject = block.question- ? { key: "question", detail: block.question.questions[0]?.question ? quote(t, block.question.questions[0].question, 200) : "", vars: {}, tally: "question" }- : subjectOf(block, t);- const { result, outcome } = resultOf(block, status, t, lang);- tally.set(subject.tally, (tally.get(subject.tally) ?? 0) + 1);- steps.push({- id: block.callId,- kind: "action",- sentence: sentenceOf(subject, t),- why: pendingWhy,- result,- outcome,- durationMs: block.durationMs,- block,- });- pendingWhy = [];- }- if (pendingWhy.length) {- steps.push({ id: `note:${firstNoteId}`, kind: "note", sentence: "", why: pendingWhy, result: "", outcome: "done", durationMs: null, block: null });- }-- const actions = steps.filter((step) => step.kind === "action");- const problems = actions.filter((step) => step.outcome !== "done" && step.outcome !== "pending");- return {- overview: overviewOf({ actions, problems, tally, thinkingMs, options }),- steps,- actionCount: actions.length,- problemCount: problems.length,- thinkingMs,- };-}--function overviewOf({ actions, problems, tally, thinkingMs, options }: {- actions: NarrativeStep[]; problems: NarrativeStep[]; tally: Map<string, number>; thinkingMs: number; options: NarrateOptions;-}): string {- const { t, lang, status, durationMs, model } = options;- const parts: string[] = [];- const count = actions.length;- const duration = durationMs !== null && durationMs > 0 ? proseDuration(durationMs) : "";- if (count > 0) {- parts.push(duration ? tr(t, `lead_${plural(lang, count)}`, { duration, count })- : tr(t, `lead_nodur_${plural(lang, count)}`, { count }));- if (thinkingMs >= 1000) parts.push(tr(t, "thinking_share", { duration: proseDuration(thinkingMs) }));- } else if (duration) {- parts.push(tr(t, "lead_thinking", { duration }));- }-- if (count >= 2) {- const did: string[] = [];- const used: string[] = [];- for (const [bucket, n] of tally) {- if (bucket.startsWith("used:")) used.push(escapeMarkdown(bucket.slice(5)));- else did.push(tr(t, `did.${bucket}_${plural(lang, n)}`, { count: n }));- }- if (used.length) did.push(tr(t, "did.used", { list: joinList(lang, used) }));- if (did.length) parts.push(tr(t, "did_sentence", { list: joinList(lang, did) }));- }-- if (count > 0) {- const by = (outcome: StepOutcome) => problems.filter((step) => step.outcome === outcome).length;- const problemParts: string[] = [];- for (const outcome of ["failed", "denied", "declined", "interrupted"] as const) {- const n = by(outcome);- if (n) problemParts.push(tr(t, `outcome.${outcome}_${plural(lang, n)}`, { count: n }));- }- if (problemParts.length) parts.push(...problemParts);- else if (!actions.some((step) => step.outcome === "pending")) {- parts.push(tr(t, count === 1 ? "outcome.ok_one" : "outcome.ok_other"));- }- }- if (status === "cancelled") parts.push(tr(t, "turn_stopped"));- else if (status === "error") parts.push(tr(t, "turn_failed"));- if (model) parts.push(tr(t, "model", { model: escapeMarkdown(model) }));- return parts.join(" ");-}--/** The report as Markdown — what "Copy" puts on the clipboard. */-export function narrativeMarkdown(narrative: TraceNarrative, t: Translate): string {- const lines: string[] = [`### ${tr(t, "title")}`, "", narrative.overview];- let n = 0;- for (const step of narrative.steps) {- lines.push("");- if (step.kind === "note") {- for (const why of step.why) lines.push(...why.split(/\r?\n/).map((line) => `> ${line}`));- continue;- }- n += 1;- for (const why of step.why) lines.push(...why.split(/\r?\n/).map((line) => `> ${line}`), "");- const tail = step.durationMs !== null && step.durationMs > 0 ? ` (${proseDuration(step.durationMs)})` : "";- lines.push(`${n}. ${step.sentence}${tail}${step.result ? ` ${step.result}` : ""}`);- }- return lines.join("\n").replace(/\n{3,}/g, "\n\n").trim();-}diff --git a/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx b/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsxindex 4a26fd1042..9ebfc68628 100644--- a/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx+++ b/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx@@ -764,9 +764,9 @@ describe("ChatStage (agent chat)", () => {render(<ChatStage />);const trace = screen.getByTestId("work-trace");- // The finished turn folds into its written report; one tap opens it.- fireEvent.click(within(trace).getByRole("button", { name: /^Thought for 6\.0s/ }));- const text = within(trace).getByTestId("trace-report").textContent!;+ // The finished turn folds behind "Worked for …"; one tap opens its timeline.+ fireEvent.click(within(trace).getByRole("button", { name: /^Worked for 6\.0s/ }));+ const text = trace.textContent!;expect(text.indexOf("First the port.")).toBeLessThan(text.indexOf("Get-NetTCPConnection"));expect(text.indexOf("Get-NetTCPConnection")).toBeLessThan(text.indexOf("It is listening."));});@@ -792,7 +792,7 @@ describe("ChatStage (agent chat)", () => {expect(outcome.textContent).not.toContain("35.4k");// With no answer the report IS the outcome: it stands open and the// failure reads without opening anything.- expect(screen.getByText(/permission check failed for command/).textContent).toContain("It failed");+ expect(screen.getByText(/permission check failed for command/).textContent).toContain("Failed");// Nothing claims to still be working.expect(screen.queryByTestId("agent-turn-live")).toBeNull();});@@ -808,17 +808,19 @@ describe("ChatStage (agent chat)", () => {]);useAgentChatStore.setState({ activeSessionId: "s5", timeline });render(<ChatStage />);- const report = screen.getByTestId("trace-report");- const [shell, grep] = Array.from(report.querySelectorAll<HTMLElement>("li[data-kind='action']"));- expect(shell.textContent).toContain("Ran the command ls -la.");- expect(grep.textContent).toContain("Searched the files for TODO.");+ // With no answer the timeline stands open: the command with what it+ // printed, the search folded into an "Explored" line.+ const shell = document.querySelector<HTMLElement>("[data-trace-entry='command']")!;+ const explore = document.querySelector<HTMLElement>("[data-trace-entry='explore']")!;+ expect(shell.textContent).toContain("Ranls -la");+ expect(shell.textContent).toContain("a.py");+ expect(explore.textContent).toContain("SearchTODO in src");// The full receipt is available on demand.- fireEvent.click(within(shell).getByRole("button", { name: "Details" }));+ fireEvent.click(within(shell).getByRole("button", { name: /^Ran ls -la/ }));expect(within(shell).getByText("Input")).toBeTruthy();- expect(shell.textContent).toContain("a.py");- // More than the sentence could say, so the whole input is worth printing.- fireEvent.click(within(grep).getByRole("button", { name: "Details" }));- expect(within(grep).getByText("Input")).toBeTruthy();+ // More than the line could say, so the whole input is worth printing.+ fireEvent.click(within(explore).getByRole("button", { name: /^Explored/ }));+ expect(within(explore).getByText("Input")).toBeTruthy();});it("uses readable tool names, preserves canonical detail, and closes with usage", () => {@@ -835,19 +837,21 @@ describe("ChatStage (agent chat)", () => {]);useAgentChatStore.setState({ activeSessionId: "s9", timeline });render(<ChatStage />);- fireEvent.click(screen.getByRole("button", { name: /^Thought for 12s/ }));- const report = screen.getByTestId("trace-report");- const tools = Array.from(report.querySelectorAll<HTMLElement>("li[data-kind='action']"));- expect(tools[0].textContent).toContain("Ran the command Get-ChildItem -Path 'C:\\Users'.");- fireEvent.click(within(tools[0]).getByRole("button", { name: "Details" }));- expect(tools[0].textContent).toContain("PowerShell");- // An MCP call is named after its server.- expect(tools[1].textContent).toContain("GitHub");-- // Thinking with no readable text is no step of its own; its time is- // told in the overview.- expect(tools).toHaveLength(2);- expect(report.querySelector("[data-trace-overview]")?.textContent).toContain("8.6 s of that went into thinking.");+ const toggle = screen.getByRole("button", { name: /^Worked for 12s/ });+ // The folded line says what the turn did.+ expect(toggle.textContent).toContain("Ran a command and used GitHub · Create Issue");+ fireEvent.click(toggle);+ const shell = document.querySelector<HTMLElement>("[data-trace-entry='command']")!;+ expect(shell.textContent).toContain("Get-ChildItem -Path 'C:\\Users'");+ fireEvent.click(within(shell).getByRole("button", { name: /^Ran/ }));+ expect(shell.textContent).toContain("PowerShell");+ // An MCP call is named after its server, and wears its mark.+ const github = document.querySelector<HTMLElement>("[data-trace-entry='tool']")!;+ expect(github.textContent).toContain("GitHub");+ expect(github.textContent).toContain("#12");++ // Thinking with no readable text draws no line of its own.+ expect(document.querySelectorAll("[data-trace-entry='thought']")).toHaveLength(0);const footer = within(screen.getByTestId("work-trace")).getByRole("status");expect(footer.textContent).toContain("12s");diff --git a/jarvis/ui/web/frontend/src/components/home/TurnSteps.test.tsx b/jarvis/ui/web/frontend/src/components/home/TurnSteps.test.tsxindex d2d8cf2f86..9c5166db17 100644--- a/jarvis/ui/web/frontend/src/components/home/TurnSteps.test.tsx+++ b/jarvis/ui/web/frontend/src/components/home/TurnSteps.test.tsx@@ -8,7 +8,7 @@ it("keeps brief voice errors visible", () => {expect(traceWorthShowing(steps, 20, false)).toBe(true);render(<TurnSteps steps={steps} durationMs={20} />);// The finished trace folds into its report; the toggle says a step failed.- const toggle = screen.getByRole("button", { name: /1 not done/ });+ const toggle = screen.getByRole("button", { name: /1 failed/ });fireEvent.click(toggle);expect(screen.getByText(/Connection lost/)).toBeTruthy();});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsxindex 126ff701b7..0b824b917a 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx@@ -65,13 +65,13 @@ it("keeps live and interrupted conversation tools in the left lane", () => {expect(screen.getByText("I will send the mail next.")).toBeTruthy();expect(screen.queryByText("Interrupted without a result")).toBeNull();expect(screen.queryByText("Inspect archive.")).toBeNull();- fireEvent.click(screen.getByRole("button", { name: /^Thought for 4\.1s/ }));- // Opening the fold shows the whole written report in one tap: the reason- // in the model's words, the step, and that it never returned.- const report = screen.getByTestId("trace-report");- expect(report.textContent).toContain("Inspect archive.");- expect(report.textContent).toContain("Searched the files for archive.");- expect(report.textContent).toContain("It stopped before it returned a result.");+ fireEvent.click(screen.getByRole("button", { name: /^Worked for 4\.1s.*1 failed/ }));+ // Opening the fold shows the whole timeline in one tap: the model's words,+ // the call, and that it never returned.+ const lane2 = screen.getByTestId("work-trace").textContent!;+ expect(lane2).toContain("Inspect archive.");+ expect(lane2).toContain("Searcharchive");+ expect(lane2).toContain("Stopped before it finished");expect(container.querySelectorAll(".mx-auto")).toHaveLength(0);expect(screen.getByTestId("work-trace").className).toMatch(/self-start/);});@@ -86,12 +86,12 @@ it("folds a failure with the surrounding work, keeping only the reply out", () =expect(screen.queryByText("Upload failed")).toBeNull();expect(screen.getByText("I could not finish.")).toBeTruthy();expect(screen.queryByText("Report contents")).toBeNull();- fireEvent.click(screen.getByRole("button", { name: /^Thought for 2\.0s.*1 not done/ }));- // The failure reads as a sentence with the tool's own reason.- expect(screen.getByText("It failed: Upload failed.")).toBeTruthy();- // The raw output stays one tap further, under the step's details.+ fireEvent.click(screen.getByRole("button", { name: /^Worked for 2\.0s.*1 failed/ }));+ // The failure reads under its line with the tool's own reason.+ expect(screen.getByText("Failed: Upload failed")).toBeTruthy();+ // The raw output stays one tap further, under the line.expect(screen.queryByText("Report contents")).toBeNull();- fireEvent.click(screen.getAllByRole("button", { name: "Details" })[0]);+ fireEvent.click(screen.getByRole("button", { name: /^Explored/ }));expect(screen.getByText("Report contents")).toBeTruthy();});@@ -104,9 +104,8 @@ it("folds failures but keeps pending approvals visible in the conversation styleexpect(screen.queryByText("Delivery failed")).toBeNull();expect(screen.getByText("Send this message?")).toBeTruthy();expect(screen.getByRole("button", { name: "Approve" })).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: /^Thought for 1\.0s/ }));- expect(screen.getByText("It failed: Delivery failed.")).toBeTruthy();- expect(screen.getByText("It is waiting for your approval.")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: /^Worked for 1\.0s/ }));+ expect(screen.getByText("Failed: Delivery failed")).toBeTruthy();// The approval card survives opening the fold — it still needs a tap.expect(screen.getByRole("button", { name: "Approve" })).toBeTruthy();});@@ -127,29 +126,29 @@ it("folds successful work and post-reply errors behind one toggle without reordeconst tool: ToolBlock = { kind: "tool", callId: "a", name: "read_file", input: { path: "report.csv" }, output: "Report contents", isError: false, durationMs: 100, approval: null, startedMs: 0 };const blocks = [tool, { ...tool, callId: "b", name: "write_file" }, { kind: "text" as const, id: "reply", text: "Your report is ready." }, { ...tool, callId: "error", isError: true, output: "Upload failed" }];const { rerender } = render(<WorkTrace conversation status="running" startedMs={0} durationMs={null} blocks={blocks} />);- const activity = screen.getByRole("button", { name: "Reading files Creating files" });- expect(activity.getAttribute("aria-expanded")).toBe("true");- fireEvent.click(activity);- fireEvent.click(activity);+ // While it runs, finished calls already read as their timeline lines.+ expect(screen.getByRole("button", { name: /^Explored/ })).toBeTruthy();+ expect(screen.getByRole("button", { name: /^Created report\.csv/ })).toBeTruthy();rerender(<WorkTrace conversation status="done" startedMs={0} durationMs={1000} blocks={blocks} />);- expect(screen.queryByRole("button", { name: "Reading files Creating files" })).toBeNull();- expect(screen.queryByRole("button", { name: /Write file/ })).toBeNull();+ expect(screen.queryByRole("button", { name: /^Explored/ })).toBeNull();expect(screen.getByText("Your report is ready.")).toBeTruthy();expect(screen.queryByText("Upload failed")).toBeNull();expect(screen.queryByText("Report contents")).toBeNull();- fireEvent.click(screen.getByRole("button", { name: /^Thought for 1\.0s/ }));- // One tap opens the whole report: every step in order, the post-reply+ const toggle = screen.getByRole("button", { name: /^Worked for 1\.0s/ });+ expect(toggle.textContent).toContain("Read 2 files and created a file");+ fireEvent.click(toggle);+ // One tap opens the whole timeline: every call in order, the post-reply// error included, with the reply kept where it was.- const report = screen.getByTestId("trace-report");- const text = report.textContent ?? "";- expect(text.indexOf("Read report.csv.")).toBeGreaterThanOrEqual(0);- expect(text.indexOf("Read report.csv.")).toBeLessThan(text.indexOf("Wrote report.csv."));- expect(text).toContain("It failed: Upload failed.");+ const text = screen.getByTestId("work-trace").textContent ?? "";+ expect(text.indexOf("Readreport.csv")).toBeGreaterThanOrEqual(0);+ expect(text.indexOf("Readreport.csv")).toBeLessThan(text.indexOf("Createdreport.csv"));+ expect(text).toContain("Failed: Upload failed");expect(screen.getAllByText("Your report is ready.")).toHaveLength(1);- // Each step's raw call stays tappable on its own.- fireEvent.click(screen.getAllByRole("button", { name: "Details" })[0]);+ // Each line's raw call stays tappable on its own.+ const explored = screen.getByRole("button", { name: /^Explored/ });+ fireEvent.click(explored);expect(screen.getAllByText("Report contents").length).toBeGreaterThan(0);- fireEvent.click(screen.getAllByRole("button", { name: "Details" })[0]);+ fireEvent.click(explored);expect(screen.queryAllByText("Report contents")).toHaveLength(0);});@@ -174,7 +173,7 @@ it("hides intermediate replies behind one thought toggle once the turn completesexpect(screen.queryByText("I will inspect the files first.")).toBeNull();expect(screen.queryByText("Used tools")).toBeNull();expect(screen.getByText("The report is ready.")).toBeTruthy();- const toggle = screen.getByRole("button", { name: /^Thought for 4\.0s/ });+ const toggle = screen.getByRole("button", { name: /^Worked for 4\.0s/ });expect(toggle.getAttribute("aria-expanded")).toBe("false");fireEvent.click(toggle);expect(toggle.getAttribute("aria-expanded")).toBe("true");diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 3f21f6e8be..f4ad1eaae7 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -5608,117 +5608,60 @@},"trace_report": {"locale": "de",- "title": "So ist diese Antwort entstanden",- "quote": "„{text}“",- "copy": "Als Text kopieren",+ "copy": "Kopieren","copied": "Kopiert","copy_failed": "Kopieren fehlgeschlagen",- "details": "Details","show_more": "Mehr anzeigen","show_less": "Weniger anzeigen",- "steps_one": "1 Schritt",- "steps_other": "{count} Schritte",- "problems": "{count} nicht erledigt",- "lead_one": "Diese Antwort hat {duration} und einen Schritt gebraucht.",- "lead_other": "Diese Antwort hat {duration} und {count} Schritte gebraucht.",- "lead_nodur_one": "Diese Antwort hat einen Schritt gebraucht.",- "lead_nodur_other": "Diese Antwort hat {count} Schritte gebraucht.",- "lead_thinking": "Diese Antwort hat {duration} Nachdenken gebraucht.",- "thinking_share": "Davon gingen {duration} ins Nachdenken.",- "did_sentence": "Dabei: {list}.",- "model": "Modell: {model}.",- "turn_stopped": "Der Durchlauf wurde gestoppt, bevor er fertig war.",- "turn_failed": "Der Durchlauf endete mit einem Fehler.",- "did": {- "command_one": "einen Befehl ausgeführt",- "command_other": "{count} Befehle ausgeführt",+ "worked_for": "{duration} gearbeitet",+ "worked": "Gearbeitet",+ "thought_for": "{duration} nachgedacht",+ "thought": "Nachgedacht",+ "failed_count": "{count} fehlgeschlagen",+ "sum": {"read_one": "eine Datei gelesen","read_other": "{count} Dateien gelesen",- "edit_one": "eine Datei bearbeitet",- "edit_other": "{count} Änderungen gemacht",- "write_one": "eine Datei geschrieben",- "write_other": "{count} Dateien geschrieben","list_one": "einen Ordner aufgelistet","list_other": "{count} Ordner aufgelistet","search_one": "eine Suche ausgeführt","search_other": "{count} Suchen ausgeführt",- "question_one": "dir eine Frage gestellt",- "question_other": "dir {count} Fragen gestellt",+ "command_one": "einen Befehl ausgeführt",+ "command_other": "{count} Befehle ausgeführt",+ "edit_one": "eine Datei bearbeitet",+ "edit_other": "{count} Änderungen gemacht",+ "write_one": "eine Datei erstellt",+ "write_other": "{count} Dateien erstellt","used": "{list} verwendet"},- "outcome": {- "ok_one": "Der Schritt hat geklappt.",- "ok_other": "Alle Schritte haben geklappt.",- "failed_one": "Ein Schritt ist fehlgeschlagen.",- "failed_other": "{count} Schritte sind fehlgeschlagen.",- "denied_one": "Ein Schritt durfte nicht laufen.",- "denied_other": "{count} Schritte durften nicht laufen.",- "declined_one": "Du hast einen Schritt abgelehnt.",- "declined_other": "Du hast {count} Schritte abgelehnt.",- "interrupted_one": "Ein Schritt brach ab, bevor er ein Ergebnis lieferte.",- "interrupted_other": "{count} Schritte brachen ab, bevor sie ein Ergebnis lieferten."- },- "step": {- "command": "Hat den Befehl {detail} ausgeführt.",- "command_plain": "Hat einen Befehl ausgeführt.",- "read": "Hat {detail} gelesen.",- "read_plain": "Hat eine Datei gelesen.",- "edit": "Hat {detail} bearbeitet.",- "edit_plain": "Hat eine Datei bearbeitet.",- "write": "Hat {detail} geschrieben.",- "write_plain": "Hat eine Datei geschrieben.",- "list": "Hat {detail} aufgelistet.",- "list_plain": "Hat Dateien aufgelistet.",- "search": "Hat die Dateien nach {detail} durchsucht.",- "search_plain": "Hat die Dateien durchsucht.",- "question": "Hat dich gefragt: {detail}",- "question_plain": "Hat dir eine Frage gestellt.",- "service": "Hat {tool} mit „{detail}“ verwendet.",- "service_plain": "Hat {tool} verwendet.",- "tool": "Hat das Werkzeug {tool} mit „{detail}“ verwendet.",- "tool_plain": "Hat das Werkzeug {tool} verwendet.",- "wiki": "Hat im Wiki nach „{detail}“ gesucht.",- "wiki_plain": "Hat im Wiki nachgesehen.",- "wiki_write": "Hat „{detail}“ ins Wiki geschrieben.",- "wiki_write_plain": "Hat ins Wiki geschrieben.",- "artifact": "Hat das Artefakt „{detail}“ erstellt.",- "artifact_plain": "Hat ein Artefakt erstellt.",- "skill": "Hat den Skill „{detail}“ ausgeführt.",- "skill_plain": "Hat einen Skill ausgeführt.",- "skill_create": "Hat den Skill „{detail}“ erstellt.",- "skill_create_plain": "Hat einen Skill erstellt.",- "web": "Hat im Web nach „{detail}“ gesucht.",- "web_plain": "Hat im Web gesucht.",- "screen": "Hat sich den Bildschirm angesehen ({detail}).",- "screen_plain": "Hat sich den Bildschirm angesehen.",- "screen_recall": "Hat sich erinnert, was zu „{detail}“ auf dem Bildschirm war.",- "screen_recall_plain": "Hat sich erinnert, was auf dem Bildschirm war.",- "control": "Hat den Bildschirm gesteuert: „{detail}“.",- "control_plain": "Hat den Bildschirm gesteuert.",- "navigate": "Hat {detail} geöffnet.",- "navigate_plain": "Hat eine Seite geöffnet.",- "app": "Hat die App „{detail}“ geöffnet.",- "app_plain": "Hat eine App geöffnet.",- "memory": "Hat das Gedächtnis genutzt: „{detail}“.",- "memory_plain": "Hat das Gedächtnis genutzt.",- "memory_update": "Hat das Gedächtnis aktualisiert: „{detail}“.",- "memory_update_plain": "Hat das Gedächtnis aktualisiert.",- "profile": "Hat das Profilfeld „{detail}“ aktualisiert.",- "profile_plain": "Hat das Profil aktualisiert.",- "contact": "Hat den Kontakt „{detail}“ nachgeschlagen.",- "contact_plain": "Hat einen Kontakt nachgeschlagen.",- "call": "Hat {detail} angerufen.",- "call_plain": "Hat einen Anruf gestartet.",- "worker": "Hat eine Aufgabe an einen Worker gegeben: „{detail}“.",- "worker_plain": "Hat eine Aufgabe an einen Worker gegeben.",- "model": "Hat das Modell auf {detail} umgestellt.",- "model_plain": "Hat das Modell umgestellt.",- "mcp_admin": "Hat den MCP-Server „{detail}“ verwaltet.",- "mcp_admin_plain": "Hat einen MCP-Server verwaltet.",- "settings": "Hat die Einstellungen zu „{detail}“ gelesen.",- "settings_plain": "Hat die Einstellungen gelesen.",- "verify": "Hat {detail} geprüft.",- "verify_plain": "Hat eine Prüfung ausgeführt."+ "entry": {+ "explored": "Erkundet",+ "read": "Gelesen",+ "list": "Aufgelistet",+ "search": "Gesucht",+ "search_in": "{pattern} in {path}",+ "ran": "Ausgeführt",+ "edited": "Bearbeitet",+ "created": "Erstellt",+ "more_one": "… +1 Zeile",+ "more_other": "… +{count} Zeilen"+ },+ "status": {+ "failed": "Fehlgeschlagen",+ "blocked": "Blockiert",+ "declined": "Von dir abgelehnt",+ "interrupted": "Abgebrochen, bevor es fertig war"+ },+ "result": {+ "items_one": "1 Ergebnis",+ "items_other": "{count} Ergebnisse",+ "none": "Keine Ergebnisse"+ },+ "reason": {+ "rule": "eine Sicherheitsregel blockiert diese Aktion",+ "plan_mode": "im Planmodus ist nur Lesen erlaubt",+ "cancelled": "es wurde abgebrochen",+ "timeout": "niemand hat es rechtzeitig freigegeben",+ "no_approver": "es brauchte eine Freigabe und niemand war da, um sie zu geben"},"subject": {"wiki": "das Wiki",@@ -5743,40 +5686,28 @@"settings": "die Einstellungen","verify": "Prüfungen"},- "result": {- "none": "Es kam kein Ergebnis zurück.",- "items_one": "Es kam ein Eintrag zurück.",- "items_other": "Es kamen {count} Einträge zurück.",- "text": "Ergebnis: {text}.",- "named_none": "Es wurden keine Einträge in {what} gefunden.",- "named_items_one": "Es kam ein Eintrag in {what} zurück.",- "named_items_other": "Es kamen {count} Einträge in {what} zurück.",- "named_list": "Es kam eine Liste von {what} zurück.",- "fields": "Es kamen Daten mit {fields} zurück.",- "data": "Es kamen strukturierte Daten zurück — die Details zeigen sie.",- "diff": "{added} Zeilen hinzugefügt und {removed} entfernt.",- "read_one": "Sie war eine Zeile lang.",- "read_other": "Sie war {count} Zeilen lang.",- "found_one": "Es gab einen Treffer.",- "found_other": "Es gab {count} Treffer.",- "lines": "Es kamen {count} Zeilen zurück, beginnend mit {text}.",- "answered": "Du hast {text} geantwortet.",- "unanswered": "Die Frage blieb unbeantwortet.",- "waiting_answer": "Die Frage wartet auf deine Antwort.",- "pending": "Der Schritt wartet auf deine Freigabe.",- "refused": "Er lief nicht: {reason}.",- "declined": "Du hast ihn abgelehnt, deshalb lief er nicht.",- "interrupted": "Er brach ab, bevor er ein Ergebnis lieferte.",- "failed": "Er ist fehlgeschlagen: {reason}",- "failed_plain": "Er ist ohne Begründung fehlgeschlagen."- },- "reason": {- "rule": "eine Sicherheitsregel blockiert diese Aktion",- "plan_mode": "im Planmodus ist nur Lesen erlaubt",- "cancelled": "er wurde abgebrochen",- "timeout": "niemand hat ihn rechtzeitig freigegeben",- "no_approver": "er brauchte eine Freigabe und niemand war da, um sie zu geben",- "declined": "du hast ihn abgelehnt"+ "family": {+ "wiki": "Im Wiki gesucht",+ "wiki_write": "Ins Wiki geschrieben",+ "artifact": "Artefakt erstellt",+ "skill": "Skill ausgeführt",+ "skill_create": "Skill erstellt",+ "web": "Im Web gesucht",+ "screen": "Bildschirm angesehen",+ "screen_recall": "Bildschirmverlauf abgerufen",+ "control": "Bildschirm gesteuert",+ "navigate": "Geöffnet",+ "app": "App geöffnet",+ "memory": "Gedächtnis abgefragt",+ "memory_update": "Gedächtnis aktualisiert",+ "profile": "Profil aktualisiert",+ "contact": "Kontakt nachgeschlagen",+ "call": "Angerufen",+ "worker": "An einen Worker übergeben",+ "model": "Modell gewechselt",+ "mcp_admin": "MCP-Server verwaltet",+ "settings": "Einstellungen gelesen",+ "verify": "Geprüft"}},"chat_media": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 60ef64c152..dfe8b484c1 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -5641,117 +5641,60 @@},"trace_report": {"locale": "en",- "title": "How this answer came about",- "quote": "“{text}”",- "copy": "Copy as text",+ "copy": "Copy","copied": "Copied","copy_failed": "Could not copy",- "details": "Details","show_more": "Show more","show_less": "Show less",- "steps_one": "1 step",- "steps_other": "{count} steps",- "problems": "{count} not done",- "lead_one": "This answer took {duration} and one step.",- "lead_other": "This answer took {duration} and {count} steps.",- "lead_nodur_one": "This answer took one step.",- "lead_nodur_other": "This answer took {count} steps.",- "lead_thinking": "This answer took {duration} of thinking.",- "thinking_share": "{duration} of that went into thinking.",- "did_sentence": "Along the way it {list}.",- "model": "Model: {model}.",- "turn_stopped": "The turn was stopped before it finished.",- "turn_failed": "The turn ended with an error.",- "did": {- "command_one": "ran a command",- "command_other": "ran {count} commands",+ "worked_for": "Worked for {duration}",+ "worked": "Worked",+ "thought_for": "Thought for {duration}",+ "thought": "Thought",+ "failed_count": "{count} failed",+ "sum": {"read_one": "read a file","read_other": "read {count} files",- "edit_one": "edited a file",- "edit_other": "made {count} edits",- "write_one": "wrote a file",- "write_other": "wrote {count} files","list_one": "listed a folder","list_other": "listed {count} folders","search_one": "ran a search","search_other": "ran {count} searches",- "question_one": "asked you a question",- "question_other": "asked you {count} questions",+ "command_one": "ran a command",+ "command_other": "ran {count} commands",+ "edit_one": "edited a file",+ "edit_other": "made {count} edits",+ "write_one": "created a file",+ "write_other": "created {count} files","used": "used {list}"},- "outcome": {- "ok_one": "The step succeeded.",- "ok_other": "Every step succeeded.",- "failed_one": "One step failed.",- "failed_other": "{count} steps failed.",- "denied_one": "One step was not allowed to run.",- "denied_other": "{count} steps were not allowed to run.",- "declined_one": "You declined one step.",- "declined_other": "You declined {count} steps.",- "interrupted_one": "One step stopped before it returned a result.",- "interrupted_other": "{count} steps stopped before they returned a result."- },- "step": {- "command": "Ran the command {detail}.",- "command_plain": "Ran a command.",- "read": "Read {detail}.",- "read_plain": "Read a file.",- "edit": "Edited {detail}.",- "edit_plain": "Edited a file.",- "write": "Wrote {detail}.",- "write_plain": "Wrote a file.",- "list": "Listed {detail}.",- "list_plain": "Listed files.",- "search": "Searched the files for {detail}.",- "search_plain": "Searched the files.",- "question": "Asked you: {detail}",- "question_plain": "Asked you a question.",- "service": "Used {tool} with “{detail}”.",- "service_plain": "Used {tool}.",- "tool": "Used the tool {tool} with “{detail}”.",- "tool_plain": "Used the tool {tool}.",- "wiki": "Looked up “{detail}” in the wiki.",- "wiki_plain": "Looked something up in the wiki.",- "wiki_write": "Wrote “{detail}” to the wiki.",- "wiki_write_plain": "Wrote to the wiki.",- "artifact": "Created the artifact “{detail}”.",- "artifact_plain": "Created an artifact.",- "skill": "Ran the skill “{detail}”.",- "skill_plain": "Ran a skill.",- "skill_create": "Created the skill “{detail}”.",- "skill_create_plain": "Created a skill.",- "web": "Searched the web for “{detail}”.",- "web_plain": "Searched the web.",- "screen": "Looked at the screen ({detail}).",- "screen_plain": "Looked at the screen.",- "screen_recall": "Recalled what was on the screen about “{detail}”.",- "screen_recall_plain": "Recalled what was on the screen.",- "control": "Controlled the screen: “{detail}”.",- "control_plain": "Controlled the screen.",- "navigate": "Opened {detail}.",- "navigate_plain": "Opened a page.",- "app": "Opened the app “{detail}”.",- "app_plain": "Opened an app.",- "memory": "Used its memory: “{detail}”.",- "memory_plain": "Used its memory.",- "memory_update": "Updated memory: “{detail}”.",- "memory_update_plain": "Updated memory.",- "profile": "Updated the profile field “{detail}”.",- "profile_plain": "Updated the profile.",- "contact": "Looked up the contact “{detail}”.",- "contact_plain": "Looked up a contact.",- "call": "Called {detail}.",- "call_plain": "Placed a call.",- "worker": "Handed a task to a worker: “{detail}”.",- "worker_plain": "Handed a task to a worker.",- "model": "Switched the model to {detail}.",- "model_plain": "Switched the model.",- "mcp_admin": "Managed the MCP server “{detail}”.",- "mcp_admin_plain": "Managed an MCP server.",- "settings": "Read the settings for “{detail}”.",- "settings_plain": "Read the settings.",- "verify": "Checked {detail}.",- "verify_plain": "Ran a check."+ "entry": {+ "explored": "Explored",+ "read": "Read",+ "list": "List",+ "search": "Search",+ "search_in": "{pattern} in {path}",+ "ran": "Ran",+ "edited": "Edited",+ "created": "Created",+ "more_one": "… +1 line",+ "more_other": "… +{count} lines"+ },+ "status": {+ "failed": "Failed",+ "blocked": "Blocked",+ "declined": "You declined it",+ "interrupted": "Stopped before it finished"+ },+ "result": {+ "items_one": "1 result",+ "items_other": "{count} results",+ "none": "No results"+ },+ "reason": {+ "rule": "a safety rule blocks this action",+ "plan_mode": "plan mode only allows reading",+ "cancelled": "it was cancelled",+ "timeout": "nobody approved it in time",+ "no_approver": "it needed an approval and nobody was there to give it"},"subject": {"wiki": "the wiki",@@ -5776,40 +5719,28 @@"settings": "the settings","verify": "checks"},- "result": {- "none": "It returned no results.",- "items_one": "It returned one item.",- "items_other": "It returned {count} items.",- "text": "It returned {text}.",- "named_none": "It found no {what}.",- "named_items_one": "It returned one entry in {what}.",- "named_items_other": "It returned {count} entries in {what}.",- "named_list": "It returned a list of {what}.",- "fields": "It returned data with {fields}.",- "data": "It returned structured data — the details show it.",- "diff": "Added {added} lines and removed {removed}.",- "read_one": "It was one line long.",- "read_other": "It was {count} lines long.",- "found_one": "It found one match.",- "found_other": "It found {count} matches.",- "lines": "It returned {count} lines, starting with {text}.",- "answered": "You answered {text}.",- "unanswered": "It was not answered.",- "waiting_answer": "It is waiting for your answer.",- "pending": "It is waiting for your approval.",- "refused": "It did not run: {reason}.",- "declined": "You declined it, so it did not run.",- "interrupted": "It stopped before it returned a result.",- "failed": "It failed: {reason}",- "failed_plain": "It failed without saying why."- },- "reason": {- "rule": "a safety rule blocks this action",- "plan_mode": "plan mode only allows reading",- "cancelled": "it was cancelled",- "timeout": "nobody approved it in time",- "no_approver": "it needed an approval and nobody was there to give it",- "declined": "you declined it"+ "family": {+ "wiki": "Searched the wiki",+ "wiki_write": "Wrote to the wiki",+ "artifact": "Created an artifact",+ "skill": "Ran a skill",+ "skill_create": "Created a skill",+ "web": "Searched the web",+ "screen": "Looked at the screen",+ "screen_recall": "Recalled the screen",+ "control": "Controlled the screen",+ "navigate": "Opened",+ "app": "Opened an app",+ "memory": "Checked memory",+ "memory_update": "Updated memory",+ "profile": "Updated the profile",+ "contact": "Looked up a contact",+ "call": "Called",+ "worker": "Handed off to a worker",+ "model": "Switched the model",+ "mcp_admin": "Managed an MCP server",+ "settings": "Read the settings",+ "verify": "Checked"}},"chat_media": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 2925e3c622..51b7d88c06 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -5608,117 +5608,60 @@},"trace_report": {"locale": "es",- "title": "Cómo se llegó a esta respuesta",- "quote": "«{text}»",- "copy": "Copiar como texto",+ "copy": "Copiar","copied": "Copiado","copy_failed": "No se pudo copiar",- "details": "Detalles","show_more": "Mostrar más","show_less": "Mostrar menos",- "steps_one": "1 paso",- "steps_other": "{count} pasos",- "problems": "{count} sin completar",- "lead_one": "Esta respuesta llevó {duration} y un paso.",- "lead_other": "Esta respuesta llevó {duration} y {count} pasos.",- "lead_nodur_one": "Esta respuesta llevó un paso.",- "lead_nodur_other": "Esta respuesta llevó {count} pasos.",- "lead_thinking": "Esta respuesta llevó {duration} de reflexión.",- "thinking_share": "{duration} de ese tiempo fueron de reflexión.",- "did_sentence": "Por el camino {list}.",- "model": "Modelo: {model}.",- "turn_stopped": "El turno se detuvo antes de terminar.",- "turn_failed": "El turno terminó con un error.",- "did": {- "command_one": "ejecutó un comando",- "command_other": "ejecutó {count} comandos",+ "worked_for": "Trabajó durante {duration}",+ "worked": "Trabajó",+ "thought_for": "Pensó durante {duration}",+ "thought": "Pensó",+ "failed_count": "{count} fallaron",+ "sum": {"read_one": "leyó un archivo","read_other": "leyó {count} archivos",- "edit_one": "editó un archivo",- "edit_other": "hizo {count} ediciones",- "write_one": "escribió un archivo",- "write_other": "escribió {count} archivos","list_one": "listó una carpeta","list_other": "listó {count} carpetas","search_one": "hizo una búsqueda","search_other": "hizo {count} búsquedas",- "question_one": "te hizo una pregunta",- "question_other": "te hizo {count} preguntas",+ "command_one": "ejecutó un comando",+ "command_other": "ejecutó {count} comandos",+ "edit_one": "editó un archivo",+ "edit_other": "hizo {count} ediciones",+ "write_one": "creó un archivo",+ "write_other": "creó {count} archivos","used": "usó {list}"},- "outcome": {- "ok_one": "El paso salió bien.",- "ok_other": "Todos los pasos salieron bien.",- "failed_one": "Un paso falló.",- "failed_other": "{count} pasos fallaron.",- "denied_one": "A un paso no se le permitió ejecutarse.",- "denied_other": "A {count} pasos no se les permitió ejecutarse.",- "declined_one": "Rechazaste un paso.",- "declined_other": "Rechazaste {count} pasos.",- "interrupted_one": "Un paso se detuvo antes de dar un resultado.",- "interrupted_other": "{count} pasos se detuvieron antes de dar un resultado."- },- "step": {- "command": "Ejecutó el comando {detail}.",- "command_plain": "Ejecutó un comando.",- "read": "Leyó {detail}.",- "read_plain": "Leyó un archivo.",- "edit": "Editó {detail}.",- "edit_plain": "Editó un archivo.",- "write": "Escribió {detail}.",- "write_plain": "Escribió un archivo.",- "list": "Listó {detail}.",- "list_plain": "Listó archivos.",- "search": "Buscó {detail} en los archivos.",- "search_plain": "Buscó en los archivos.",- "question": "Te preguntó: {detail}",- "question_plain": "Te hizo una pregunta.",- "service": "Usó {tool} con «{detail}».",- "service_plain": "Usó {tool}.",- "tool": "Usó la herramienta {tool} con «{detail}».",- "tool_plain": "Usó la herramienta {tool}.",- "wiki": "Buscó «{detail}» en la wiki.",- "wiki_plain": "Consultó la wiki.",- "wiki_write": "Escribió «{detail}» en la wiki.",- "wiki_write_plain": "Escribió en la wiki.",- "artifact": "Creó el artefacto «{detail}».",- "artifact_plain": "Creó un artefacto.",- "skill": "Ejecutó la habilidad «{detail}».",- "skill_plain": "Ejecutó una habilidad.",- "skill_create": "Creó la habilidad «{detail}».",- "skill_create_plain": "Creó una habilidad.",- "web": "Buscó «{detail}» en la web.",- "web_plain": "Buscó en la web.",- "screen": "Miró la pantalla ({detail}).",- "screen_plain": "Miró la pantalla.",- "screen_recall": "Recordó lo que había en pantalla sobre «{detail}».",- "screen_recall_plain": "Recordó lo que había en la pantalla.",- "control": "Controló la pantalla: «{detail}».",- "control_plain": "Controló la pantalla.",- "navigate": "Abrió {detail}.",- "navigate_plain": "Abrió una página.",- "app": "Abrió la app «{detail}».",- "app_plain": "Abrió una app.",- "memory": "Usó su memoria: «{detail}».",- "memory_plain": "Usó su memoria.",- "memory_update": "Actualizó la memoria: «{detail}».",- "memory_update_plain": "Actualizó la memoria.",- "profile": "Actualizó el campo de perfil «{detail}».",- "profile_plain": "Actualizó el perfil.",- "contact": "Buscó el contacto «{detail}».",- "contact_plain": "Buscó un contacto.",- "call": "Llamó a {detail}.",- "call_plain": "Hizo una llamada.",- "worker": "Le pasó una tarea a un worker: «{detail}».",- "worker_plain": "Le pasó una tarea a un worker.",- "model": "Cambió el modelo a {detail}.",- "model_plain": "Cambió el modelo.",- "mcp_admin": "Gestionó el servidor MCP «{detail}».",- "mcp_admin_plain": "Gestionó un servidor MCP.",- "settings": "Leyó la configuración de «{detail}».",- "settings_plain": "Leyó la configuración.",- "verify": "Comprobó {detail}.",- "verify_plain": "Hizo una comprobación."+ "entry": {+ "explored": "Exploró",+ "read": "Leyó",+ "list": "Listó",+ "search": "Buscó",+ "search_in": "{pattern} en {path}",+ "ran": "Ejecutó",+ "edited": "Editó",+ "created": "Creó",+ "more_one": "… +1 línea",+ "more_other": "… +{count} líneas"+ },+ "status": {+ "failed": "Falló",+ "blocked": "Bloqueado",+ "declined": "Lo rechazaste",+ "interrupted": "Se detuvo antes de terminar"+ },+ "result": {+ "items_one": "1 resultado",+ "items_other": "{count} resultados",+ "none": "Sin resultados"+ },+ "reason": {+ "rule": "una regla de seguridad bloquea esta acción",+ "plan_mode": "el modo plan solo permite leer",+ "cancelled": "se canceló",+ "timeout": "nadie lo aprobó a tiempo",+ "no_approver": "necesitaba una aprobación y no había nadie para darla"},"subject": {"wiki": "la wiki",@@ -5743,40 +5686,28 @@"settings": "la configuración","verify": "comprobaciones"},- "result": {- "none": "No devolvió resultados.",- "items_one": "Devolvió un elemento.",- "items_other": "Devolvió {count} elementos.",- "text": "Devolvió {text}.",- "named_none": "No encontró nada en {what}.",- "named_items_one": "Devolvió un elemento en {what}.",- "named_items_other": "Devolvió {count} elementos en {what}.",- "named_list": "Devolvió una lista de {what}.",- "fields": "Devolvió datos con {fields}.",- "data": "Devolvió datos estructurados; los detalles los muestran.",- "diff": "Añadió {added} líneas y quitó {removed}.",- "read_one": "Tenía una línea.",- "read_other": "Tenía {count} líneas.",- "found_one": "Encontró una coincidencia.",- "found_other": "Encontró {count} coincidencias.",- "lines": "Devolvió {count} líneas, empezando por {text}.",- "answered": "Respondiste {text}.",- "unanswered": "No se respondió.",- "waiting_answer": "Está esperando tu respuesta.",- "pending": "Está esperando tu aprobación.",- "refused": "No se ejecutó: {reason}.",- "declined": "Lo rechazaste, así que no se ejecutó.",- "interrupted": "Se detuvo antes de dar un resultado.",- "failed": "Falló: {reason}",- "failed_plain": "Falló sin decir por qué."- },- "reason": {- "rule": "una regla de seguridad bloquea esta acción",- "plan_mode": "el modo plan solo permite leer",- "cancelled": "se canceló",- "timeout": "nadie lo aprobó a tiempo",- "no_approver": "necesitaba una aprobación y no había nadie para darla",- "declined": "lo rechazaste"+ "family": {+ "wiki": "Buscó en la wiki",+ "wiki_write": "Escribió en la wiki",+ "artifact": "Creó un artefacto",+ "skill": "Ejecutó una habilidad",+ "skill_create": "Creó una habilidad",+ "web": "Buscó en la web",+ "screen": "Miró la pantalla",+ "screen_recall": "Recordó la pantalla",+ "control": "Controló la pantalla",+ "navigate": "Abrió",+ "app": "Abrió una app",+ "memory": "Consultó la memoria",+ "memory_update": "Actualizó la memoria",+ "profile": "Actualizó el perfil",+ "contact": "Buscó un contacto",+ "call": "Llamó",+ "worker": "Lo pasó a un worker",+ "model": "Cambió el modelo",+ "mcp_admin": "Gestionó un servidor MCP",+ "settings": "Leyó la configuración",+ "verify": "Comprobó"}},"chat_media": {