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): tell a finished turn's work as a written report
rubenluetke10-beepe7a110d237dd
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsxindex 7224c3dcbf..ff6e9e8cf4 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx@@ -14,7 +14,10 @@ afterEach(() => { cleanup(); seq = 0; });it("replays persisted events through the new shared trace", () => {draw([ev("turn_started", { turn_id: "t1" }), ev("tool_call", { turn_id: "t1", call_id: "c1", name: "list_dir", input: { path: "src" } }), ev("tool_result", { turn_id: "t1", call_id: "c1", output: "index.ts", duration_ms: 800 }), ev("turn_finished", { turn_id: "t1", status: "done" })]);expect(screen.getByTestId("work-trace")).toBeTruthy();- expect(screen.getByRole("button", { name: /List files/ })).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.");});describe("the person's turn with files", () => {const SHOT = {diff --git a/jarvis/ui/web/frontend/src/components/agentchat/TraceReport.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/TraceReport.test.tsxnew file mode 100644index 0000000000..78fa767b6d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/TraceReport.test.tsx@@ -0,0 +1,46 @@+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";+import { afterEach, expect, it } from "vitest";+import { VoiceWorkTrace } from "./VoiceWorkTrace";+import type { ThinkingStep } from "@/lib/thinkingSteps";++afterEach(cleanup);++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", () => {+ 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." }),+ step({ id: "w", detail: "wiki-recall", args: { query: "Urlaub 2026" }, result: '{"pages": [{"title": "Urlaub"}]}', durationMs: 49 }),+ 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.+ 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" }));+ expect(within(wiki).getByText("Input")).toBeTruthy();+ expect(screen.getByRole("button", { name: "Copy as text" })).toBeTruthy();+});++it("shows no report for a turn with nothing to tell", () => {+ 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/TraceReport.tsx b/jarvis/ui/web/frontend/src/components/agentchat/TraceReport.tsxnew file mode 100644index 0000000000..909badb298--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/TraceReport.tsx@@ -0,0 +1,145 @@+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/VoiceWorkTrace.tsx b/jarvis/ui/web/frontend/src/components/agentchat/VoiceWorkTrace.tsxindex 93cb054bfb..2d0ac34136 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/VoiceWorkTrace.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/VoiceWorkTrace.tsx@@ -1,31 +1,61 @@import { useMemo } from "react";import { useT } from "@/i18n";-import type { ThinkingStep } from "@/lib/thinkingSteps";-import type { TurnBlock } from "./reduce";+import { traceModel, type ThinkingStep } from "@/lib/thinkingSteps";+import type { ToolBlock, TurnBlock } from "./reduce";import { WorkTrace } from "./WorkTrace";+function toolBlock(step: ThinkingStep, name: string, input: unknown): ToolBlock {+ return {+ kind: "tool", callId: step.id, name, input,+ output: step.error ?? step.result ?? (step.status === "active" ? null : ""),+ isError: step.status === "error", durationMs: step.durationMs ?? null,+ startedMs: step.startedTs,+ // A refused call is told as refused, never as a call that ran and failed.+ approval: step.denied ? { approvalId: "", summary: step.error ?? "", decision: "deny" } : null,+ };+}++/**+ * Jarvis's own reasoning steps (voice, the history) as trace blocks.+ *+ * The brain call is the turn itself, not a step: it names the model in the+ * report and draws no row (it used to become an empty "Thought" row on+ * every turn). Computer-use and worker steps become the tool families that+ * describe them, so the report says "Controlled the screen" and "Handed a+ * task to a worker" instead of quoting a status label.+ */+export function stepsToBlocks(steps: ThinkingStep[], live: boolean, label: (key: string) => string): TurnBlock[] {+ const blocks: TurnBlock[] = [];+ for (const step of steps) {+ if (step.kind === "brain") continue;+ if (step.kind === "tool") {+ blocks.push(toolBlock(step, step.detail || label(step.labelKey), step.args));+ } else if (step.kind === "note" && step.status === "error") {+ // A note that failed is a step that failed, counted and told as one.+ blocks.push(toolBlock(step, label(step.labelKey), step.detail ? { text: step.detail } : {}));+ } else if (step.kind === "thought" || step.kind === "note") {+ blocks.push({+ kind: "reasoning", id: step.id, text: step.detail ?? "",+ durationMs: step.durationMs ?? null, live: live && step.status === "active", startedMs: step.startedTs,+ });+ } else if (step.kind === "computer") {+ blocks.push(toolBlock(step, "computer_use", step.detail ? { target: step.detail } : {}));+ } else {+ blocks.push(toolBlock(step, "spawn_worker", step.detail ? { task: step.detail } : {}));+ }+ }+ return blocks;+}+/** Adapt existing voice receipts without changing their persisted contract. */export function VoiceWorkTrace({ steps, live = false, durationMs, className }: {steps: ThinkingStep[]; live?: boolean; durationMs?: number; className?: string;}) {const t = useT();- const blocks = useMemo(() => steps.map((step): TurnBlock => {- if (step.kind === "tool") return {- kind: "tool", callId: step.id, name: step.detail || t(step.labelKey), input: step.args,- output: step.error ?? step.result ?? (step.status === "active" ? null : ""),- isError: step.status === "error", durationMs: step.durationMs ?? null,- startedMs: step.startedTs, approval: null,- };- if (step.kind === "thought" || step.kind === "brain") return {- kind: "reasoning", id: step.id, text: step.kind === "thought" ? step.detail ?? "" : "",- durationMs: step.durationMs ?? null, live: live && step.status === "active", startedMs: step.startedTs,- };- // Non-tool actions keep their real error and status, never a fabricated success.- return { kind: "tool", callId: step.id, name: t(step.labelKey), input: step.detail,- output: step.error ?? step.result ?? (step.status === "active" ? null : ""),- isError: step.status === "error", durationMs: step.durationMs ?? null,- startedMs: step.startedTs, approval: null };- }), [steps, live, t]);- return <WorkTrace blocks={blocks} status={live ? "running" : steps.some(step => step.status === "error") ? "error" : "done"}- startedMs={steps[0]?.startedTs ?? Date.now()} durationMs={durationMs ?? null} className={className} companion />;+ const blocks = useMemo(() => stepsToBlocks(steps, live, t), [steps, live, t]);+ // A step that failed is told in the report; the turn itself still ended —+ // 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 />;}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.css b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.cssindex fc08cdf279..0309394090 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.css+++ b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.css@@ -144,3 +144,71 @@animation: none;}}++/* ── 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;+}+.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));+}+/* A long reason folds with a fade at its foot, so it reads as "more below". */+.trace-report-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 eeee47dbc7..d4f4171b6c 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.test.tsx@@ -11,12 +11,14 @@ const tool = (id: string, over: Partial<ToolBlock> = {}): ToolBlock => ({const thought: TurnBlock = { kind: "reasoning", id: "reason", text: "**Check** the input.", live: false, durationMs: 8000, startedMs: 1000 };const reply = (id: string, text: string): TextBlock => ({ kind: "text", id, text });const props = { startedMs: 1000, durationMs: 12000, status: "done" as TurnStatus };+/** Finished rows are drawn by the classic look; the rail writes a report. */+const rows = { ...props, look: "classic" as const };afterEach(() => { cleanup(); vi.useRealTimers(); });describe("work trace", () => {it("summarizes integrations and mutations in first-use order with original logos", () => {const blocks = [tool("linear", {name:"mcp__codex_apps__linear_list_issues"}), tool("edit", {name:"apply_patch"}), tool("shell", {name:"exec_command"}), tool("again", {name:"linear/get_issue"})];- const {container} = render(<WorkTrace {...props} blocks={blocks} />);+ const {container} = render(<WorkTrace {...rows} blocks={blocks} />);const summary = screen.getByRole("button", {name:"Used Linear Edited files Ran commands"});expect(summary.getAttribute("aria-expanded")).toBe("false");expect(summary.querySelector("img, [data-logo]")).toBeTruthy();@@ -41,7 +43,7 @@ describe("work trace", () => {const blocks = [tool("a",{name:"linear/get_issue"}),tool("b",{name:"exec_command"})];const {rerender} = render(<WorkTrace {...props} status="running" blocks={blocks} />);expect(screen.getByRole("button",{name:"Using Linear Running commands"}).getAttribute("aria-expanded")).toBe("true");- rerender(<WorkTrace {...props} blocks={blocks} />);+ rerender(<WorkTrace {...rows} blocks={blocks} />);expect(screen.getByRole("button",{name:"Used Linear Ran commands"}).getAttribute("aria-expanded")).toBe("false");});@@ -57,6 +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/ }));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"));@@ -67,7 +70,7 @@ describe("work trace", () => {it("groups fourteen successful reads and expands their full receipts", () => {const blocks = Array.from({length: 14}, (_, i) => tool(`file${i}`));- render(<WorkTrace {...props} blocks={blocks} />);+ render(<WorkTrace {...rows} blocks={blocks} />);const group = screen.getByRole("button", { name: "Read 14 files" });expect(group.getAttribute("aria-expanded")).toBe("false");expect(screen.queryByText("file0.ts")).toBeNull();@@ -89,15 +92,19 @@ describe("work trace", () => {const group = screen.getByRole("button", { name: "Read 2 files" });fireEvent.click(group); fireEvent.click(group);expect(group.getAttribute("aria-expanded")).toBe("true");- rerender(<WorkTrace {...props} blocks={blocks} />);- expect(group.getAttribute("aria-expanded")).toBe("false");+ rerender(<WorkTrace {...rows} blocks={blocks} />);+ expect(screen.getByRole("button", { name: "Read 2 files" }).getAttribute("aria-expanded")).toBe("false");});it("keeps errors and pending approval visible beside folded success", () => {render(<WorkTrace {...props} blocks={[tool("a"),tool("b"),tool("err",{isError:true,output:"Permission denied"}),tool("approval",{output:null,approval:{approvalId:"ap",summary:"Delete generated files?",decision:null}})]} onDecide={() => undefined} />);- expect(screen.getByText("Permission denied")).toBeTruthy();+ // The approval stays actionable beside the folded report; the toggle+ // 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();+ expect(screen.getByRole("button", { name: "Approve" })).toBeTruthy();});it.each(["allow", "allow_always", "deny"] as const)("submits %s exactly once and reports failures", async decision => {@@ -122,16 +129,21 @@ describe("work trace", () => {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:/Edit/}));+ 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" }));expect(screen.getByLabelText("Changes").textContent).toContain("− oldValue");expect(screen.getByLabelText("Changes").textContent).toContain("+ newValue");expect(screen.getByText("File updated")).toBeTruthy();});it.each(["cancelled", "error"] as const)("does not leave tools spinning after %s", status => {- const {container} = render(<WorkTrace {...props} status={status} blocks={[tool("a",{output:null})]} />);+ 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();+ 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();});it("updates the live clock and releases timers at completion", () => {@@ -144,8 +156,12 @@ describe("work trace", () => {});it("does not interpret tool output as HTML", () => {- const {container} = render(<WorkTrace {...props} blocks={[tool("a",{output:'<img src=x onerror=alert(1)>'})]} />);- fireEvent.click(screen.getByRole("button", {name:/Read file/}));+ 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.+ 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('img')).toBeNull();expect(screen.getByText('<img src=x onerror=alert(1)>')).toBeTruthy();});@@ -160,9 +176,12 @@ describe("work trace", () => {});it.each(["RunCommand", "RunShellCommand", "run_shell"])("shows the short duration beside a readable %s label", name => {- render(<WorkTrace {...props} blocks={[tool("shell", { name, input: { command: "read skill instructions" }, durationMs: 49 })]} />);+ const { rerender } = render(<WorkTrace {...rows} blocks={[tool("shell", { name, input: { command: "read skill instructions" }, durationMs: 49 })]} />);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();});it("keeps the last reply visible and treats earlier text as foldable work", () => {@@ -186,17 +205,17 @@ describe("work trace", () => {describe("rail look", () => {it("threads thoughts, tools and the state line on one rail by default", () => {- const { container } = render(<WorkTrace {...props} blocks={[thought, tool("a", { name: "exec_command" })]} />);+ const { container } = render(<WorkTrace {...props} status="running" blocks={[thought, tool("a", { name: "exec_command" })]} />);expect(screen.getByTestId("work-trace").getAttribute("data-look")).toBe("rail");const rails = container.querySelectorAll(".trace-rail");expect(rails).toHaveLength(1);const steps = rails[0].querySelectorAll(":scope > .trace-step");expect(steps).toHaveLength(3);- expect(steps[2].querySelector("[role='status']")?.textContent).toContain("Done");+ expect(steps[2].querySelector("[role='status']")?.textContent).toContain("Working");});it("breaks the rail around a reply so narration stands on its own", () => {- const { container } = render(<WorkTrace {...props} blocks={[tool("a", { name: "exec_command" }), reply("mid", "Halfway there."), tool("b", { name: "exec_command" })]} />);+ const { container } = render(<WorkTrace {...props} status="running" blocks={[tool("a", { name: "exec_command" }), reply("mid", "Halfway there."), tool("b", { name: "exec_command", output: null })]} />);const rails = container.querySelectorAll(".trace-rail");expect(rails).toHaveLength(2);expect(rails[0].textContent).not.toContain("Halfway there.");@@ -245,7 +264,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: /^Thought 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 3b5eb4112e..668661af85 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx@@ -16,6 +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 "./WorkTrace.css";export type Decide = (id: string, decision: ApprovalDecision) => void | Promise<void>;@@ -525,15 +527,19 @@ function traceLogos(blocks: TurnBlock[]): ToolChoice[] {}/** Small chevron that hides finished work so the reply can stand alone. */-function ConversationWorkFold({ durationMs, attention, blocks, children }: {+function ConversationWorkFold({ durationMs, attention, blocks, children, narrative, 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;}) {const t = useT();const rail = useRail();const id = useId();- const [open, setOpen] = useState(false);+ const [open, setOpen] = useState(initiallyOpen);// Counts openings so inner disclosures expand all at once, every time.- const [seq, setSeq] = useState(0);+ 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))@@ -550,6 +556,14 @@ function ConversationWorkFold({ durationMs, attention, blocks, children }: {{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> : null}<ChevronRight aria-hidden className={cn("h-3 w-3 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"@@ -625,6 +639,8 @@ function withoutQuestionPolls(blocks: TurnBlock[]): TurnBlock[] {return kept.length === blocks.length ? blocks : kept;}+const NO_BLOCKS: TurnBlock[] = [];+export function WorkTrace({ look = "rail", ...props }: WorkTraceProps & { look?: TraceLook }) {return <TraceLookContext.Provider value={look}><WorkTraceBody {...props} /></TraceLookContext.Provider>;}@@ -633,6 +649,8 @@ 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@@ -641,13 +659,16 @@ type WorkTraceProps = {companion?: boolean;};-function WorkTraceBody({ blocks: rawBlocks, status, startedMs, durationMs, error, onDecide, renderText, className, receipt, completionLabel, conversation = false, companion = false }: WorkTraceProps) {+function WorkTraceBody({ blocks: rawBlocks, status, startedMs, durationMs, error, onDecide, renderText, className, receipt, completionLabel, conversation = false, companion = false, model }: WorkTraceProps) {const t = useT();const rail = useRail();const blocks = useMemo(() => withoutQuestionPolls(rawBlocks), [rawBlocks]);const live = status === "running";const elapsed = useClock(startedMs, live);- const split = useMemo(() => conversation && !live ? splitConversationTurn(blocks) : null, [blocks, conversation, 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.+ 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// post-reply work — folds behind the "Thought for …" toggle. Pending@@ -665,6 +686,7 @@ 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);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";@@ -684,7 +706,7 @@ function WorkTraceBody({ blocks: rawBlocks, status, startedMs, durationMs, error// The state line is the thread's last node while work is under way (or// whenever the trace has no reply between it and the work); a finished// conversation turn closes with a quiet line under its reply instead.- const statusOnRail = !conversation || live;+ const statusOnRail = !fold && (!conversation || live);const petState = companion && working ? livePetState(blocks) : null;const statusLine = <div role="status" aria-live="polite" data-trace-status={outcome}className={cn("flex min-w-0 flex-wrap items-start gap-x-3 text-xs leading-6 text-muted-foreground",@@ -705,9 +727,15 @@ function WorkTraceBody({ blocks: rawBlocks, status, startedMs, durationMs, errorconst main = traceGroupItems({ groups, ...groupProps });const rest = restGroups ? traceGroupItems({ groups: restGroups, ...groupProps }) : [];const items: RailItem[] = fold- ? [{ key: "trace:fold", rail: false, node: <ConversationWorkFold durationMs={durationMs} blocks={fold.workAll}+ ? [{ key: "trace:fold", rail: false, node: <ConversationWorkFold durationMs={durationMs} blocks={fold.workAll} narrative={narrative}+ // A turn that ended without an answer (TurnTrace names it so) has+ // nothing to read but its work: the report 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>}>- <Rail items={[...main, ...(foldedError ? [errorItem(foldedError, "trace:folded-error")] : [])]} />+ <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}</ConversationWorkFold> }, ...rest]: main;if (visibleError) items.push(errorItem(visibleError, "trace:error"));@@ -742,6 +770,7 @@ 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/traceNarrative.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/traceNarrative.test.tsnew file mode 100644index 0000000000..3d3d35b982--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/traceNarrative.test.ts@@ -0,0 +1,204 @@+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.tsnew file mode 100644index 0000000000..1ade1e4e65--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/traceNarrative.ts@@ -0,0 +1,503 @@+/**+ * 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 a45aa62cbd..4a26fd1042 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");- expect(within(trace).getByRole("button", { name: "Thought for 1.0s" })).toBeTruthy();- expect(within(trace).getByRole("button", { name: "Thought for 4.0s" })).toBeTruthy();- const text = trace.textContent!;+ // 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!;expect(text.indexOf("First the port.")).toBeLessThan(text.indexOf("Get-NetTCPConnection"));expect(text.indexOf("Get-NetTCPConnection")).toBeLessThan(text.indexOf("It is listening."));});@@ -790,8 +790,9 @@ describe("ChatStage (agent chat)", () => {expect(outcome.textContent).toContain("448");// Only the output side reaches the receipt.expect(outcome.textContent).not.toContain("35.4k");- // The failure reads on the row itself, without opening anything.- expect(screen.getByText(/permission check failed for command/).textContent).toContain("permission check failed");+ // 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");// Nothing claims to still be working.expect(screen.queryByTestId("agent-turn-live")).toBeNull();});@@ -807,19 +808,16 @@ describe("ChatStage (agent chat)", () => {]);useAgentChatStore.setState({ activeSessionId: "s5", timeline });render(<ChatStage />);- const fold = screen.queryByTestId("conversation-work-fold");- if (fold) fireEvent.click(within(fold).getByRole("button"));- const activity = document.querySelector<HTMLElement>("[data-trace-summary]");- if (activity) fireEvent.click(within(activity).getByRole("button"));-- const [shell, grep] = Array.from(document.querySelectorAll<HTMLElement>("[data-trace-tool]"));- fireEvent.click(within(shell).getByRole("button"));+ 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.");// The full receipt is available on demand.+ fireEvent.click(within(shell).getByRole("button", { name: "Details" }));expect(within(shell).getByText("Input")).toBeTruthy();expect(shell.textContent).toContain("a.py");-- fireEvent.click(within(grep).getByRole("button"));- // More than the summary could say, so the whole input is worth printing.+ // 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();});@@ -837,22 +835,19 @@ describe("ChatStage (agent chat)", () => {]);useAgentChatStore.setState({ activeSessionId: "s9", timeline });render(<ChatStage />);- const fold = screen.queryByTestId("conversation-work-fold");- if (fold) fireEvent.click(within(fold).getByRole("button"));- const activity = document.querySelector<HTMLElement>("[data-trace-summary]");- if (activity) fireEvent.click(within(activity).getByRole("button"));-- const tools = Array.from(document.querySelectorAll<HTMLElement>("[data-trace-tool]"));- expect(tools[0].textContent).toContain("Run command");- fireEvent.click(within(tools[0]).getByRole("button"));+ 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");- expect(tools[0].textContent).toContain("Get-ChildItem");- // An MCP call is named after its server, and wears its mark.+ // An MCP call is named after its server.expect(tools[1].textContent).toContain("GitHub");- // Thinking with no readable text still shows its time and does not open.- const reasoning = screen.getByRole("button", {name: "Thought for 8.6s"});- expect(reasoning.hasAttribute("disabled")).toBe(true);+ // 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 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 282d328599..d2d8cf2f86 100644--- a/jarvis/ui/web/frontend/src/components/home/TurnSteps.test.tsx+++ b/jarvis/ui/web/frontend/src/components/home/TurnSteps.test.tsx@@ -1,4 +1,4 @@-import { cleanup, render, screen } from "@testing-library/react";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, expect, it } from "vitest";import { TurnSteps, formatThoughtDuration, traceWorthShowing } from "./TurnSteps";import type { ThinkingStep } from "@/lib/thinkingSteps";@@ -7,7 +7,10 @@ it("keeps brief voice errors visible", () => {const steps: ThinkingStep[] = [{ id: "s", kind: "note", status: "error", labelKey: "thinking.step_update", error: "Connection lost", startedTs: 0 }];expect(traceWorthShowing(steps, 20, false)).toBe(true);render(<TurnSteps steps={steps} durationMs={20} />);- expect(screen.getByText("Connection lost")).toBeTruthy();+ // The finished trace folds into its report; the toggle says a step failed.+ const toggle = screen.getByRole("button", { name: /1 not done/ });+ fireEvent.click(toggle);+ expect(screen.getByText(/Connection lost/)).toBeTruthy();});it("does not hide live work with no events", () => {const { rerender, container } = render(<TurnSteps steps={[]} />);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 51c3475098..126ff701b7 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,10 +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" }));- expect(screen.getByText("Interrupted without a result")).toBeTruthy();- // Opening the fold expands the whole chain, not one more chevron level.- expect(screen.getByText("Inspect archive.")).toBeTruthy();+ 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.");expect(container.querySelectorAll(".mx-auto")).toHaveLength(0);expect(screen.getByTestId("work-trace").className).toMatch(/self-start/);});@@ -83,9 +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" }));- expect(screen.getAllByText("Upload failed").length).toBeGreaterThan(0);- // The open fold expands tool details too — no second tap needed.+ 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.+ expect(screen.queryByText("Report contents")).toBeNull();+ fireEvent.click(screen.getAllByRole("button", { name: "Details" })[0]);expect(screen.getByText("Report contents")).toBeTruthy();});@@ -98,8 +104,9 @@ 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.getAllByText("Delivery failed").length).toBeGreaterThan(0);+ 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();// The approval card survives opening the fold — it still needs a tap.expect(screen.getByRole("button", { name: "Approve" })).toBeTruthy();});@@ -130,16 +137,20 @@ it("folds successful work and post-reply errors behind one toggle without reordeexpect(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 chain: the post-reply error and the tool details.- expect(screen.getAllByText("Upload failed").length).toBeGreaterThan(0);+ fireEvent.click(screen.getByRole("button", { name: /^Thought for 1\.0s/ }));+ // One tap opens the whole report: every step 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.");+ 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]);expect(screen.getAllByText("Report contents").length).toBeGreaterThan(0);- // Inner rows stay tappable: collapsing the group hides the details again.- fireEvent.click(screen.getByRole("button", { name: "Read files Created files" }));+ fireEvent.click(screen.getAllByRole("button", { name: "Details" })[0]);expect(screen.queryAllByText("Report contents")).toHaveLength(0);- expect(screen.getAllByText("Upload failed").length).toBeGreaterThan(0);- fireEvent.click(screen.getByRole("button", { name: "Read files Created files" }));- expect(screen.getAllByText("Report contents").length).toBeGreaterThan(0);});it("does not offer a thought toggle when the turn is only a reply", () => {@@ -163,7 +174,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: /^Thought 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 b5f0bee118..be248d6828 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -5606,6 +5606,179 @@"write": "Datei schreiben","memory": "Updating Memory"},+ "trace_report": {+ "locale": "de",+ "title": "So ist diese Antwort entstanden",+ "quote": "„{text}“",+ "copy": "Als Text 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",+ "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",+ "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."+ },+ "subject": {+ "wiki": "das Wiki",+ "wiki_write": "das Wiki",+ "artifact": "Artefakte",+ "skill": "Skills",+ "skill_create": "Skills",+ "web": "die Websuche",+ "screen": "den Bildschirm",+ "screen_recall": "den Bildschirmverlauf",+ "control": "die Bildschirmsteuerung",+ "navigate": "den Browser",+ "app": "Apps",+ "memory": "das Gedächtnis",+ "memory_update": "das Gedächtnis",+ "profile": "dein Profil",+ "contact": "Kontakte",+ "call": "Anrufe",+ "worker": "einen Worker",+ "model": "die Modelleinstellungen",+ "mcp_admin": "MCP-Server",+ "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"+ }+ },"chat_media": {"unavailable": "Dieses Medium kann nicht geladen oder abgespielt werden. Du kannst die Datei weiterhin öffnen.","expand": "{file} vergrößern",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 7dfd6f5673..958d0ac9c0 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -5639,6 +5639,179 @@"write": "Write file","memory": "Updating Memory"},+ "trace_report": {+ "locale": "en",+ "title": "How this answer came about",+ "quote": "“{text}”",+ "copy": "Copy as text",+ "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",+ "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",+ "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."+ },+ "subject": {+ "wiki": "the wiki",+ "wiki_write": "the wiki",+ "artifact": "artifacts",+ "skill": "skills",+ "skill_create": "skills",+ "web": "web search",+ "screen": "the screen",+ "screen_recall": "screen history",+ "control": "screen control",+ "navigate": "the browser",+ "app": "apps",+ "memory": "memory",+ "memory_update": "memory",+ "profile": "your profile",+ "contact": "contacts",+ "call": "calls",+ "worker": "a worker",+ "model": "model settings",+ "mcp_admin": "MCP servers",+ "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"+ }+ },"chat_media": {"unavailable": "This media cannot be loaded or played. You can still open the file.","expand": "Enlarge {file}",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex a766aa5094..b73278e2df 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -5606,6 +5606,179 @@"write": "Escribir archivo","memory": "Updating Memory"},+ "trace_report": {+ "locale": "es",+ "title": "Cómo se llegó a esta respuesta",+ "quote": "«{text}»",+ "copy": "Copiar como texto",+ "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",+ "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",+ "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."+ },+ "subject": {+ "wiki": "la wiki",+ "wiki_write": "la wiki",+ "artifact": "artefactos",+ "skill": "habilidades",+ "skill_create": "habilidades",+ "web": "la búsqueda web",+ "screen": "la pantalla",+ "screen_recall": "el historial de pantalla",+ "control": "el control de pantalla",+ "navigate": "el navegador",+ "app": "apps",+ "memory": "la memoria",+ "memory_update": "la memoria",+ "profile": "tu perfil",+ "contact": "contactos",+ "call": "llamadas",+ "worker": "un worker",+ "model": "la configuración del modelo",+ "mcp_admin": "servidores MCP",+ "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"+ }+ },"chat_media": {"unavailable": "No se puede cargar o reproducir este archivo. Puedes abrirlo directamente.","expand": "Ampliar {file}",diff --git a/jarvis/ui/web/frontend/src/lib/thinkingSteps.test.ts b/jarvis/ui/web/frontend/src/lib/thinkingSteps.test.tsindex fcefa09f89..d50385d19f 100644--- a/jarvis/ui/web/frontend/src/lib/thinkingSteps.test.ts+++ b/jarvis/ui/web/frontend/src/lib/thinkingSteps.test.ts@@ -147,13 +147,27 @@ describe("reduceThinkingSteps", () => {});});- it("adds progress announcements as instantly-done notes, skips other kinds", () => {+ it("adds progress as a note and a preamble as a thought, skips other kinds", () => {const steps = run([["AnnouncementRequested", { kind: "progress", text: "Halfway there" }],- ["AnnouncementRequested", { kind: "preamble", text: "On it" }],+ ["AnnouncementRequested", { kind: "preamble", text: "I'll check the computers you set up." }],+ ["AnnouncementRequested", { kind: "completion", text: "Done" }],]);- expect(steps).toHaveLength(1);+ expect(steps).toHaveLength(2);expect(steps[0]).toMatchObject({ kind: "note", detail: "Halfway there", status: "done" });+ expect(steps[1]).toMatchObject({ kind: "thought", detail: "I'll check the computers you set up.", status: "done" });+ });++ it("keeps a refused call as a denied step, even with no proposal before it", () => {+ const proposed = run([+ ["ActionProposed", { tool_name: "run-app-action" }],+ ["ActionDenied", { tool_name: "run-app-action", reason: "blacklist: <tool-declared-block>" }],+ ]);+ expect(proposed).toHaveLength(1);+ expect(proposed[0]).toMatchObject({ kind: "tool", status: "error", denied: true, error: "blacklist: <tool-declared-block>" });+ const guarded = run([["ActionDenied", { tool_name: "run-app-action", reason: "Plan mode permits reads only" }]]);+ expect(guarded).toHaveLength(1);+ expect(guarded[0]).toMatchObject({ kind: "tool", detail: "run-app-action", status: "error", denied: true });});it("caps the list and evicts finished steps before active ones", () => {diff --git a/jarvis/ui/web/frontend/src/lib/thinkingSteps.ts b/jarvis/ui/web/frontend/src/lib/thinkingSteps.tsindex f84e6302bf..53e0f5369d 100644--- a/jarvis/ui/web/frontend/src/lib/thinkingSteps.ts+++ b/jarvis/ui/web/frontend/src/lib/thinkingSteps.ts@@ -49,6 +49,8 @@ export interface ThinkingStep {result?: string;/** Tool / worker rows: why it failed, when it did. */error?: string;+ /** Tool rows: the call was refused (ActionDenied), not run and failed. */+ denied?: boolean;}/** Finished trace attached to the assistant message that ended the turn. */@@ -275,7 +277,7 @@ export function reduceThinkingSteps(// The sentence the model wrote next to the call ("I'll check the wiki// for that") is the closest thing to its thinking we get for free —// one muted line above the tool row, never spoken.- const rationale = clip(str(p.rationale), 200);+ const rationale = clip(str(p.rationale), 600);const withThought = rationale? push(steps, {id: nextId(),@@ -330,9 +332,32 @@ export function reduceThinkingSteps(case "ActionDenied": {const name = str(p.tool_name);- return completeTool(steps, name, tsMs, {- error: true,- errorText: clip(str(p.reason), 200) || undefined,+ const reason = clip(str(p.reason), 400) || undefined;+ const completed = completeTool(steps, name, tsMs, { error: true, errorText: reason });+ if (completed) {+ // completeTool finished the matching row; mark that row as refused.+ for (let i = completed.length - 1; i >= 0; i--) {+ const s = completed[i];+ if (s.kind === "tool" && s.status === "error" && (!name || s.detail === name)) {+ completed[i] = { ...s, denied: true };+ break;+ }+ }+ return completed;+ }+ // A guard refused the call before it was ever proposed: still a step+ // the turn took, or the trace would hide why the action never ran.+ if (!name) return null;+ return push(steps, {+ id: nextId(),+ kind: "tool",+ labelKey: "thinking.step_tool",+ detail: name,+ status: "error",+ startedTs: tsMs,+ durationMs: 0,+ denied: true,+ ...(reason ? { error: reason } : {}),});}@@ -385,9 +410,25 @@ export function reduceThinkingSteps(}case "AnnouncementRequested": {- // Progress announcements only — preambles already render as their own- // chat bubble and completions arrive as the final reply.- if (str(p.kind) !== "progress") return null;+ // A preamble ("I'll check the computers you set up") is the model+ // saying why it reaches for the next tool — often the only reason a+ // turn records, since many models leave the call's rationale empty.+ // It becomes a thought; completions arrive as the final reply.+ const kind = str(p.kind);+ if (kind === "preamble") {+ const said = clip(str(p.text), 600);+ if (!said) return null;+ return push(steps, {+ id: nextId(),+ kind: "thought",+ labelKey: "thinking.step_thought",+ detail: said,+ status: "done",+ startedTs: tsMs,+ durationMs: 0,+ });+ }+ if (kind !== "progress") return null;const text = clip(str(p.text), 80);if (!text) return null;return push(steps, {