Skip to content

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.

feat(chat): rebuild chronological work trace UI (RUB-51)

rubenluetke10-beepe84360fb9e8b
diff --git a/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx b/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx
index 5d1cc202eb..ab820e6d75 100644
--- a/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx
+++ b/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx
@@ -1,262 +1,13 @@
-/**
- * ThinkingTrace — the live reasoning card shown while the assistant works.
- *
- * The turn's visible state while it is running — the timeline never shows a
- * gap where an answer is being written. A pulsing core, a shimmering
- * "Thinking" wordmark, a live elapsed timer and a vertical step rail where
- * real backend events (tool calls, computer-use phases, worker dispatches)
- * appear as animated rows.
- *
- * It is an assistant bubble, not a special surface: same fill, same side, same
- * radius as the reply that replaces it, so the turn does not visibly change
- * shape when it finishes. The byline it used to carry is gone for the same
- * reason it is gone from MessageBubble — the fill and the side already say who
- * is speaking, and it was set in --primary, which is a fill and not an ink.
- *
- * ThoughtTraceDisclosure is the after-the-fact companion: once the reply
- * lands, the finished trace renders as a collapsed "Thought for 12.4s ·
- * 5 steps" row above the answer and can be expanded to replay the steps.
- */
-import { useEffect, useState } from "react";
-import { motion, useReducedMotion } from "framer-motion";
-import {
- Bot,
- Brain,
- Check,
- ChevronRight,
- Info,
- MonitorDot,
- Wrench,
- X,
-} from "lucide-react";
import { useEventStore } from "@/store/events";
-import type {
- ThinkingStep,
- ThinkingStepKind,
- ThinkingTraceSnapshot,
-} from "@/lib/thinkingSteps";
-import { cn } from "@/lib/utils";
-import { useT } from "@/i18n";
-import { LiveCore } from "@/components/LiveCore";
+import type { ThinkingTraceSnapshot } from "@/lib/thinkingSteps";
+import { VoiceWorkTrace } from "@/components/agentchat/VoiceWorkTrace";
+export { traceDuration as formatThinkingDuration } from "@/components/agentchat/WorkTrace";
-/** Rows visible in the live card — older ones collapse into a "+N" row. */
-const VISIBLE_STEPS = 5;
-
-const KIND_ICON: Record<ThinkingStepKind, typeof Wrench> = {
- brain: Brain,
- thought: Brain,
- tool: Wrench,
- computer: MonitorDot,
- worker: Bot,
- note: Info,
-};
-
-export function formatThinkingDuration(ms: number): string {
- if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;
- const m = Math.floor(ms / 60_000);
- const s = Math.round((ms % 60_000) / 1000);
- return `${m}m ${String(s).padStart(2, "0")}s`;
-}
-
-/** Live elapsed readout. 100ms tick keeps the tenths digit feeling alive. */
-function useElapsedMs(startedTs: number | null): number {
- const [now, setNow] = useState(() => Date.now());
- useEffect(() => {
- if (startedTs === null) return;
- const id = window.setInterval(() => setNow(Date.now()), 100);
- return () => window.clearInterval(id);
- }, [startedTs]);
- return startedTs === null ? 0 : Math.max(0, now - startedTs);
-}
-
-/**
- * A step's state, in colour and nothing else.
- *
- * Each of the three used to be a ring around a wash around a glyph — three
- * nested surfaces to say one word, at 12px. The glyph alone says it, and it
- * says it in the status palette: life for a finished step, fault for a failed
- * one, and the spinner's leading edge in life while the step is still running.
- * A done step must not be quieter than a pending one, so "done" is the only
- * green on the rail.
- */
-function StatusNode({ status }: { status: ThinkingStep["status"] }) {
- if (status === "active") {
- return (
- <span
- aria-hidden
- className="relative z-10 h-3 w-3 shrink-0 animate-spin rounded-full border-2 border-secondary border-t-success bg-card"
- />
- );
- }
- if (status === "error") {
- return (
- <span aria-hidden className="relative z-10 flex h-3 w-3 shrink-0 items-center justify-center">
- <X className="h-3 w-3 text-destructive" strokeWidth={3} />
- </span>
- );
- }
- return (
- <span aria-hidden className="relative z-10 flex h-3 w-3 shrink-0 items-center justify-center">
- <Check className="h-3 w-3 text-success" strokeWidth={3} />
- </span>
- );
-}
-
-function StepRow({ step, live }: { step: ThinkingStep; live: boolean }) {
- const t = useT();
- const reduced = useReducedMotion();
- const KindIcon = KIND_ICON[step.kind];
- const active = step.status === "active";
-
- return (
- <motion.li
- layout={!reduced}
- initial={live && !reduced ? { opacity: 0, y: 6 } : false}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
- className="relative flex min-w-0 items-center gap-2"
- >
- <StatusNode status={step.status} />
- <KindIcon
- aria-hidden
- className={cn("h-3 w-3 shrink-0 text-muted-foreground")}
- />
- <span
- className={cn(
- "shrink-0 text-meta",
- active ? "thinking-shimmer font-medium" : "text-foreground",
- step.status === "error" && "text-destructive",
- )}
- >
- {t(step.labelKey)}
- </span>
- {step.detail && (
- <span className="min-w-0 truncate font-mono text-micro text-muted-foreground">
- {step.detail}
- </span>
- )}
- {step.durationMs !== undefined && step.durationMs > 0 && (
- <span className="ml-auto shrink-0 pl-2 font-mono text-micro tabular-nums text-muted-foreground">
- {formatThinkingDuration(step.durationMs)}
- </span>
- )}
- </motion.li>
- );
-}
-
-function StepRail({
- steps,
- live,
- hiddenCount,
-}: {
- steps: ThinkingStep[];
- live: boolean;
- hiddenCount: number;
-}) {
- const t = useT();
- return (
- <ol className="relative space-y-2">
- {/* Vertical rail behind the status nodes — fades out downward. */}
- <span
- aria-hidden
- className="absolute bottom-2 left-[5.5px] top-2 w-px bg-border"
- />
- {hiddenCount > 0 && (
- <li className="relative flex items-center gap-2 pl-5 font-mono text-micro text-muted-foreground">
- +{hiddenCount} {t("thinking.earlier")}
- </li>
- )}
- {steps.map((s) => (
- <StepRow key={s.id} step={s} live={live} />
- ))}
- </ol>
- );
-}
-
-/** The live card rendered in the transcript while `chatThinking` is true. */
export function ThinkingTrace() {
- const t = useT();
const steps = useEventStore((s) => s.thinkingSteps);
- const startedTs = useEventStore((s) => s.thinkingStartedTs);
- const elapsed = useElapsedMs(startedTs);
-
- const visible = steps.slice(-VISIBLE_STEPS);
- const hidden = steps.length - visible.length;
-
- return (
- <div
- className="flex justify-start"
- role="status"
- aria-live="polite"
- aria-label={t("chats_view.thinking_aria")}
- >
- {/*
- * The in-progress turn is a bubble like any other: the assistant's own
- * fill, on the assistant's own side, at the assistant's own radius. The
- * blurred bloom behind it is gone — a glow is additive light standing in
- * for a fill that is now actually there — and so is the rim, because a
- * fill and a border are two answers to one question.
- */}
- <div className="relative w-full max-w-[85%] overflow-hidden rounded-lg bg-card px-4 py-3 sm:max-w-[440px]">
- <div className="relative flex items-center gap-row">
- <LiveCore />
- <span className="thinking-shimmer text-meta font-medium">
- {t("thinking.label")}
- </span>
- <span className="ml-auto font-mono text-micro tabular-nums text-muted-foreground">
- {formatThinkingDuration(elapsed)}
- </span>
- </div>
-
- {visible.length > 0 && (
- <div className="relative mt-3">
- <StepRail steps={visible} live hiddenCount={hidden} />
- </div>
- )}
- </div>
- </div>
- );
+ return <VoiceWorkTrace steps={steps} live />;
}
-/**
- * Collapsed "Thought for Xs · N steps" disclosure above an assistant reply.
- * Expands to the finished step list — the conserved reasoning trace.
- */
-export function ThoughtTraceDisclosure({
- trace,
-}: {
- trace: ThinkingTraceSnapshot;
-}) {
- const t = useT();
- const [open, setOpen] = useState(false);
-
- return (
- <div className="mb-1.5 mt-1">
- <button
- type="button"
- onClick={() => setOpen((v) => !v)}
- aria-expanded={open}
- className="group -ml-1 flex items-center gap-1.5 rounded-md px-1 py-0.5 text-micro text-muted-foreground transition-colors hover:text-foreground"
- >
- <ChevronRight
- aria-hidden
- className={cn(
- "h-3 w-3 transition-transform duration-200",
- open && "rotate-90",
- )}
- />
- <span className="font-medium">
- {t("thinking.thought_for")} {formatThinkingDuration(trace.durationMs)}
- </span>
- <span className="text-muted-foreground">
- · {trace.steps.length} {t("thinking.steps")}
- </span>
- </button>
- {open && (
- <div className="mt-2 border-b border-border pb-2">
- <StepRail steps={trace.steps} live={false} hiddenCount={0} />
- </div>
- )}
- </div>
- );
+export function ThoughtTraceDisclosure({ trace }: { trace: ThinkingTraceSnapshot }) {
+ return <VoiceWorkTrace steps={trace.steps} durationMs={trace.durationMs} />;
}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx
index fc49d518e4..3694390f8a 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx
@@ -1,388 +1,21 @@
-import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import {
- AgentTimeline,
- arrangeThinking,
- thoughtGist,
- thoughtNeedsFold,
-} from "@/components/agentchat/AgentTimeline";
-import { EMPTY_TIMELINE, reduceEvents, type TurnBlock } from "@/components/agentchat/reduce";
+import { cleanup, render, screen, within } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { AgentTimeline } from "./AgentTimeline";
+import { EMPTY_TIMELINE, reduceEvents } from "./reduce";
import type { AgentChatEvent } from "@/lib/agentChatApi";
-
-/**
- * The scratchpad — how a turn's thinking is shown.
- *
- * The complaint this file guards (maintainer, 2026-08-25): the model's
- * intermediate steps had stopped showing. Every stretch of thought was
- * merged into one folded "Thought for Ns" row at the top of the turn, and
- * the running one drew nothing at all, so the reasoning was neither
- * watchable while it happened nor readable where it happened.
- */
-
let seq = 0;
-function ev(kind: string, payload: Record<string, unknown>, tsMs = 1_000): AgentChatEvent {
- seq += 1;
- return { seq, ts_ms: tsMs, kind, payload } as AgentChatEvent;
+function ev(kind: string, payload: Record<string, unknown>, tsMs = 1000): AgentChatEvent {
+ return { seq: ++seq, ts_ms: tsMs, kind, payload } as AgentChatEvent;
}
-
-const TURN = { provider: "openai-codex", model: "gpt-5.4", effort: "high", runner: "codex-cli" };
-
function draw(events: AgentChatEvent[]) {
- const { items } = reduceEvents(EMPTY_TIMELINE, events);
- return render(
- <AgentTimeline
- items={items}
- assistantName="Jarvis"
- providerLabel={(id) => id}
- onDecide={() => undefined}
- />,
- );
+ return render(<AgentTimeline items={reduceEvents(EMPTY_TIMELINE, events).items} assistantName="Jarvis" providerLabel={id => id} onDecide={() => undefined} />);
}
-
-const LONG =
- "First I need to find where the port is configured. The launcher reads it from the " +
- "instance config, so the dev instance and the live one cannot collide.\n\n" +
- "Then I will check whether anything else already listens there.";
-
-afterEach(() => {
- cleanup();
- seq = 0;
-});
-
-describe("arrangeThinking", () => {
- const spoken = (id: string, text: string, live = false): TurnBlock => ({
- kind: "reasoning",
- id,
- text,
- durationMs: live ? null : 1000,
- live,
- startedMs: 0,
- });
- const silent = (id: string, durationMs: number, live = false): TurnBlock => ({
- kind: "reasoning",
- id,
- text: "",
- durationMs: live ? null : durationMs,
- live,
- startedMs: 0,
- });
- const tool: TurnBlock = {
- kind: "tool",
- callId: "c1",
- name: "Bash",
- input: {},
- output: "ok",
- isError: false,
- durationMs: 10,
- approval: null,
- startedMs: 0,
- };
-
- it("keeps a thought with words where it happened, live or finished", () => {
- const out = arrangeThinking([spoken("a", "Port first."), tool, spoken("b", "Now the log.", true)]);
- expect(out.map((b) => (b.kind === "reasoning" ? b.id : b.kind))).toEqual(["a", "tool", "b"]);
- });
-
- it("folds the wordless thoughts into one timing row and drops a running one", () => {
- const out = arrangeThinking([silent("a", 1000), tool, silent("b", 4000), silent("c", 0, true)]);
- expect(out).toHaveLength(2);
- const [row] = out;
- expect(row.kind).toBe("reasoning");
- if (row.kind === "reasoning") expect(row.durationMs).toBe(5000);
- });
-});
-
-describe("thought helpers", () => {
- it("folds only what a preview cannot hold", () => {
- expect(thoughtNeedsFold("Looking in the wiki for the holiday dates.")).toBe(false);
- expect(thoughtNeedsFold(LONG)).toBe(true);
- expect(thoughtNeedsFold("x".repeat(201))).toBe(true);
- });
-
- it("flattens Markdown into one readable line", () => {
- expect(thoughtGist("**Checking** the `config`\n\n- first\n- second")).toBe(
- "Checking the config - first - second",
- );
- });
-});
-
-describe("the scratchpad", () => {
- it("streams the thought as it is written, under the turn's one live line", () => {
- vi.useFakeTimers();
- try {
- const started = Date.now();
- draw([
- ev("user_message", { text: "look into it" }, started),
- ev("turn_started", { turn_id: "t1", ...TURN }, started),
- ev("reasoning_started", { turn_id: "t1", message_id: "r1" }, started),
- ev("usage_delta", { turn_id: "t1", usage: { input_tokens: 12, output_tokens: 300 } }, started),
- ev("reasoning_delta", { turn_id: "t1", text: "The port is read from " }, started),
- ev("reasoning_delta", { turn_id: "t1", text: "the instance config." }, started),
- ]);
-
- const pad = screen.getByTestId("agent-reasoning");
- expect(pad.getAttribute("data-state")).toBe("live");
- // The words are on screen while they arrive.
- expect(pad.textContent).toContain("The port is read from the instance config.");
- // …and the live line is the scratchpad's own header: the core, the
- // running time, the tokens so far — once, not once here and once below.
- const live = screen.getAllByTestId("agent-turn-live");
- expect(live).toHaveLength(1);
- expect(pad.contains(live[0])).toBe(true);
- expect(within(live[0]).getByTestId("live-core")).toBeTruthy();
- expect(live[0].textContent).toMatch(/300/);
- act(() => {
- vi.advanceTimersByTime(8_000);
- });
- expect(live[0].textContent).toMatch(/8s/);
- } finally {
- vi.useRealTimers();
- }
- });
-
- it("reads every stretch of thinking where it happened, open while the turn still works", () => {
- draw([
- ev("user_message", { text: "look into it" }),
- ev("turn_started", { turn_id: "t2", ...TURN }),
- ev("reasoning", { turn_id: "t2", text: LONG, duration_ms: 3000 }),
- ev("tool_call", { turn_id: "t2", call_id: "c1", name: "Bash", input: { command: "ss -ltnp" } }),
- ev("tool_result", { turn_id: "t2", call_id: "c1", output: "ok", is_error: false }),
- ev("reasoning", { turn_id: "t2", text: "It is listening.", duration_ms: 1000 }),
- ]);
-
- const rows = screen.getAllByTestId("agent-reasoning");
- expect(rows).toHaveLength(2);
- // Thought, command, thought — in that order, not one merged row on top.
- const order = Array.from(
- document.querySelectorAll("[data-testid='agent-reasoning'],[data-testid='agent-tool']"),
- ).map((el) => el.getAttribute("data-testid"));
- expect(order).toEqual(["agent-reasoning", "agent-tool", "agent-reasoning"]);
-
- // A long thought is open in full while the turn runs; the short one is
- // whole either way, with nothing left to unfold.
- expect(rows[0].getAttribute("data-state")).toBe("open");
- expect(rows[0].textContent).toContain("3s");
- expect(rows[0].textContent).toContain("already listens there");
- expect(rows[1].getAttribute("data-state")).toBe("whole");
- expect(rows[1].textContent).toContain("It is listening.");
- expect(within(rows[1]).getByRole("button").hasAttribute("disabled")).toBe(true);
-
- // The turn's own live line sits below, because no thought is streaming.
- expect(screen.getAllByTestId("agent-turn-live")).toHaveLength(1);
- expect(rows[0].contains(screen.getByTestId("agent-turn-live"))).toBe(false);
- });
-
- it("folds a long thought to a two-line preview once the turn is done, and opens on a click", () => {
- draw([
- ev("user_message", { text: "look into it" }),
- ev("turn_started", { turn_id: "t3", ...TURN }),
- ev("reasoning", { turn_id: "t3", text: LONG, duration_ms: 3000 }),
- ev("assistant_text", { turn_id: "t3", message_id: "m1", text: "Running." }),
- ev("turn_finished", { turn_id: "t3", status: "done", duration_ms: 4000, usage: {} }),
- ]);
-
- const pad = screen.getByTestId("agent-reasoning");
- expect(pad.getAttribute("data-state")).toBe("folded");
- // The preview still shows the thought's first words without a click.
- const preview = within(pad).getByTestId("agent-reasoning-preview");
- expect(preview.textContent).toContain("First I need to find where the port is configured.");
- expect(preview.className).toContain("line-clamp-2");
-
- fireEvent.click(within(pad).getByRole("button"));
- expect(pad.getAttribute("data-state")).toBe("open");
- expect(pad.textContent).toContain("already listens there");
- fireEvent.click(within(pad).getByRole("button"));
- expect(pad.getAttribute("data-state")).toBe("folded");
- });
-
- it("reduces wordless thinking to its time and never opens it", () => {
- draw([
- ev("turn_started", { turn_id: "t4", ...TURN }),
- ev("reasoning", { turn_id: "t4", text: "", duration_ms: 2000 }),
- ev("tool_call", { turn_id: "t4", call_id: "c1", name: "Read", input: { path: "a.py" } }),
- ev("tool_result", { turn_id: "t4", call_id: "c1", output: "ok", is_error: false }),
- ev("reasoning", { turn_id: "t4", text: "", duration_ms: 6000 }),
- ev("assistant_text", { turn_id: "t4", message_id: "m1", text: "Done." }),
- ev("turn_finished", { turn_id: "t4", status: "done", duration_ms: 9000, usage: {} }),
- ]);
-
- const rows = screen.getAllByTestId("agent-reasoning");
- expect(rows).toHaveLength(1);
- expect(rows[0].getAttribute("data-state")).toBe("silent");
- expect(rows[0].textContent).toMatch(/8s/);
- expect(within(rows[0]).getByRole("button").hasAttribute("disabled")).toBe(true);
- });
-
- it("draws nothing for a thought that has started but has no words yet", () => {
- draw([
- ev("turn_started", { turn_id: "t5", ...TURN }),
- ev("reasoning_started", { turn_id: "t5", message_id: "r1" }),
- ]);
- expect(screen.queryByTestId("agent-reasoning")).toBeNull();
- // The live line below is what says the turn is thinking.
- expect(screen.getAllByTestId("agent-turn-live")).toHaveLength(1);
- });
-});
-
-/*
- * The change a coding call made, and the wall of steps around it.
- *
- * Two complaints from 2026-08-27, judged against Claude Code and Codex: an
- * edit arrived as its raw arguments, so the one thing worth reading — what
- * actually changed — was the one thing you could not read; and a finished
- * turn left its whole run of calls lying in the transcript, which the
- * maintainer called "far too much stuff".
- */
-describe("a coding call shows its diff", () => {
- const EDIT = {
- turn_id: "d1",
- call_id: "e1",
- name: "Edit",
- input: {
- file_path: "src/app.ts",
- old_string: "const port = 47821;",
- new_string: "const port = 47921;",
- },
- };
-
- function drawEdit(output = "The file src/app.ts has been updated successfully.") {
- draw([
- ev("user_message", { text: "change the port" }),
- ev("turn_started", { turn_id: "d1", ...TURN }),
- ev("tool_call", EDIT),
- ev("tool_result", { turn_id: "d1", call_id: "e1", output, is_error: false }),
- ev("turn_finished", { turn_id: "d1", status: "done", duration_ms: 900, usage: {} }),
- ]);
- }
-
- it("wears the size of the change on the row, before anything is opened", () => {
- drawEdit();
- const stat = screen.getByTestId("agent-diff-stat");
- expect(stat.dataset.added).toBe("1");
- expect(stat.dataset.removed).toBe("1");
- });
-
- it("paints the removed line and the added one when the row is opened", () => {
- drawEdit();
- fireEvent.click(screen.getByTestId("agent-tool").querySelector("button")!);
- const diff = screen.getByTestId("agent-tool-diff");
- const removed = diff.querySelector("[data-diff='del']");
- const added = diff.querySelector("[data-diff='add']");
- expect(removed?.textContent).toContain("47821");
- expect(added?.textContent).toContain("47921");
- // The colours live on a class each, so both themes get their own pair.
- expect(removed?.className).toContain("diff-line-del");
- expect(added?.className).toContain("diff-line-add");
- });
-
- it("does not repeat the edit's receipt under the diff it already showed", () => {
- drawEdit();
- fireEvent.click(screen.getByTestId("agent-tool").querySelector("button")!);
- expect(screen.getByTestId("agent-tool-diff")).toBeTruthy();
- expect(screen.queryByText(/has been updated successfully/)).toBeNull();
- });
-
- it("still shows the output when the edit FAILED — that is the whole point", () => {
- draw([
- ev("turn_started", { turn_id: "d1", ...TURN }),
- ev("tool_call", EDIT),
- ev("tool_result", {
- turn_id: "d1",
- call_id: "e1",
- output: "String to replace not found in file.",
- is_error: true,
- }),
- ev("turn_finished", { turn_id: "d1", status: "done", duration_ms: 900, usage: {} }),
- ]);
- fireEvent.click(screen.getByTestId("agent-tool").querySelector("button")!);
- expect(screen.getByText(/String to replace not found/)).toBeTruthy();
- });
-
- it("leaves a call that edits nothing exactly as it was", () => {
- draw([
- ev("turn_started", { turn_id: "d2", ...TURN }),
- ev("tool_call", { turn_id: "d2", call_id: "b1", name: "Bash", input: { command: "ls" } }),
- ev("tool_result", { turn_id: "d2", call_id: "b1", output: "a.ts", is_error: false }),
- ev("turn_finished", { turn_id: "d2", status: "done", duration_ms: 200, usage: {} }),
- ]);
- expect(screen.queryByTestId("agent-diff-stat")).toBeNull();
- fireEvent.click(screen.getByTestId("agent-tool").querySelector("button")!);
- expect(screen.queryByTestId("agent-tool-diff")).toBeNull();
- expect(screen.getByText("a.ts")).toBeTruthy();
- });
-});
-
-describe("a run of steps puts itself away", () => {
- /** `count` calls in a row, optionally one of them failing. */
- function run(count: number, opts: { live?: boolean; failAt?: number } = {}) {
- const events = [
- ev("user_message", { text: "look into it" }),
- ev("turn_started", { turn_id: "g1", ...TURN }),
- ];
- for (let i = 0; i < count; i++) {
- events.push(
- ev("tool_call", {
- turn_id: "g1",
- call_id: `c${i}`,
- name: "Grep",
- input: { pattern: `p${i}` },
- }),
- );
- events.push(
- ev("tool_result", {
- turn_id: "g1",
- call_id: `c${i}`,
- output: "hit",
- is_error: opts.failAt === i,
- }),
- );
- }
- if (!opts.live) {
- events.push(
- ev("turn_finished", { turn_id: "g1", status: "done", duration_ms: 5000, usage: {} }),
- );
- }
- draw(events);
- }
-
- it("folds a finished run to one line, and opens it again on a click", () => {
- run(6);
- const group = screen.getByTestId("agent-tool-group");
- expect(group.dataset.state).toBe("folded");
- expect(screen.queryAllByTestId("agent-tool")).toHaveLength(0);
-
- fireEvent.click(screen.getByTestId("agent-tool-group-toggle"));
- expect(screen.getByTestId("agent-tool-group").dataset.state).toBe("open");
- expect(screen.queryAllByTestId("agent-tool")).toHaveLength(6);
- });
-
- it("leaves a short run alone: three rows are not a wall", () => {
- run(3);
- expect(screen.getByTestId("agent-tool-group").dataset.state).toBe("plain");
- expect(screen.queryByTestId("agent-tool-group-toggle")).toBeNull();
- expect(screen.queryAllByTestId("agent-tool")).toHaveLength(3);
- });
-
- it("shows every step while the turn is still working", () => {
- run(6, { live: true });
- expect(screen.getByTestId("agent-tool-group").dataset.state).toBe("plain");
- expect(screen.queryAllByTestId("agent-tool")).toHaveLength(6);
- });
-
- it("folds AROUND a step that failed, keeping the failure itself in view", () => {
- // The first pass held the whole run open on any failure, which left a
- // group of thirty-five calls lying open because one of them missed (live
- // check, 2026-08-27). The failure is the thing worth seeing — not the
- // thirty-four calls that went fine around it.
- run(6, { failAt: 2 });
- expect(screen.getByTestId("agent-tool-group").dataset.state).toBe("folded");
- const rows = screen.queryAllByTestId("agent-tool");
- expect(rows).toHaveLength(1);
- expect(rows[0].dataset.state).toBe("error");
- });
+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();
});
-
describe("the person's turn with files", () => {
const SHOT = {
name: "shot.png",
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx
index 9b23c186a5..321052937e 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx
@@ -1,91 +1,17 @@
-import { InternalMessageBubble, type InternalParticipant } from "./InternalMessageBubble";
-import {
- memo,
- useEffect,
- useLayoutEffect,
- useMemo,
- useRef,
- useState,
- type ReactNode,
-} from "react";
+import { memo } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
-import {
- ArrowDown,
- Ban,
- Check,
- ChevronRight,
- CircleAlert,
- FileText,
- ImageIcon,
- ShieldQuestion,
- X,
-} from "lucide-react";
-
-import { LiveCore } from "@/components/LiveCore";
+import { CircleAlert, FileText, ImageIcon } from "lucide-react";
+import { InternalMessageBubble, type InternalParticipant } from "./InternalMessageBubble";
import { MessageWithChips } from "./ToolChoiceChips";
import { ProviderLogo } from "@/components/providers/ProviderLogo";
-import { formatThoughtDuration } from "@/components/home/TurnSteps";
-import { agentToolView, formatTokens, outputTokens } from "@/components/agentchat/toolView";
-import { diffStat, toolDiff, type DiffFile, type DiffLine } from "@/components/agentchat/toolDiff";
-import type {
- ReasoningBlock,
- TextBlock,
- TimelineItem,
- ToolBlock,
- TurnBlock,
- TurnItem,
-} from "@/components/agentchat/reduce";
-import type { ApprovalDecision } from "@/lib/agentChatApi";
-import { effortLabel } from "@/components/agentchat/AgentComposer";
-import { fill, useT } from "@/i18n";
+import { effortLabel } from "./AgentComposer";
+import { TurnTrace, type Decide } from "./WorkTrace";
+import type { TimelineItem, TurnItem, TextBlock } from "./reduce";
+import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
-/**
- * The agent chat column — the person's lines in a quiet bubble on the
- * right, each assistant turn flush-left under a byline that says who
- * answered (the provider's mark, the model, the effort).
- *
- * Under the byline, in the order they happened: the model's thinking as a
- * readable scratchpad wherever it thought (a vendor that redacts its
- * thinking still gets a row, because the time is the fact), the tool calls
- * under the names the agent's own log uses, approval cards where the runner
- * asked, and the answer as Markdown.
- *
- * Three rules decide how all of that is drawn (maintainer, 2026-08-25:
- * it looks sloppy, odd boxes everywhere, and a strange stripe down the side):
- *
- * 1. ONE container per turn. Nothing inside draws a box of its own — a
- * tool call is a row, an opened detail is a hairline and some text.
- * Boxes inside boxes inside boxes is what made the column look busy,
- * and a nested frame carries no information the indent does not.
- * The turn itself is held together by its byline and the spacing; an
- * earlier version hung it off a glowing hairline rail, which read as a
- * stray stripe running down the transcript.
- * 2. The thinking is READ, not counted (maintainer, 2026-08-25: the
- * intermediate steps had stopped showing). A stretch of thought that has
- * words is a scratchpad in the place it happened: its text streams while
- * the model writes it, stays open while the turn still works, and folds
- * to a two-line preview once the turn is done. Only a thought with no
- * words to show — a vendor that redacts (Claude Code) — is reduced to its
- * time, and a running one of those draws nothing, because the live line
- * already says the turn is thinking and two lines saying it at once is
- * the duplication the maintainer objected to. A streaming scratchpad
- * carries the live line in its own header for the same reason: the turn
- * says it is working exactly ONCE.
- * 3. The turn ALWAYS says which state it is in. While it runs: the live
- * core, a word that changes as the minutes pass, the elapsed time and
- * the tokens spent — the Claude CLI's "Composing… (2m 35s · ↓ 3.7k
- * tokens)", in the product's own mark and colours. The moment it stops
- * there is a line saying so — Done, Stopped, Failed, or "finished
- * without an answer" when a turn ends on a dead tool call. A live line
- * that simply disappears leaves the person guessing.
- *
- * Only OUTPUT tokens are ever shown (maintainer, 2026-08-25). The input
- * side of a coding CLI re-counts the whole conversation on every step, so
- * it reads as an absurd number for one question (BUG-173); what the turn
- * produced is the honest, monotonic figure.
- */
+/** Shared transcript shell; the work trace owns all execution presentation. */
export function AgentTimeline({
items,
assistantName,
@@ -97,7 +23,7 @@ export function AgentTimeline({
items: TimelineItem[];
assistantName: string;
providerLabel: (providerId: string) => string;
- onDecide: (approvalId: string, decision: ApprovalDecision) => void;
+ onDecide: Decide;
/** Who an internal agent message was sent to — the chat owner (defaults to the assistant). */
recipientName?: string;
/** Sender faces by agent id, where the caller has a roster. */
@@ -237,282 +163,21 @@ export function AgentTimeline({
);
}
-const Turn = memo(function Turn({
- turn,
- assistantName,
- providerLabel,
- onDecide,
-}: {
- turn: TurnItem;
- assistantName: string;
- providerLabel: string;
- onDecide: (approvalId: string, decision: ApprovalDecision) => void;
+const Turn = memo(function Turn({ turn, assistantName, providerLabel, onDecide }: {
+ turn: TurnItem; assistantName: string; providerLabel: string; onDecide: Decide;
}) {
const t = useT();
- const live = turn.status === "running";
- const elapsed = useElapsedMs(live ? turn.startedMs : null);
- const blocks = useMemo(() => arrangeThinking(turn.blocks), [turn.blocks]);
- const groups = useMemo(() => groupSteps(blocks), [blocks]);
- // A scratchpad still receiving words carries the turn's live line in its
- // own header; the line below would only say "thinking" a second time.
- const thinkingAloud = blocks.some((b) => b.kind === "reasoning" && b.live);
-
- return (
- <div
- className="flex flex-col gap-1.5"
- data-testid="agent-turn"
- data-message-id={turn.id}
- data-status={turn.status}
- >
- {/*
- * This byline stays where the home chat's was deleted, because it is not
- * a repeat: it names WHICH agent, provider and model answered, and in a
- * pane that can be pointed at any of them that is the fact the reader
- * needs. It just stops shouting — no small caps, no --primary, and the
- * dot is green only while the turn is actually running.
- */}
- <div className="flex flex-wrap items-center gap-x-2 gap-y-1 px-1 font-mono text-micro text-muted-foreground">
- <span
- className={cn(
- "h-1.5 w-1.5 rounded-full",
- live ? "bg-success motion-safe:animate-pulse" : "bg-muted-foreground",
- )}
- aria-hidden
- />
- <span className="text-foreground">{assistantName}</span>
- <span className="inline-flex items-center gap-1.5">
- <ProviderLogo providerId={turn.provider} label={providerLabel} size="sm" />
- <span>{providerLabel}</span>
- {turn.model && <span>· {turn.model}</span>}
- {turn.effort && <span>· {effortLabel(turn.effort, t)}</span>}
- </span>
- </div>
-
- {/* No rail, no frame: the byline above and the spacing are what group
- the turn, and the closing line below says how it ended. */}
- <div className="flex flex-col gap-1.5 px-1">
- {groups.map((group) => {
- if (group.kind === "tools") {
- return (
- <ToolGroup
- key={group.id}
- blocks={group.blocks}
- turnLive={live}
- onDecide={onDecide}
- />
- );
- }
- if (group.block.kind === "text") return <Prose key={group.id} block={group.block} />;
- return (
- <Thought
- key={group.id}
- block={group.block}
- turnLive={live}
- usage={turn.liveUsage}
- />
- );
- })}
-
- {live && !thinkingAloud && <LiveStatus elapsed={elapsed} usage={turn.liveUsage} />}
-
- {turn.status === "error" && turn.error && (
- <div
- className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive"
- role="alert"
- data-testid="agent-turn-error"
- >
- <CircleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden />
- <span className="whitespace-pre-wrap break-words">{turn.error}</span>
- </div>
- )}
-
- {!live && <TurnOutcome turn={turn} />}
- </div>
+ return <div className="flex min-w-0 flex-col gap-3" data-testid="agent-turn" data-message-id={turn.id} data-status={turn.status}>
+ <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
+ <span className="font-medium text-foreground">{assistantName}</span>
+ <ProviderLogo providerId={turn.provider} label={providerLabel} size="sm" />
+ <span>{providerLabel}{turn.model ? ` · ${turn.model}` : ""}</span>
+ {turn.effort ? <span>{effortLabel(turn.effort, t)}</span> : null}
</div>
- );
+ <TurnTrace turn={turn} onDecide={onDecide} renderText={(text, id) => <Prose block={{ kind: "text", text, id }} />} />
+ </div>;
});
-/**
- * Where each stretch of a turn's thinking goes.
- *
- * A thought WITH words is a scratchpad and stays exactly where it happened —
- * ahead of the tool call it explains, between two of them, before the
- * answer. Reading the reasoning in the order it was written is the whole
- * point of showing it; the earlier design merged every stretch into one row
- * at the top of the turn, which hid the streaming text altogether and put
- * the finished thoughts behind a single click (maintainer, 2026-08-25: the
- * intermediate steps are no longer shown properly).
- *
- * A thought WITHOUT words is only a duration: a vendor that redacts its
- * thinking (Claude Code), or a runner that announced the thought before any
- * text arrived. Those stay quiet. The finished ones fold into ONE "Thought
- * for Ns" row where the first of them happened, seconds added up — a stack
- * of timing rows said nothing a sum does not. A running one draws nothing at
- * all: the live line below already says the turn is thinking, and saying it
- * twice in a row is the duplication the maintainer objected to.
- */
-export function arrangeThinking(blocks: TurnBlock[]): TurnBlock[] {
- const silent = blocks.filter(
- (b): b is ReasoningBlock => b.kind === "reasoning" && !b.live && !b.text.trim(),
- );
- const folded: ReasoningBlock | null =
- silent.length === 0
- ? null
- : {
- kind: "reasoning",
- id: silent[0].id,
- text: "",
- durationMs: silent.reduce((sum, th) => sum + (th.durationMs ?? 0), 0),
- live: false,
- startedMs: silent[0].startedMs,
- };
-
- const out: TurnBlock[] = [];
- let placed = false;
- for (const block of blocks) {
- if (block.kind !== "reasoning" || block.text.trim()) {
- out.push(block);
- continue;
- }
- if (block.live) continue;
- if (folded && !placed) {
- out.push(folded);
- placed = true;
- }
- }
- return out;
-}
-
-/**
- * The line that says the turn is alive.
- *
- * The live core, a word, the elapsed time and what the turn has produced so
- * far. The word changes every few seconds (locale-supplied,
- * comma-separated) so a long turn never looks frozen — the same trick the
- * Claude CLI plays, and the cheapest possible proof that something is still
- * happening. This is the ONLY line in a running turn that claims to be
- * working; the thought rows deliberately stay quiet until they close.
- */
-function LiveStatus({
- elapsed,
- usage,
-}: {
- elapsed: number;
- usage: Record<string, number> | null;
-}) {
- const t = useT();
- const words = useMemo(() => statusWords(t("agent_chat.status_words")), [t]);
- const word = words[Math.floor(elapsed / STATUS_WORD_MS) % words.length];
- const out = outputTokens(usage);
-
- return (
- <div
- className="flex flex-wrap items-center gap-x-2 gap-y-0.5 py-0.5 text-meta"
- data-testid="agent-turn-live"
- role="status"
- aria-live="polite"
- >
- <LiveCore />
- <span className="thinking-shimmer font-medium">{word}</span>
- <span className="inline-flex items-center gap-1.5 font-mono text-micro tabular-nums text-muted-foreground">
- <span>({formatThoughtDuration(elapsed)}</span>
- {out !== null && out > 0 && (
- <>
- <span aria-hidden>·</span>
- <OutTokens n={out} />
- </>
- )}
- <span>)</span>
- </span>
- <span className="text-muted-foreground">{t("agent_chat.interrupt_hint")}</span>
- </div>
- );
-}
-
-/** How long one status word stays before the next takes over. */
-const STATUS_WORD_MS = 4000;
-
-/** The locale's comma-separated word list; never empty. */
-export function statusWords(raw: string): string[] {
- const words = raw
- .split(",")
- .map((w) => w.trim())
- .filter(Boolean);
- return words.length > 0 ? words : ["Working…"];
-}
-
-/**
- * What the turn produced, in tokens.
- *
- * The OUTPUT side only, everywhere it appears — live and on the receipt.
- * The arrow is the CLI's own shorthand, so the two read the same.
- */
-function OutTokens({ n }: { n: number }) {
- const t = useT();
- return (
- <span className="inline-flex items-center gap-1" title={t("agent_chat.tokens_out")}>
- <ArrowDown className="h-3 w-3" aria-hidden />
- {formatTokens(n)}
- <span>{t("agent_chat.tokens")}</span>
- </span>
- );
-}
-
-/**
- * The closing line: the turn is over, and this is how it ended.
- *
- * It is drawn for EVERY finished turn, even one that produced nothing at
- * all — the whole point is that the person never has to guess whether the
- * agent is still working (maintainer, 2026-08-25). A turn that ends on a
- * failed tool call with no answer says exactly that instead of trailing
- * off into white space.
- */
-function TurnOutcome({ turn }: { turn: TurnItem }) {
- const t = useT();
- const usage = turn.usage ?? turn.liveUsage;
- const out = outputTokens(usage);
- const answered = turn.blocks.some((b) => b.kind === "text" && b.text.trim().length > 0);
-
- /*
- * The closing line's colour is the turn's outcome, and the ramp used to run
- * backwards: "done" was the DIMMEST of the four, quieter than "cancelled"
- * and quieter than "finished without an answer". Success is life, a turn
- * that produced nothing is degraded, a failure is fault, and a turn the
- * person stopped themselves is not a status at all — it is meta.
- */
- const { Icon, label, tone } =
- turn.status === "error"
- ? { Icon: CircleAlert, label: t("agent_chat.turn_failed"), tone: "text-destructive" }
- : turn.status === "cancelled"
- ? { Icon: Ban, label: t("agent_chat.turn_cancelled"), tone: "text-muted-foreground" }
- : answered
- ? { Icon: Check, label: t("agent_chat.turn_done"), tone: "text-success" }
- : {
- Icon: CircleAlert,
- label: t("agent_chat.turn_no_answer"),
- tone: "text-warning",
- };
-
- return (
- <div
- className={cn(
- "flex flex-wrap items-center gap-x-2.5 gap-y-0.5 pt-0.5 font-mono text-micro tabular-nums",
- tone,
- )}
- data-testid="agent-turn-footer"
- data-outcome={turn.status === "done" && !answered ? "no-answer" : turn.status}
- >
- <span className="inline-flex items-center gap-1 font-sans text-micro font-medium">
- <Icon className="h-3.5 w-3.5" aria-hidden />
- {label}
- </span>
- {turn.durationMs ? <span>{formatThoughtDuration(turn.durationMs)}</span> : null}
- {out !== null && out > 0 && <OutTokens n={out} />}
- {turn.costUsd !== null && turn.costUsd > 0 && <span>${turn.costUsd.toFixed(4)}</span>}
- </div>
- );
-}
-
function Prose({ block }: { block: TextBlock }) {
if (!block.text.trim()) return null;
return (
@@ -534,788 +199,3 @@ function Prose({ block }: { block: TextBlock }) {
</div>
);
}
-
-/** One stretch of thinking: a scratchpad when it has words, a timing row when it has none. */
-function Thought({
- block,
- turnLive,
- usage,
-}: {
- block: ReasoningBlock;
- turnLive: boolean;
- usage: Record<string, number> | null;
-}) {
- if (!block.text.trim()) return <SilentThought block={block} />;
- return <Scratchpad block={block} turnLive={turnLive} usage={usage} />;
-}
-
-/**
- * Past this many characters (or at the first blank line) a finished thought
- * is more than a preview can hold and earns a fold.
- */
-const PREVIEW_CHARS = 200;
-
-/** Does a thought need a fold, or does its preview already show all of it? */
-export function thoughtNeedsFold(text: string): boolean {
- const trimmed = text.trim();
- return trimmed.length > PREVIEW_CHARS || /\n\s*\n/.test(trimmed);
-}
-
-/**
- * A thought as one flat line for the folded preview — no Markdown marks, no
- * code blocks, no line breaks — so two lines of it read as a sentence.
- */
-export function thoughtGist(text: string): string {
- return text
- .replace(/```[\s\S]*?```/g, " ")
- .replace(/[`*_#>~]+/g, "")
- .replace(/\s+/g, " ")
- .trim();
-}
-
-/**
- * The model's thinking, readable — the scratchpad.
- *
- * WHILE THE WORDS ARRIVE it is open. Its header is the turn's live line for
- * as long as the thought runs — the core, "Thinking for 8s", the tokens so
- * far, the interrupt hint — and under a hairline sits the text itself,
- * anchored to its newest lines so the reader watches the thought unfold
- * instead of scrolling after it (the earlier lines fade out at the top once
- * there are more than fit).
- *
- * WHEN THE THOUGHT CLOSES it keeps its place. It stays open while the turn
- * still works, because watching the work is the point of a running turn,
- * and folds to "Thought for 8s" over a two-line preview the moment the turn
- * is done, so the answer is what a finished conversation reads as. A click
- * opens it again; a thought short enough to fit its own preview never needs
- * one and shows whole.
- *
- * The thought reads as prose, not as a log dump: models write their
- * reasoning in Markdown, and a raw `**like this**` on screen is the same
- * defect the local-models panel was fixed for.
- */
-function Scratchpad({
- block,
- turnLive,
- usage,
-}: {
- block: ReasoningBlock;
- turnLive: boolean;
- usage: Record<string, number> | null;
-}) {
- const t = useT();
- // `null` until the person decides; until then the turn's state decides.
- const [manual, setManual] = useState<boolean | null>(null);
- const live = block.live;
- const thinking = useElapsedMs(live ? block.startedMs : null);
- const text = block.text.trim();
- const foldable = thoughtNeedsFold(text);
- const open = live || (foldable && (manual ?? turnLive));
- const duration = block.durationMs ?? 0;
- const out = outputTokens(usage);
- const header =
- duration > 0
- ? fill(t("agent_chat.thought_for"), { duration: formatThoughtDuration(duration) })
- : t("agent_chat.thought");
-
- return (
- <div
- data-testid="agent-reasoning"
- data-state={live ? "live" : open ? "open" : foldable ? "folded" : "whole"}
- >
- {live ? (
- <div
- className="flex flex-wrap items-center gap-x-2 gap-y-0.5 py-0.5 text-xs"
- data-testid="agent-turn-live"
- role="status"
- aria-live="polite"
- >
- <LiveCore />
- <span className="thinking-shimmer font-medium">
- {fill(t("agent_chat.thinking_for"), { duration: formatThoughtDuration(thinking) })}
- </span>
- {out !== null && out > 0 && (
- <span className="inline-flex items-center gap-1.5 font-mono text-micro tabular-nums text-muted-foreground">
- <span aria-hidden>·</span>
- <OutTokens n={out} />
- </span>
- )}
- <span className="text-muted-foreground">{t("agent_chat.interrupt_hint")}</span>
- </div>
- ) : (
- <button
- type="button"
- onClick={() => setManual(!open)}
- aria-expanded={open}
- disabled={!foldable}
- className={cn(
- "-ml-1 inline-flex items-center gap-1.5 rounded-md px-1 py-0.5 text-xs text-muted-foreground transition-colors",
- foldable ? "hover:bg-secondary hover:text-foreground" : "cursor-default",
- )}
- >
- <ChevronRight
- className={cn(
- "h-3.5 w-3.5 shrink-0 transition-transform",
- open && "rotate-90",
- !foldable && "opacity-30",
- )}
- aria-hidden
- />
- <span>{header}</span>
- </button>
- )}
-
- {live ? (
- <Trace>
- <ThoughtTail text={text} />
- </Trace>
- ) : open ? (
- <Trace>
- <ThoughtProse text={text} />
- </Trace>
- ) : (
- <div
- className={cn(
- "ml-[1.25rem] text-meta text-muted-foreground [overflow-wrap:anywhere]",
- foldable && "line-clamp-2",
- )}
- data-testid="agent-reasoning-preview"
- >
- {thoughtGist(text)}
- </div>
- )}
- </div>
- );
-}
-
-/**
- * The streaming thought, anchored to its newest lines.
- *
- * The window is a fixed height with the text pinned to its bottom edge, so
- * new words push the old ones up and out of view — the reader always sees
- * what the model is writing NOW. Once more has been written than fits, the
- * top fades out to say so; a thought that fits is shown whole, unfaded.
- */
-function ThoughtTail({ text }: { text: string }) {
- const outer = useRef<HTMLDivElement>(null);
- const inner = useRef<HTMLDivElement>(null);
- const [clipped, setClipped] = useState(false);
- useLayoutEffect(() => {
- const box = outer.current;
- const body = inner.current;
- if (!box || !body) return;
- setClipped(body.offsetHeight > box.clientHeight + 1);
- }, [text]);
- return (
- <div
- ref={outer}
- className={cn(
- "flex max-h-44 flex-col justify-end overflow-hidden",
- clipped && "[mask-image:linear-gradient(to_bottom,transparent,black_2.75rem)]",
- )}
- data-testid="agent-reasoning-tail"
- data-clipped={clipped ? "true" : undefined}
- >
- <div ref={inner}>
- <ThoughtProse text={text} />
- </div>
- </div>
- );
-}
-
-function ThoughtProse({ text }: { text: string }) {
- return (
- <div
- className={cn(
- "prose prose-neutral max-w-none text-meta text-muted-foreground dark:prose-invert [overflow-wrap:anywhere]",
- "prose-p:my-1.5 prose-headings:my-1.5 prose-headings:text-meta prose-headings:font-semibold prose-headings:text-foreground",
- "prose-strong:text-foreground prose-li:my-0.5 prose-ul:my-1.5 prose-ol:my-1.5",
- "prose-code:font-mono prose-code:text-[0.9em] prose-code:before:hidden prose-code:after:hidden",
- "prose-pre:my-1.5 prose-pre:bg-transparent prose-pre:p-0 prose-pre:text-micro",
- )}
- >
- <ReactMarkdown remarkPlugins={[remarkGfm]}>{text}</ReactMarkdown>
- </div>
- );
-}
-
-/**
- * Thinking with no words to show — the vendor redacted it (Claude Code
- * does). The row still states the time, because the time is the fact, and
- * stays shut rather than opening onto emptiness.
- */
-function SilentThought({ block }: { block: ReasoningBlock }) {
- const t = useT();
- const duration = block.durationMs ?? 0;
- const header =
- duration > 0
- ? fill(t("agent_chat.thought_for"), { duration: formatThoughtDuration(duration) })
- : t("agent_chat.thought");
-
- return (
- <div data-testid="agent-reasoning" data-state="silent">
- <button
- type="button"
- aria-expanded={false}
- disabled
- className="-ml-1 inline-flex cursor-default items-center gap-1.5 rounded-md px-1 py-0.5 text-xs text-muted-foreground"
- >
- <ChevronRight className="h-3.5 w-3.5 shrink-0 opacity-30" aria-hidden />
- <span>{header}</span>
- </button>
- </div>
- );
-}
-
-function pretty(value: unknown): string {
- if (typeof value === "string") return value;
- try {
- return JSON.stringify(value, null, 2);
- } catch {
- return String(value);
- }
-}
-
-/**
- * Is the raw input worth printing under a row that already shows it?
- *
- * A shell call whose whole payload is `{"command": "ls -la"}` is fully told
- * by the row's own summary; repeating it as JSON below is the same string
- * twice, which is what made an opened tool call read as duplicated output
- * (maintainer, 2026-08-25). Anything with a second field, or a value the
- * summary had to truncate, still earns its lines.
- */
-export function inputAddsNothing(input: unknown, summary: string): boolean {
- if (input === undefined || input === null) return true;
- if (!summary) return false;
- if (typeof input === "string") return input.trim() === summary.trim();
- if (typeof input !== "object" || Array.isArray(input)) return false;
- const entries = Object.entries(input as Record<string, unknown>).filter(
- ([, v]) => v !== undefined && v !== null && v !== "",
- );
- if (entries.length !== 1) return false;
- const [, only] = entries[0];
- return typeof only === "string" && only.trim() === summary.trim();
-}
-
-/** The first line of a tool error, short enough to sit on the row. */
-function errorGist(text: string): string {
- const line = text.split("\n").find((l) => l.trim()) ?? "";
- const trimmed = line.trim();
- return trimmed.length > 160 ? `${trimmed.slice(0, 159)}…` : trimmed;
-}
-
-/**
- * The change a coding call made, painted the way every code host paints one.
- *
- * A row saying `Edit src/app.ts` names a file and says nothing about what
- * happened in it, and the arguments underneath were worse: two JSON string
- * literals, escapes and all, so the one thing worth reading was the one thing
- * that could not be (maintainer, 2026-08-27, against Claude Code and Codex).
- *
- * No frame — the fold's own indent already holds it (rule 1). What carries
- * the meaning is the ink: removed lines in the destructive red the whole app
- * uses for loss, added lines in the one green the palette now has, and every
- * line that did NOT move in plain grey, which is what makes a change legible
- * rather than a wall of colour.
- */
-function DiffView({ files }: { files: DiffFile[] }) {
- const t = useT();
- return (
- <div className="flex flex-col gap-2" data-testid="agent-tool-diff">
- {files.map((file, i) => (
- <div key={`${file.path}:${i}`} className="flex min-w-0 flex-col gap-1">
- {/* The path only when the row above cannot already be carrying it:
- one file is named on the row, several need naming here. */}
- {files.length > 1 && file.path && (
- <span className="truncate font-mono text-micro text-muted-foreground">
- {file.path}
- </span>
- )}
- <div className="scrollbar-jarvis max-h-80 overflow-auto">
- {file.lines.map((line, n) => (
- <DiffRow key={n} line={line} />
- ))}
- </div>
- {file.truncated > 0 && (
- <span className="font-mono text-micro text-muted-foreground">
- {fill(t("agent_chat.diff_truncated"), { count: String(file.truncated) })}
- </span>
- )}
- </div>
- ))}
- </div>
- );
-}
-
-/**
- * One line of a diff.
- *
- * The +/- mark is unselectable, so copying a diff out of the chat yields the
- * CODE rather than a column of marks to strip afterwards.
- */
-function DiffRow({ line }: { line: DiffLine }) {
- const t = useT();
- if (line.kind === "gap") {
- return (
- <div
- data-diff="gap"
- className="select-none px-2 py-0.5 font-mono text-micro text-muted-foreground"
- >
- {line.text ? fill(t("agent_chat.diff_skipped"), { count: line.text }) : "⋯"}
- </div>
- );
- }
- return (
- <div
- data-diff={line.kind}
- className={cn(
- "flex whitespace-pre-wrap break-words px-2 font-mono text-xs leading-relaxed",
- line.kind === "add" && "diff-line-add",
- line.kind === "del" && "diff-line-del",
- line.kind === "ctx" && "text-muted-foreground",
- )}
- >
- <span aria-hidden className="mr-2 w-2 shrink-0 select-none opacity-70">
- {line.kind === "add" ? "+" : line.kind === "del" ? "-" : " "}
- </span>
- <span className="min-w-0">{line.text || "\u00A0"}</span>
- </div>
- );
-}
-
-/** `+12 -3` — how big the change is, in the shape every code host uses. */
-function DiffStat({ added, removed }: { added: number; removed: number }) {
- if (added === 0 && removed === 0) return null;
- return (
- <span
- className="shrink-0 font-mono text-micro tabular-nums"
- data-testid="agent-diff-stat"
- data-added={added}
- data-removed={removed}
- >
- {added > 0 && <span className="diff-ink-add">+{added}</span>}
- {added > 0 && removed > 0 && <span className="text-muted-foreground"> </span>}
- {removed > 0 && <span className="diff-ink-del">-{removed}</span>}
- </span>
- );
-}
-
-/**
- * A turn's blocks, with consecutive tool calls collected into one group.
- *
- * Thinking and prose stay exactly where they happened — that is rule 2 and it
- * is not up for negotiation. What CAN be put away is a run of tool calls with
- * nothing between them: twenty greps and reads in a row is the "far too much
- * stuff" the maintainer objected to (2026-08-27), and it is also the part of
- * a finished turn nobody re-reads.
- */
-export type TurnGroup =
- | { kind: "tools"; id: string; blocks: ToolBlock[] }
- | { kind: "block"; id: string; block: TextBlock | ReasoningBlock };
-
-export function groupSteps(blocks: TurnBlock[]): TurnGroup[] {
- const out: TurnGroup[] = [];
- for (const block of blocks) {
- if (block.kind === "tool") {
- const last = out[out.length - 1];
- if (last && last.kind === "tools") {
- last.blocks.push(block);
- continue;
- }
- out.push({ kind: "tools", id: `g-${block.callId}`, blocks: [block] });
- continue;
- }
- out.push({ kind: "block", id: block.id, block });
- }
- return out;
-}
-
-/** From this many calls in a row, a finished run puts itself away. */
-export const FOLD_STEPS_FROM = 4;
-
-/**
- * A run of tool calls — open while it matters, one line once it does not.
- *
- * WHILE THE TURN WORKS every step shows: watching the work is the whole point
- * of a running turn, and a spinner behind a fold proves nothing. The moment
- * the turn is done a long run collapses to "14 steps · +42 -7 · 1m 12s",
- * which is what a finished conversation should read as — the answer, with the
- * work one click away.
- *
- * Two runs never fold, however long: one holding a step that FAILED, and one
- * holding a step still waiting for a decision. Both are the reason the person
- * is looking at the turn at all.
- */
-function ToolGroup({
- blocks,
- turnLive,
- onDecide,
-}: {
- blocks: ToolBlock[];
- turnLive: boolean;
- onDecide: (approvalId: string, decision: ApprovalDecision) => void;
-}) {
- const [manual, setManual] = useState<boolean | null>(null);
- // A call still waiting for a decision is a question to the person: it holds
- // the whole run open, because an approval behind a fold is an approval
- // nobody gives. A call that FAILED does not — it stays in view on its own
- // while the rest of the run folds away around it.
- const asking = blocks.some((b) => b.approval !== null && b.approval.decision === null);
- const foldable = !turnLive && !asking && blocks.length >= FOLD_STEPS_FROM;
- const open = !foldable || (manual ?? false);
- const shown = open ? blocks : blocks.filter((b) => b.isError);
- const duration = blocks.reduce((sum, b) => sum + (b.durationMs ?? 0), 0);
- const stat = useMemo(() => {
- const files = blocks.flatMap((b) => toolDiff(b.name, b.input) ?? []);
- return files.length ? diffStat(files) : null;
- }, [blocks]);
-
- return (
- <div
- className="flex min-w-0 flex-col gap-1.5"
- data-testid="agent-tool-group"
- data-state={!foldable ? "plain" : open ? "open" : "folded"}
- data-steps={blocks.length}
- >
- {foldable && (
- <GroupToggle
- open={open}
- count={blocks.length}
- duration={duration}
- stat={stat}
- onClick={() => setManual(!open)}
- />
- )}
- {shown.map((b) => (
- <ToolRow key={b.callId} block={b} onDecide={onDecide} />
- ))}
- </div>
- );
-}
-
-/** The one line a folded run wears, and the way back out of an open one. */
-function GroupToggle({
- open,
- count,
- duration,
- stat,
- onClick,
-}: {
- open: boolean;
- count: number;
- duration: number;
- stat: { added: number; removed: number } | null;
- onClick: () => void;
-}) {
- const t = useT();
- return (
- <button
- type="button"
- onClick={onClick}
- aria-expanded={open}
- data-testid="agent-tool-group-toggle"
- className={cn(
- "-ml-1 flex w-full min-w-0 items-center gap-2 rounded-md px-1 py-1",
- "text-left text-xs transition-colors hover:bg-secondary",
- )}
- >
- <ChevronRight
- className={cn(
- "h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform",
- open && "rotate-90",
- )}
- aria-hidden
- />
- <span className="shrink-0 font-medium text-muted-foreground">
- {fill(t("agent_chat.steps_count"), { count: String(count) })}
- </span>
- {stat && <DiffStat added={stat.added} removed={stat.removed} />}
- <span className="flex-1" />
- {duration > 0 && (
- <span className="shrink-0 font-mono text-micro tabular-nums text-muted-foreground">
- {formatStepDuration(duration)}
- </span>
- )}
- </button>
- );
-}
-
-/**
- * One tool call — a ROW, not a card.
- *
- * The name is the agent's own — "PowerShell", "ToolSearch", "Grep" — never a
- * prettied-up rename, because the row is read next to the agent's log
- * (maintainer, 2026-08-23). The mark left of it comes from the tool family,
- * or the vendor's SVG for an MCP server. On the right sits the one thing
- * the person is actually asking of a running agent: whether this step is
- * still going. A finished call shows what it took; a running one counts up.
- *
- * A call that failed says why on the row itself, in one line — the point of
- * a failure is that you read it without hunting for it. Click to see the
- * whole of it, and the input when the summary did not already carry it.
- */
-function ToolRow({
- block,
- onDecide,
-}: {
- block: ToolBlock;
- onDecide: (approvalId: string, decision: ApprovalDecision) => void;
-}) {
- const t = useT();
- const [open, setOpen] = useState(false);
- const [logoFailed, setLogoFailed] = useState(false);
- const pending = Boolean(block.approval && block.approval.decision === null);
- const denied = block.approval?.decision === "deny" || block.approval?.decision === "cancel";
- const running = block.output === null && !pending && !denied;
- const done = block.output !== null;
- const elapsed = useElapsedMs(running ? block.startedMs : null);
- const view = agentToolView(block.name, block.input);
- const summary = view.summary;
- const showLogo = Boolean(view.logoUrl) && !logoFailed;
- const gist = block.isError && block.output ? errorGist(block.output) : "";
- const showInput = !inputAddsNothing(block.input, summary);
- // A coding call carries its change in its arguments. Read it once here: the
- // row wears the size of it, the fold paints the whole thing.
- const diff = useMemo(() => toolDiff(block.name, block.input), [block.name, block.input]);
- const stat = diff ? diffStat(diff) : null;
-
- return (
- <div
- data-testid="agent-tool"
- data-tool={block.name}
- data-family={view.family}
- data-state={
- pending
- ? "pending"
- : denied
- ? "denied"
- : done
- ? block.isError
- ? "error"
- : "done"
- : "running"
- }
- className={cn(
- "text-xs",
- // Only a call that WANTS something gets a frame of its own: an
- // approval is a question to the person, not a log line.
- pending && "rounded-lg border border-primary/40 bg-primary/5",
- )}
- >
- <button
- type="button"
- onClick={() => setOpen((v) => !v)}
- aria-expanded={open}
- className={cn(
- "-ml-1 flex w-full min-w-0 items-center gap-2 rounded-md px-1 py-1 text-left transition-colors",
- pending ? "ml-0 px-2 pt-1.5" : "hover:bg-secondary",
- )}
- >
- <span className="grid h-4 w-4 shrink-0 place-items-center">
- {pending ? (
- <ShieldQuestion className="h-3.5 w-3.5 text-primary" aria-hidden />
- ) : showLogo ? (
- <img
- src={view.logoUrl}
- alt=""
- className="h-3.5 w-3.5"
- loading="lazy"
- onError={() => setLogoFailed(true)}
- />
- ) : (
- <view.Icon
- className={cn(
- "h-3.5 w-3.5",
- block.isError ? "text-destructive" : "text-muted-foreground",
- )}
- aria-hidden
- />
- )}
- </span>
- <span
- className={cn(
- "shrink-0 font-mono font-medium",
- block.isError ? "text-destructive" : "text-foreground",
- )}
- >
- {view.label}
- </span>
- {summary ? (
- <span className="min-w-0 flex-1 truncate font-mono text-micro text-muted-foreground">
- {summary}
- </span>
- ) : (
- <span className="flex-1" />
- )}
- {stat && !running && <DiffStat added={stat.added} removed={stat.removed} />}
- {running ? (
- <span className="inline-flex shrink-0 items-center gap-1.5 text-micro text-primary/90">
- <Spinner />
- <span className="font-mono tabular-nums">{formatStepDuration(elapsed)}</span>
- </span>
- ) : block.durationMs !== null && block.durationMs > 0 ? (
- <span className="shrink-0 font-mono text-micro tabular-nums text-muted-foreground">
- {formatStepDuration(block.durationMs)}
- </span>
- ) : null}
- <ChevronRight
- className={cn(
- "h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform",
- open && "rotate-90",
- )}
- aria-hidden
- />
- </button>
-
- {gist && !open && (
- <div
- className="ml-[1.375rem] truncate font-mono text-micro text-destructive"
- data-testid="agent-tool-gist"
- >
- {gist}
- </div>
- )}
-
- {pending && block.approval && (
- <div className="flex flex-col gap-2 px-2 pb-2" data-testid="agent-approval">
- <div className="text-foreground">
- <span className="font-medium">{t("agent_chat.approval_title")}</span>{" "}
- <span className="text-muted-foreground">{block.approval.summary || summary}</span>
- </div>
- <div className="flex flex-wrap items-center gap-1.5">
- <button
- type="button"
- onClick={() => onDecide(block.approval!.approvalId, "allow")}
- className="inline-flex h-7 items-center gap-1 rounded-md bg-foreground/70 px-2.5 text-xs font-medium text-primary-foreground hover:bg-primary/90"
- data-testid="approval-allow"
- >
- <Check className="h-3.5 w-3.5" aria-hidden />
- {t("agent_chat.approval_allow")}
- </button>
- <button
- type="button"
- onClick={() => onDecide(block.approval!.approvalId, "allow_always")}
- className="inline-flex h-7 items-center rounded-md border border-border px-2.5 text-xs font-medium text-foreground hover:bg-secondary"
- data-testid="approval-always"
- >
- {t("agent_chat.approval_always")}
- </button>
- <button
- type="button"
- onClick={() => onDecide(block.approval!.approvalId, "deny")}
- className="inline-flex h-7 items-center gap-1 rounded-md border border-border px-2.5 text-xs font-medium text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
- data-testid="approval-deny"
- >
- <X className="h-3.5 w-3.5" aria-hidden />
- {t("agent_chat.approval_deny")}
- </button>
- </div>
- </div>
- )}
-
- {open && (
- <Trace tone={block.isError ? "error" : "plain"}>
- {diff ? (
- <DiffView files={diff} />
- ) : (
- showInput && <Detail label={t("agent_chat.tool_input")} text={pretty(block.input)} />
- )}
- {denied && <div className="text-muted-foreground">{t("agent_chat.approval_denied")}</div>}
- {block.output !== null
- ? // An edit's receipt — "The file … has been updated successfully" —
- // says nothing the diff above did not already show, so a call that
- // painted its change keeps its output for the case that matters:
- // when it failed.
- (!diff || block.isError) && (
- <Detail
- label={block.isError ? t("agent_chat.tool_error") : t("agent_chat.tool_output")}
- text={block.output}
- error={block.isError}
- />
- )
- : running && (
- <div className="text-muted-foreground">{t("agent_chat.tool_running")}</div>
- )}
- </Trace>
- )}
- </div>
- );
-}
-
-/**
- * The one shape an opened detail wears: an indent and a hairline.
- *
- * Every unfolded thing in the column — a thought, a tool's input, its
- * output — is drawn this way, so the turn reads as one document with
- * margins rather than a stack of framed cards.
- */
-function Trace({
- children,
- tone = "plain",
-}: {
- children: ReactNode;
- tone?: "plain" | "error";
-}) {
- return (
- <div
- className={cn(
- "ml-[0.375rem] mt-1 flex flex-col gap-2 border-l pl-3",
- tone === "error" ? "border-destructive/40" : "border-border",
- )}
- >
- {children}
- </div>
- );
-}
-
-function Detail({ label, text, error }: { label: string; text: string; error?: boolean }) {
- return (
- <div className="flex flex-col gap-0.5">
- <span className="font-mono text-micro text-muted-foreground">
- {label}
- </span>
- <pre
- className={cn(
- "scrollbar-jarvis max-h-72 overflow-auto whitespace-pre-wrap break-words font-mono text-xs leading-relaxed",
- error ? "text-destructive" : "text-muted-foreground",
- )}
- >
- {text}
- </pre>
- </div>
- );
-}
-
-function formatStepDuration(ms: number): string {
- if (ms < 10_000) return `${(ms / 1000).toFixed(1)}s`;
- return formatThoughtDuration(ms);
-}
-
-function Spinner() {
- return (
- <span
- aria-hidden
- data-testid="agent-spinner"
- className="inline-block h-3 w-3 rounded-full border-2 border-primary/25 border-t-primary motion-safe:animate-spin"
- />
- );
-}
-
-/**
- * Elapsed wall-clock since `startedTs`, ticking while set.
- *
- * Twice a second, not once: the number beside a live glyph is the proof
- * that something is happening, and a second-long freeze on a 1 s cadence
- * reads as a hang.
- */
-function useElapsedMs(startedTs: number | null): number {
- const [now, setNow] = useState(() => Date.now());
- useEffect(() => {
- if (startedTs === null) return;
- setNow(Date.now());
- const id = window.setInterval(() => setNow(Date.now()), 500);
- return () => window.clearInterval(id);
- }, [startedTs]);
- return startedTs === null ? 0 : Math.max(0, now - startedTs);
-}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/VoiceWorkTrace.tsx b/jarvis/ui/web/frontend/src/components/agentchat/VoiceWorkTrace.tsx
new file mode 100644
index 0000000000..14d8370407
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/VoiceWorkTrace.tsx
@@ -0,0 +1,31 @@
+import { useMemo } from "react";
+import { useT } from "@/i18n";
+import type { ThinkingStep } from "@/lib/thinkingSteps";
+import type { TurnBlock } from "./reduce";
+import { WorkTrace } from "./WorkTrace";
+
+/** 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} />;
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.test.tsx
new file mode 100644
index 0000000000..94fd58b240
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.test.tsx
@@ -0,0 +1,115 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { groupTrace, WorkTrace, traceDuration } from "./WorkTrace";
+import type { ToolBlock, TurnBlock, TurnStatus } from "./reduce";
+
+const tool = (id: string, over: Partial<ToolBlock> = {}): ToolBlock => ({
+ kind: "tool", callId: id, name: "read_file", input: { path: `${id}.ts` }, output: `Contents of ${id}`,
+ isError: false, durationMs: 800, approval: null, startedMs: 1000, ...over,
+});
+const thought: TurnBlock = { kind: "reasoning", id: "reason", text: "**Check** the input.", live: false, durationMs: 8000, startedMs: 1000 };
+const props = { startedMs: 1000, durationMs: 12000, status: "done" as TurnStatus };
+afterEach(() => { cleanup(); vi.useRealTimers(); });
+
+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} />);
+ 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"));
+ expect(text.indexOf("Next, check")).toBeLessThan(text.indexOf("b.ts"));
+ expect(text.indexOf("b.ts")).toBeLessThan(text.indexOf("Everything is ready"));
+ expect(text.indexOf("Everything is ready")).toBeLessThan(text.indexOf("Done"));
+ });
+
+ 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} />);
+ const group = screen.getByRole("button", { name: "Read 14 files" });
+ expect(group.getAttribute("aria-expanded")).toBe("false");
+ expect(screen.queryByText("file0.ts")).toBeNull();
+ fireEvent.click(group);
+ fireEvent.click(screen.getByRole("button", { name: /Read file file0.ts/ }));
+ expect(screen.getByText('"path": "file0.ts"', { exact: false })).toBeTruthy();
+ expect(screen.getByText("Contents of file0")).toBeTruthy();
+ expect(screen.getByText("read_file")).toBeTruthy();
+ });
+
+ it("never groups across reasoning, errors, approvals, active calls or mutations", () => {
+ const blocks: TurnBlock[] = [tool("a"), thought, tool("b"), tool("err", {isError:true}), tool("c"), tool("approve", {approval:{approvalId:"ap",summary:"Confirm",decision:null}}), tool("d"), tool("running", {output:null}), tool("e"), tool("write1", {name:"write_file"}), tool("write2", {name:"write_file"})];
+ expect(groupTrace(blocks)).toHaveLength(blocks.length);
+ });
+
+ it("automatically collapses completed groups even after live interaction", () => {
+ const blocks = [tool("a"), tool("b")];
+ const { rerender } = render(<WorkTrace {...props} status="running" blocks={blocks} />);
+ const 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");
+ });
+
+ 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();
+ expect(screen.getByText("Delete generated files?")).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 => {
+ const calls: string[] = [];
+ let reject!: (error: Error) => void;
+ const onDecide = (id: string, value: string) => { calls.push(`${id}:${value}`); return new Promise<void>((_, fail) => { reject = fail; }); };
+ render(<WorkTrace {...props} status="running" blocks={[tool("ap",{output:null,approval:{approvalId:"approval-id",summary:"Confirm this action",decision:null}})]} onDecide={onDecide} />);
+ const name = {allow:"Approve",allow_always:"Always allow",deny:"Deny"}[decision];
+ const button = screen.getByRole("button", {name});
+ fireEvent.click(button); fireEvent.click(button);
+ expect(calls).toEqual([`approval-id:${decision}`]);
+ await act(async () => reject(new Error("Could not save decision")));
+ expect(screen.getByRole("alert").textContent).toBe("Could not save decision");
+ await waitFor(() => expect((button as HTMLButtonElement).disabled).toBe(false));
+ });
+
+ it("shows a denied action without a running indicator", () => {
+ const {container} = render(<WorkTrace {...props} status="running" blocks={[tool("a",{output:null,approval:{approvalId:"ap",summary:"Delete?",decision:"deny"}})]} />);
+ expect(container.querySelector('[data-state="denied"]')).toBeTruthy();
+ expect(screen.queryByRole("button", {name:"Approve"})).toBeNull();
+ });
+
+ it("renders edit input, a diff and output on demand", () => {
+ render(<WorkTrace {...props} blocks={[tool("edit",{name:"Edit",input:{file_path:"app.ts",old_string:"oldValue",new_string:"newValue"},output:"File updated"})]} />);
+ fireEvent.click(screen.getByRole("button",{name:/Edit/}));
+ 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})]} />);
+ expect(container.querySelector('[data-state="interrupted"]')).toBeTruthy();
+ expect(container.querySelector('[data-state="running"]')).toBeNull();
+ });
+
+ it("updates the live clock and releases timers at completion", () => {
+ vi.useFakeTimers(); vi.setSystemTime(1000);
+ const {rerender} = render(<WorkTrace {...props} durationMs={null} status="running" blocks={[]} />);
+ act(() => vi.advanceTimersByTime(3000));
+ expect(screen.getByRole("status").textContent).toContain("3.0s");
+ rerender(<WorkTrace {...props} blocks={[]} />);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ 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/}));
+ expect(container.querySelector('img')).toBeNull();
+ expect(screen.getByText('<img src=x onerror=alert(1)>')).toBeTruthy();
+ });
+
+ it("formats durations without a 60-second remainder", () => {
+ expect(traceDuration(119999)).toBe("1m 59s");
+ expect(traceDuration(-1)).toBe("0.0s");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx
new file mode 100644
index 0000000000..4d87cc7189
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx
@@ -0,0 +1,230 @@
+import { memo, useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
+import { Brain, Check, ChevronRight, CircleAlert, CircleDashed, ShieldQuestion, Wrench } from "lucide-react";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { describeToolStep } from "@/lib/toolStepLabel";
+import type { ApprovalDecision } from "@/lib/agentChatApi";
+import type { ReasoningBlock, ToolBlock, TurnBlock, TurnItem, TurnStatus } from "./reduce";
+import { toolDiff } from "./toolDiff";
+import { formatTokens, outputTokens } from "./toolView";
+
+export type Decide = (id: string, decision: ApprovalDecision) => void | Promise<void>;
+type Group = { id: string; blocks: TurnBlock[]; family: string | null };
+
+export function traceDuration(ms: number): string {
+ const seconds = Math.max(0, ms) / 1000;
+ if (seconds < 10) return `${seconds.toFixed(1)}s`;
+ if (seconds < 60) return `${Math.floor(seconds)}s`;
+ return `${Math.floor(seconds / 60)}m ${String(Math.floor(seconds % 60)).padStart(2, "0")}s`;
+}
+
+function useClock(start: number, live: boolean) {
+ const [now, setNow] = useState(Date.now);
+ useEffect(() => {
+ if (!live) return;
+ setNow(Date.now());
+ const timer = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(timer);
+ }, [start, live]);
+ return Math.max(0, now - start);
+}
+
+function operation(name: string): string | null {
+ const key = name.toLowerCase().replace(/[-_]/g, "");
+ if (/^(read|readfile|viewfile|cat|openfile|readmediafile)$/.test(key)) return "read";
+ if (/^(ls|listdir|listdirectory|listfiles|glob)$/.test(key)) return "list";
+ if (/^(grep|rg|search|searchfiles|grepsearch|codesearch|findbyname)$/.test(key)) return "search";
+ return null;
+}
+
+function attention(block: ToolBlock) {
+ return block.isError || Boolean(block.approval);
+}
+
+/** Only adjacent, successful, read-only operations may lose individual rows. */
+export function groupTrace(blocks: TurnBlock[]): Group[] {
+ const groups: Group[] = [];
+ for (const block of blocks) {
+ const family = block.kind === "tool" && !attention(block) && block.output !== null ? operation(block.name) : null;
+ const previous = groups[groups.length - 1];
+ if (family && previous?.family === family) previous.blocks.push(block);
+ else groups.push({ id: block.kind === "tool" ? block.callId : block.id, blocks: [block], family });
+ }
+ return groups;
+}
+
+function pretty(value: unknown): string {
+ if (typeof value === "string") return value;
+ return JSON.stringify(value, null, 2) ?? "";
+}
+
+const rowButton = "flex w-full min-w-0 items-start gap-2.5 rounded-sm py-2 text-left text-sm leading-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring hover:text-foreground";
+const iconClass = "mt-0.5 h-4 w-4 shrink-0";
+
+function Disclosure({ label, children, forced = false, initiallyOpen = false, icon, trailing, tone, summary }: {
+ label: ReactNode; children?: ReactNode; forced?: boolean; initiallyOpen?: boolean;
+ icon: ReactNode; trailing?: ReactNode; tone?: string; summary?: ReactNode;
+}) {
+ const id = useId();
+ // A manual choice during a live turn must not prevent completion folding.
+ const [choice, setChoice] = useState<{ phase: boolean; open: boolean } | null>(null);
+ const open = forced || (choice?.phase === initiallyOpen ? choice.open : initiallyOpen);
+ return (
+ <div className={cn("min-w-0 text-muted-foreground", tone)}>
+ <button type="button" className={rowButton} aria-expanded={children ? open : undefined}
+ aria-controls={children ? id : undefined} disabled={!children || forced}
+ onClick={() => setChoice({ phase: initiallyOpen, open: !open })}>
+ {icon}
+ <span className="min-w-0 flex-1 [overflow-wrap:anywhere]">{label}</span>
+ {trailing ? <span className="shrink-0 text-xs tabular-nums">{trailing}</span> : null}
+ {children ? <ChevronRight aria-hidden className={cn(iconClass, "h-3.5 w-3.5", open && "rotate-90")} /> : null}
+ </button>
+ {summary}
+ {children && open ? <div id={id} className="ml-[7px] min-w-0 border-l border-border pb-2 pl-6">{children}</div> : null}
+ </div>
+ );
+}
+
+export function ReasoningTrace({ block, turnLive }: { block: ReasoningBlock; turnLive: boolean }) {
+ const t = useT();
+ const live = turnLive && block.live;
+ const elapsed = useClock(block.startedMs, live);
+ const text = block.text.trim();
+ const duration = live ? elapsed : block.durationMs;
+ const label = duration === null ? t("work_trace.thought")
+ : t(live ? "work_trace.thinking_for" : "work_trace.thought_for").replace("{duration}", traceDuration(duration));
+ const gist = text.replace(/```[\s\S]*?```/g, " ").replace(/[`*_#>~]/g, "").replace(/\s+/g, " ").trim();
+ return <Disclosure label={label} icon={<Brain aria-hidden className={cn(iconClass, live && "motion-safe:animate-pulse")} />}
+ forced={live} initiallyOpen={turnLive}
+ summary={!turnLive && gist ? <p className="mb-2 ml-6 line-clamp-2 text-xs leading-5">{gist.slice(0, 240)}</p> : undefined}>
+ {text ? <div className="prose prose-sm max-h-64 max-w-none overflow-auto text-xs leading-6 text-muted-foreground dark:prose-invert [overflow-wrap:anywhere] prose-p:my-1 prose-pre:overflow-auto">
+ <ReactMarkdown remarkPlugins={[remarkGfm]}>{text}</ReactMarkdown>
+ </div> : undefined}
+ </Disclosure>;
+}
+
+function ToolDetails({ block }: { block: ToolBlock }) {
+ const t = useT();
+ const diff = useMemo(() => toolDiff(block.name, block.input), [block.name, block.input]);
+ return <div className="space-y-3 py-1 text-xs">
+ <Detail label={t("work_trace.tool")} text={block.name} />
+ {block.input !== undefined && block.input !== null ? <Detail label={t("work_trace.input")} text={pretty(block.input)} /> : null}
+ {diff ? <div aria-label={t("work_trace.diff")} className="max-h-72 overflow-auto font-mono text-xs">
+ {diff.map((file, i) => <div key={i} className="mb-2">
+ <p className="mb-1 [overflow-wrap:anywhere]">{file.path}</p>
+ {file.lines.map((line, n) => <div key={n} className={cn("whitespace-pre-wrap [overflow-wrap:anywhere]", line.kind === "add" && "diff-line-add", line.kind === "del" && "diff-line-del")}>
+ {line.kind === "add" ? "+ " : line.kind === "del" ? "− " : " "}{line.text}
+ </div>)}
+ {file.truncated > 0 ? <p>{t("work_trace.truncated").replace("{count}", String(file.truncated))}</p> : null}
+ </div>)}
+ </div> : null}
+ {block.output !== null ? <Detail label={t(block.isError ? "work_trace.error" : "work_trace.output")} text={block.output || t("work_trace.empty_output")} /> : null}
+ </div>;
+}
+
+function Detail({ label, text }: { label: string; text: string }) {
+ return <div><p className="mb-1 font-medium text-foreground">{label}</p>
+ <pre tabIndex={0} className="max-h-64 overflow-auto whitespace-pre-wrap font-mono text-xs leading-5 [overflow-wrap:anywhere] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring">{text}</pre>
+ </div>;
+}
+
+export const TraceTool = memo(function TraceTool({ block, status, onDecide }: { block: ToolBlock; status: TurnStatus; onDecide?: Decide }) {
+ const t = useT();
+ const pending = Boolean(block.approval && block.approval.decision === null);
+ const denied = block.approval?.decision === "deny";
+ const running = status === "running" && block.output === null && !pending && !denied;
+ const elapsed = useClock(block.startedMs, running);
+ const [busy, setBusy] = useState(false);
+ const submitting = useRef(false);
+ const [error, setError] = useState<string | null>(null);
+ const family = operation(block.name);
+ const description = describeToolStep(block.name, (block.input && typeof block.input === "object" ? block.input : {}) as Record<string, unknown>);
+ const readable = description.label.charAt(0).toUpperCase() + description.label.slice(1);
+ const action = /^(bash|powershell|shell|run_shell|exec_command|run_command)$/i.test(block.name) ? "command"
+ : /^(edit|edit_file|apply_patch|multi_edit|str_replace)$/i.test(block.name) ? "edit"
+ : /^(write|write_file|create_file)$/i.test(block.name) ? "write" : family;
+ const label = action ? t(`work_trace.${action}`) : description.labelKey ? t(description.labelKey) : readable;
+ const detail = description.detail || (typeof block.input === "object" && block.input !== null
+ ? String((block.input as Record<string, unknown>).file_path ?? (block.input as Record<string, unknown>).path ?? "") : "");
+ const state = pending ? "approval" : denied ? "denied" : block.isError ? "failed" : running ? "running" : block.output === null ? "interrupted" : "completed";
+ const Icon = pending ? ShieldQuestion : block.isError ? CircleAlert : running ? CircleDashed : Wrench;
+ const decide = async (decision: ApprovalDecision) => {
+ if (!onDecide || !block.approval || submitting.current) return;
+ submitting.current = true;
+ setBusy(true);
+ setError(null);
+ try { await onDecide(block.approval.approvalId, decision); }
+ catch (err) { setError(err instanceof Error ? err.message : String(err)); }
+ finally { submitting.current = false; setBusy(false); }
+ };
+ return <div data-trace-tool={block.callId} data-state={state}>
+ <Disclosure label={<>{label}{detail ? <span className="ml-2 text-xs text-muted-foreground">{" "}{detail}</span> : null}</>}
+ icon={<Icon aria-hidden className={cn(iconClass, running && "motion-safe:animate-spin")} />}
+ trailing={running ? traceDuration(elapsed) : block.durationMs !== null ? traceDuration(block.durationMs) : undefined}
+ tone={block.isError ? "text-destructive" : pending ? "text-foreground" : undefined}
+ summary={<>
+ {state !== "completed" ? <p className={cn("mb-1 ml-6 text-xs", block.isError && "text-destructive")}>{t(`work_trace.${state}`)}</p> : null}
+ {block.isError && block.output ? <p className="mb-2 ml-6 whitespace-pre-wrap text-xs text-destructive [overflow-wrap:anywhere]">{block.output.slice(0, 500)}</p> : null}
+ </>}>
+ <ToolDetails block={block} />
+ </Disclosure>
+ {pending ? <div className="mb-3 ml-6 space-y-2 text-sm" role="group" aria-label={t("work_trace.approval")}>
+ <p className="[overflow-wrap:anywhere]">{block.approval?.summary}</p>
+ {onDecide ? <div className="flex flex-wrap gap-2">
+ {(["allow", "allow_always", "deny"] as const).map(decision => <button key={decision} type="button" disabled={busy}
+ onClick={() => void decide(decision)} className="rounded-md border border-border px-3 py-1.5 text-xs text-foreground hover:bg-secondary focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50">
+ {t(`work_trace.${decision}`)}
+ </button>)}
+ </div> : <p className="text-xs text-muted-foreground">{t("work_trace.approval_elsewhere")}</p>}
+ {error ? <p role="alert" className="text-xs text-destructive">{error}</p> : null}
+ </div> : null}
+ </div>;
+});
+
+export function WorkTrace({ blocks, status, startedMs, durationMs, error, onDecide, renderText, className, receipt, completionLabel }: {
+ 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;
+}) {
+ const t = useT();
+ const live = status === "running";
+ const elapsed = useClock(startedMs, live);
+ const groups = useMemo(() => groupTrace(blocks), [blocks]);
+ const pending = blocks.some(block => block.kind === "tool" && block.approval?.decision === null);
+ const outcome = pending ? "approval" : live ? "working" : status === "error" ? "failed" : status === "cancelled" ? "stopped" : "done";
+ const Icon = pending ? ShieldQuestion : live ? CircleDashed : status === "error" ? CircleAlert : Check;
+ return <div className={cn("min-w-0 space-y-0.5", className)} data-testid="work-trace" data-state={status}>
+ {groups.map(group => {
+ const first = group.blocks[0];
+ if (group.blocks.length > 1) return <Disclosure key={group.id}
+ label={t(`work_trace.group_${group.family}`).replace("{count}", String(group.blocks.length))}
+ icon={<Check aria-hidden className={iconClass} />} initiallyOpen={live}>
+ {group.blocks.map(block => <TraceTool key={(block as ToolBlock).callId} block={block as ToolBlock} status={status} onDecide={onDecide} />)}
+ </Disclosure>;
+ if (first.kind === "tool") return <TraceTool key={group.id} block={first} status={status} onDecide={onDecide} />;
+ if (first.kind === "reasoning") return <ReasoningTrace key={group.id} block={first} turnLive={live} />;
+ return first.text.trim() ? <div key={group.id} className="min-w-0 py-2">{renderText ? renderText(first.text, first.id) : <div className="prose prose-sm max-w-none text-foreground dark:prose-invert [overflow-wrap:anywhere]"><ReactMarkdown remarkPlugins={[remarkGfm]}>{first.text}</ReactMarkdown></div>}</div> : null;
+ })}
+ {error ? <p role="alert" className="py-2 text-sm text-destructive [overflow-wrap:anywhere]">{error}</p> : null}
+ <div role="status" aria-live="polite" className={cn("flex flex-wrap items-center gap-2 border-t border-border pt-3 text-xs text-muted-foreground", status === "error" && "text-destructive")}>
+ <Icon aria-hidden className={cn("h-3.5 w-3.5", live && !pending && "motion-safe:animate-spin")} />
+ <span>{outcome === "done" && completionLabel ? completionLabel : t(`work_trace.${outcome}`)}</span>
+ {(live || durationMs !== null) ? <span aria-live="off" className="tabular-nums">{traceDuration(live ? elapsed : durationMs ?? 0)}</span> : null}
+ {receipt}
+ </div>
+ </div>;
+}
+
+export function TurnTrace({ turn, ...props }: { turn: TurnItem; onDecide?: Decide; renderText?: (text: string, id: string) => ReactNode }) {
+ const t = useT();
+ const 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}
+ completionLabel={!answered ? t("agent_chat.turn_no_answer") : undefined}
+ receipt={<>
+ {tokens !== null && tokens > 0 ? <span aria-live="off" className="tabular-nums">{formatTokens(tokens)} {t("agent_chat.tokens")}</span> : null}
+ {turn.costUsd !== null && turn.costUsd > 0 ? <span className="tabular-nums">${turn.costUsd.toFixed(4)}</span> : null}
+ </>} />;
+}
diff --git a/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx b/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx
index 6808dd92d6..d2f9f07b54 100644
--- a/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx
@@ -402,27 +402,12 @@ describe("ChatStage (agent chat)", () => {
expect(screen.getByTestId("composer-plan").getAttribute("aria-checked")).toBe("false");
});
- it("grows the text box with the typed text and caps it at its max height", () => {
+ it("accepts a prompt through the current rich text composer", () => {
render(<ChatStage />);
- const box = screen.getByPlaceholderText("Ask anything…") as HTMLTextAreaElement;
- // jsdom has no layout: stand in for scrollHeight and the max-height rule.
- let scrollHeight = 48;
- Object.defineProperty(box, "scrollHeight", { configurable: true, get: () => scrollHeight });
- const computed = vi.spyOn(window, "getComputedStyle").mockImplementation(
- () => ({ maxHeight: "192px" }) as CSSStyleDeclaration,
- );
- try {
- scrollHeight = 120;
- fireEvent.change(box, { target: { value: "one two three four five" } });
- expect(box.style.height).toBe("120px");
- expect(box.style.overflowY).toBe("hidden");
- scrollHeight = 400;
- fireEvent.change(box, { target: { value: "a much longer prompt".repeat(40) } });
- expect(box.style.height).toBe("192px");
- expect(box.style.overflowY).toBe("auto");
- } finally {
- computed.mockRestore();
- }
+ const box = screen.getByRole("textbox");
+ box.textContent = "Check this trace";
+ fireEvent.input(box);
+ expect((screen.getByTestId("composer-send") as HTMLButtonElement).disabled).toBe(false);
});
it("shows no restart notice when the catalog carries the permission ladders", () => {
@@ -457,9 +442,9 @@ describe("ChatStage (agent chat)", () => {
const turn = screen.getByTestId("agent-turn");
expect(turn.textContent).toContain("Anthropic Claude");
expect(turn.textContent).toContain("claude-opus-5");
- const tool = within(turn).getByTestId("agent-tool");
- expect(tool.getAttribute("data-tool")).toBe("Bash");
- expect(tool.getAttribute("data-state")).toBe("done");
+ const tool = turn.querySelector<HTMLElement>("[data-trace-tool]")!;
+ expect(tool.textContent).toContain("Run command");
+ expect(tool.getAttribute("data-state")).toBe("completed");
// The row opens to show input and output.
fireEvent.click(within(tool).getByRole("button"));
expect(tool.textContent).toContain("a.py");
@@ -547,10 +532,10 @@ describe("ChatStage (agent chat)", () => {
]);
useAgentChatStore.setState({ activeSessionId: "s2", timeline, decide });
render(<ChatStage />);
- const card = screen.getByTestId("agent-approval");
+ const card = screen.getByRole("group", { name: "Approval required" });
expect(card.textContent).toContain("rm x");
act(() => {
- fireEvent.click(within(card).getByTestId("approval-allow"));
+ fireEvent.click(within(card).getByRole("button", { name: "Approve" }));
});
expect(decide).toHaveBeenCalledWith("a1", "allow");
// The composer offers Stop while the turn runs.
@@ -575,8 +560,8 @@ describe("ChatStage (agent chat)", () => {
// the duplication the maintainer objected to (2026-08-25).
expect(screen.queryByTestId("agent-reasoning")).toBeNull();
- const live = screen.getByTestId("agent-turn-live");
- expect(within(live).getByTestId("live-core")).toBeTruthy();
+ const live = within(screen.getByTestId("work-trace")).getByRole("status");
+ expect(live.textContent).toContain("Working");
expect(live.textContent).toMatch(/4\.8k/);
// Output only: the input side of a CLI re-counts the whole conversation
// on every step, so it reads as an absurd number for one question.
@@ -614,18 +599,12 @@ describe("ChatStage (agent chat)", () => {
useAgentChatStore.setState({ activeSessionId: "s4", timeline });
render(<ChatStage />);
- const rows = screen.getAllByTestId("agent-reasoning");
- expect(rows).toHaveLength(2);
- // Each thought keeps its own time and shows its words without a click.
- expect(rows[0].textContent).toMatch(/1s/);
- expect(rows[0].textContent).toContain("First the port.");
- expect(rows[1].textContent).toMatch(/4s/);
- expect(rows[1].textContent).toContain("It is listening.");
- // Thought, command, thought — the order they happened in.
- const order = Array.from(
- document.querySelectorAll("[data-testid='agent-reasoning'],[data-testid='agent-tool']"),
- ).map((el) => el.getAttribute("data-testid"));
- expect(order).toEqual(["agent-reasoning", "agent-tool", "agent-reasoning"]);
+ 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!;
+ expect(text.indexOf("First the port.")).toBeLessThan(text.indexOf("Get-NetTCPConnection"));
+ expect(text.indexOf("Get-NetTCPConnection")).toBeLessThan(text.indexOf("It is listening."));
});
it("says how a turn ended — including one that answered nothing at all", () => {
@@ -642,18 +621,18 @@ describe("ChatStage (agent chat)", () => {
useAgentChatStore.setState({ activeSessionId: "s4", timeline });
render(<ChatStage />);
- const outcome = screen.getByTestId("agent-turn-footer");
- expect(outcome.getAttribute("data-outcome")).toBe("no-answer");
+ const outcome = within(screen.getByTestId("work-trace")).getByRole("status");
+ expect(outcome.textContent).toContain("Finished without an answer");
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.getByTestId("agent-tool-gist").textContent).toContain("permission check failed");
+ expect(screen.getByText(/permission check failed for command/).textContent).toContain("permission check failed");
// Nothing claims to still be working.
expect(screen.queryByTestId("agent-turn-live")).toBeNull();
});
- it("does not print a tool's input twice when the row already says it", () => {
+ it("keeps full tool input behind the detail disclosure", () => {
const timeline = reduceEvents(EMPTY_TIMELINE, [
ev("turn_started", { turn_id: "t5", provider: "claude-api", model: "claude-opus-5", effort: "high", runner: "claude-cli" }),
ev("tool_call", { turn_id: "t5", call_id: "c1", name: "Bash", input: { command: "ls -la" } }),
@@ -665,10 +644,10 @@ describe("ChatStage (agent chat)", () => {
useAgentChatStore.setState({ activeSessionId: "s5", timeline });
render(<ChatStage />);
- const [shell, grep] = screen.getAllByTestId("agent-tool");
+ const [shell, grep] = Array.from(document.querySelectorAll<HTMLElement>("[data-trace-tool]"));
fireEvent.click(within(shell).getByRole("button"));
- // One field, and the row's summary already carries it — no INPUT block.
- expect(within(shell).queryByText("Input")).toBeNull();
+ // The full receipt is available on demand.
+ expect(within(shell).getByText("Input")).toBeTruthy();
expect(shell.textContent).toContain("a.py");
fireEvent.click(within(grep).getByRole("button"));
@@ -676,7 +655,7 @@ describe("ChatStage (agent chat)", () => {
expect(within(grep).getByText("Input")).toBeTruthy();
});
- it("names tools the way the agent's log does and closes with time and tokens", () => {
+ it("uses readable tool names, preserves canonical detail, and closes with usage", () => {
const timeline = reduceEvents(EMPTY_TIMELINE, [
ev("user_message", { text: "check the repo" }),
ev("turn_started", { turn_id: "t9", provider: "claude-api", model: "claude-opus-5", effort: "high", runner: "claude-cli" }),
@@ -691,20 +670,19 @@ describe("ChatStage (agent chat)", () => {
useAgentChatStore.setState({ activeSessionId: "s9", timeline });
render(<ChatStage />);
- const tools = screen.getAllByTestId("agent-tool");
- expect(tools[0].getAttribute("data-tool")).toBe("PowerShell");
+ const tools = Array.from(document.querySelectorAll<HTMLElement>("[data-trace-tool]"));
+ expect(tools[0].textContent).toContain("Run command");
+ fireEvent.click(within(tools[0]).getByRole("button"));
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.
- expect(tools[1].getAttribute("data-family")).toBe("mcp");
expect(tools[1].textContent).toContain("GitHub");
// Thinking with no readable text still shows its time and does not open.
- const reasoning = screen.getByTestId("agent-reasoning");
- expect(reasoning.textContent).toMatch(/9s|8\.6s|8s/);
- expect(within(reasoning).getByRole("button").hasAttribute("disabled")).toBe(true);
+ const reasoning = screen.getByRole("button", {name: "Thought for 8.6s"});
+ expect(reasoning.hasAttribute("disabled")).toBe(true);
- const footer = screen.getByTestId("agent-turn-footer");
+ const footer = within(screen.getByTestId("work-trace")).getByRole("status");
expect(footer.textContent).toContain("12s");
expect(footer.textContent).toContain("219");
expect(footer.textContent).toContain("$0.8483");
diff --git a/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx b/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx
index c2150ee875..7052b7c935 100644
--- a/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx
@@ -74,7 +74,7 @@ export function ChatStage() {
[catalog],
);
const onDecide = useCallback(
- (approvalId: string, decision: ApprovalDecision) => void decide(approvalId, decision),
+ (approvalId: string, decision: ApprovalDecision) => decide(approvalId, decision),
[decide],
);
diff --git a/jarvis/ui/web/frontend/src/components/home/TurnSteps.test.tsx b/jarvis/ui/web/frontend/src/components/home/TurnSteps.test.tsx
index 3bbdb3c81f..282d328599 100644
--- a/jarvis/ui/web/frontend/src/components/home/TurnSteps.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/TurnSteps.test.tsx
@@ -1,198 +1,20 @@
-import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
-import { afterEach, describe, expect, it } from "vitest";
-
-import { TurnSteps, formatThoughtDuration, traceWorthShowing } from "@/components/home/TurnSteps";
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, expect, it } from "vitest";
+import { TurnSteps, formatThoughtDuration, traceWorthShowing } from "./TurnSteps";
import type { ThinkingStep } from "@/lib/thinkingSteps";
-
-function step(over: Partial<ThinkingStep> & Pick<ThinkingStep, "id" | "kind">): ThinkingStep {
- return {
- labelKey: over.kind === "tool" ? "thinking.step_tool" : "thinking.step_brain",
- status: "done",
- startedTs: 0,
- durationMs: 1200,
- ...over,
- };
-}
-
-const FINISHED: ThinkingStep[] = [
- step({ id: "a", kind: "brain", detail: "openai · gpt-5" }),
- step({ id: "b", kind: "tool", detail: "gmail_search", durationMs: 820 }),
- step({ id: "c", kind: "tool", detail: "run_shell", status: "error", durationMs: 300 }),
- step({ id: "d", kind: "note", labelKey: "thinking.step_update", detail: "Found 3 mails" }),
-];
-
-describe("TurnSteps", () => {
- afterEach(() => cleanup());
-
- it("renders nothing for a finished turn without steps, but a live header with none", () => {
- const { container, rerender } = render(<TurnSteps steps={[]} />);
- expect(container.querySelector('[data-testid="turn-steps"]')).toBeNull();
- rerender(<TurnSteps steps={[]} live durationMs={3000} />);
- const root = screen.getByTestId("turn-steps");
- expect(root.getAttribute("data-live")).toBe("true");
- expect(screen.getByTestId("turn-steps-toggle").textContent).toContain("Thinking");
- expect(screen.getByTestId("turn-steps-toggle").textContent).toContain("3s");
- });
-
- it("starts folded when finished: header with the duration, tool rows still visible", () => {
- render(<TurnSteps steps={FINISHED} durationMs={10_400} />);
- const toggle = screen.getByTestId("turn-steps-toggle");
- expect(toggle.getAttribute("aria-expanded")).toBe("false");
- expect(toggle.textContent).toContain("10s");
-
- const list = screen.getByTestId("turn-steps-list");
- expect(list.getAttribute("data-folded")).toBe("true");
- const rows = within(list).getAllByTestId("turn-step");
- expect(rows.map((r) => r.getAttribute("data-kind"))).toEqual(["tool", "tool"]);
- // Non-tool rows are behind the fold (labels resolve through the real EN locale).
- expect(screen.queryByText("Reasoning")).toBeNull();
- });
-
- it("unfolds to every row and folds back", () => {
- render(<TurnSteps steps={FINISHED} durationMs={10_400} />);
- fireEvent.click(screen.getByTestId("turn-steps-toggle"));
- expect(screen.getByTestId("turn-steps-toggle").getAttribute("aria-expanded")).toBe("true");
- expect(screen.getAllByTestId("turn-step")).toHaveLength(4);
- expect(screen.getByText("Reasoning")).toBeTruthy();
- expect(screen.getByText("Found 3 mails")).toBeTruthy();
-
- fireEvent.click(screen.getByTestId("turn-steps-toggle"));
- expect(screen.getAllByTestId("turn-step")).toHaveLength(2);
- });
-
- it("renders tool rows with the brand tile or the feature's icon and a readable line", () => {
- render(<TurnSteps steps={FINISHED} durationMs={10_400} />);
- const [gmail, shell] = screen.getAllByTestId("turn-step");
-
- // A service tool: the brand logo and the brand's own label.
- const gmailTile = within(gmail).getByTestId("turn-step-brand");
- expect(gmailTile.getAttribute("data-brand-tier")).toBe("logo");
- expect(gmailTile.querySelector("img")?.getAttribute("src")).toMatch(/svg/);
- expect(gmail.textContent).toContain("Gmail · search");
- expect(gmail.textContent).toContain("0.8s");
- expect(gmail.getAttribute("data-family")).toBe("service");
-
- // A Jarvis tool: the family's icon (never a monogram) and the verb line.
- const shellTile = within(shell).getByTestId("turn-step-brand");
- expect(shellTile.getAttribute("data-brand-tier")).toBe("icon");
- expect(shellTile.querySelector("svg")).not.toBeNull();
- expect(shell.getAttribute("data-family")).toBe("shell");
- expect(shell.getAttribute("data-status")).toBe("error");
- // The key may or may not be in the locale yet; both forms contain "failed".
- expect(shell.textContent).toMatch(/failed/i);
- });
-
- it("shows the model's own sentence as a muted thought row above the tool", () => {
- const steps: ThinkingStep[] = [
- step({
- id: "th",
- kind: "thought",
- labelKey: "thinking.step_thought",
- detail: "I'll check the wiki for that.",
- durationMs: 0,
- }),
- step({ id: "w", kind: "tool", detail: "wiki-recall", args: { query: "Urlaub" }, durationMs: 400 }),
- ];
- render(<TurnSteps steps={steps} durationMs={2_000} defaultOpen />);
- const rows = screen.getAllByTestId("turn-step");
- expect(rows[0].getAttribute("data-kind")).toBe("thought");
- expect(rows[0].textContent).toContain("I'll check the wiki for that.");
- // The wiki row: family icon + the call's detail.
- expect(rows[1].getAttribute("data-family")).toBe("wiki");
- expect(rows[1].textContent).toContain("Urlaub");
- // Folded, only tool rows stay — the thought goes with the header.
- fireEvent.click(screen.getByTestId("turn-steps-toggle"));
- expect(screen.getAllByTestId("turn-step")).toHaveLength(1);
- });
-
- it("unfolds a finished tool row into its arguments, result and error", () => {
- const steps: ThinkingStep[] = [
- step({
- id: "s",
- kind: "tool",
- detail: "search_web",
- args: { query: "weather Berlin", limit: 3 },
- result: "3 results",
- durationMs: 900,
- }),
- step({
- id: "f",
- kind: "tool",
- detail: "open_app",
- status: "error",
- args: { app: "Spotify" },
- error: "not installed",
- durationMs: 50,
- }),
- ];
- render(<TurnSteps steps={steps} durationMs={3_000} />);
- const [search, app] = screen.getAllByTestId("turn-step");
- expect(screen.queryByTestId("turn-step-details")).toBeNull();
-
- fireEvent.click(within(search).getByTestId("turn-step-toggle"));
- const details = within(search).getByTestId("turn-step-details");
- expect(details.textContent).toContain("query");
- expect(details.textContent).toContain("weather Berlin");
- expect(details.textContent).toContain("3");
- expect(details.textContent).toContain("3 results");
-
- fireEvent.click(within(app).getByTestId("turn-step-toggle"));
- expect(within(app).getByTestId("turn-step-details").textContent).toContain("not installed");
- });
-
- it("names the model in the unfolded header of a finished turn", () => {
- render(<TurnSteps steps={FINISHED} durationMs={4_000} model="openai · gpt-5" />);
- expect(screen.queryByTestId("turn-steps-model")).toBeNull();
- fireEvent.click(screen.getByTestId("turn-steps-toggle"));
- expect(screen.getByTestId("turn-steps-model").textContent).toContain("openai · gpt-5");
- });
-
- it("is open in live mode and spins on the active row", () => {
- const live: ThinkingStep[] = [
- step({ id: "a", kind: "brain", durationMs: 900 }),
- step({ id: "b", kind: "tool", detail: "github_issues", status: "active", durationMs: undefined }),
- ];
- render(<TurnSteps steps={live} live durationMs={2_500} />);
- expect(screen.getByTestId("turn-steps-toggle").getAttribute("aria-expanded")).toBe("true");
- const rows = screen.getAllByTestId("turn-step");
- expect(rows).toHaveLength(2);
- expect(within(rows[1]).getByTestId("turn-step-spinner")).toBeTruthy();
- expect(within(rows[0]).queryByTestId("turn-step-spinner")).toBeNull();
- });
-
- it("honours defaultOpen over the mode default", () => {
- render(<TurnSteps steps={FINISHED} durationMs={1000} defaultOpen />);
- expect(screen.getAllByTestId("turn-step")).toHaveLength(4);
- });
+afterEach(cleanup);
+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();
});
-
-describe("formatThoughtDuration", () => {
- it("rounds to whole seconds and never shows 0s for a real turn", () => {
- expect(formatThoughtDuration(0)).toBe("0s");
- expect(formatThoughtDuration(400)).toBe("1s");
- expect(formatThoughtDuration(10_400)).toBe("10s");
- expect(formatThoughtDuration(65_000)).toBe("1m 05s");
- });
+it("does not hide live work with no events", () => {
+ const { rerender, container } = render(<TurnSteps steps={[]} />);
+ expect(container.textContent).toBe("");
+ rerender(<TurnSteps steps={[]} live />);
+ expect(screen.getByRole("status").textContent).toContain("Working");
});
-
-describe("traceWorthShowing", () => {
- const brain: ThinkingStep = {
- id: "b1", kind: "brain", labelKey: "thinking.step_brain", status: "done", startedTs: 0, durationMs: 200,
- };
- const tool: ThinkingStep = {
- id: "t1", kind: "tool", labelKey: "thinking.step_tool", detail: "gmail_search", status: "done", startedTs: 0, durationMs: 400,
- };
-
- it("hides a finished sub-second brain-only turn — no 'Thought for 0s'", () => {
- expect(traceWorthShowing([brain], 200, false)).toBe(false);
- expect(traceWorthShowing([], 0, false)).toBe(false);
- const { container } = render(<TurnSteps steps={[brain]} durationMs={200} />);
- expect(container.firstChild).toBeNull();
- });
-
- it("keeps turns with a tool, a real thinking time, or that are still live", () => {
- expect(traceWorthShowing([brain, tool], 200, false)).toBe(true);
- expect(traceWorthShowing([brain], 3200, false)).toBe(true);
- expect(traceWorthShowing([], 0, true)).toBe(true);
- });
+it("preserves the public duration formatter", () => {
+ expect(formatThoughtDuration(65000)).toBe("1m 05s");
});
diff --git a/jarvis/ui/web/frontend/src/components/home/TurnSteps.tsx b/jarvis/ui/web/frontend/src/components/home/TurnSteps.tsx
index 2d0c6d37b6..1407dc3b8e 100644
--- a/jarvis/ui/web/frontend/src/components/home/TurnSteps.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/TurnSteps.tsx
@@ -1,68 +1,5 @@
-/**
- * The reasoning steps of one turn, the way the Claude desktop app shows
- * them: a muted "Thought for 10s" line that folds and unfolds the list, rows
- * hung on a thin vertical connector, and every step as a line a person can
- * read — "Looking in Wiki · Urlaub", "Creating artifact · Sales deck",
- * "Running skill · daily-brief" — with the feature's own mark in front of
- * it, or the service's brand logo for Gmail, Spotify, an MCP server…
- *
- * Row kinds:
- * thought — the sentence the model wrote next to a tool call (its own
- * words for why it reaches for the tool); muted, italic.
- * tool — the call: verb + detail, a spinner while it runs, the time
- * it took, red with "failed" when it did. Click a finished row
- * to unfold what went in (arguments) and what came back.
- * brain / computer / worker / note — the rest of the turn.
- *
- * Two modes share one renderer:
- * live — the turn is still running; the list is open, the active row
- * spins, the header counts the seconds.
- * finished — folded to the header by default, BUT the tool rows stay
- * visible under it: what the assistant reached for is the part
- * worth seeing without a click. Unfolding shows every row and,
- * when the turn said, which model answered.
- *
- * Presentational only: steps come in as props (the store keeps the live
- * list and the per-message snapshots), time comes in as `durationMs` — the
- * caller ticks. That keeps this usable from the chat column, the voice lane
- * and the history alike, and testable without a store.
- */
-import { useId, useState } from "react";
-import {
- AppWindow,
- BookMarked,
- BookOpen,
- Bookmark,
- Bot,
- Brain,
- ChevronRight,
- CircleAlert,
- Clock,
- Compass,
- Contact,
- Cpu,
- FilePlus2,
- Globe,
- Info,
- MonitorDot,
- MousePointerClick,
- Phone,
- Plug,
- Puzzle,
- ScanEye,
- Settings2,
- ShieldCheck,
- Sparkles,
- Terminal,
- UserRound,
- Wand2,
- type LucideIcon,
-} from "lucide-react";
-
-import type { ThinkingStep, ThinkingStepKind } from "@/lib/thinkingSteps";
-import { describeToolStep, type ToolFamily } from "@/lib/toolStepLabel";
-import { fill, useT } from "@/i18n";
-import { cn } from "@/lib/utils";
+import type { ThinkingStep } from "@/lib/thinkingSteps";
+import { VoiceWorkTrace } from "@/components/agentchat/VoiceWorkTrace";
export interface TurnStepsProps {
steps: ThinkingStep[];
@@ -79,7 +16,6 @@ export interface TurnStepsProps {
className?: string;
}
-/** Whole seconds like the Claude app: "10s", "1m 05s"; never "0s" for a real turn. */
export function formatThoughtDuration(ms: number): string {
const total = Math.max(0, Math.round(ms / 1000));
if (total < 60) return `${Math.max(total, ms > 0 ? 1 : 0)}s`;
@@ -88,376 +24,7 @@ export function formatThoughtDuration(ms: number): string {
return `${m}m ${String(s).padStart(2, "0")}s`;
}
-/** Per-row durations keep tenths under ten seconds — a 0.4s tool call is not "0s". */
-function formatStepDuration(ms: number): string {
- if (ms < 10_000) return `${(ms / 1000).toFixed(1)}s`;
- return formatThoughtDuration(ms);
-}
-
-const KIND_ICON: Record<Exclude<ThinkingStepKind, "tool" | "thought">, LucideIcon> = {
- brain: Brain,
- computer: MonitorDot,
- worker: Bot,
- note: Info,
-};
-
-/** The feature's own mark for a tool row that has no brand logo. */
-const FAMILY_ICON: Record<ToolFamily, LucideIcon> = {
- wiki: BookOpen,
- wiki_write: BookMarked,
- artifact: FilePlus2,
- skill: Wand2,
- skill_create: Sparkles,
- web: Globe,
- screen: ScanEye,
- screen_recall: ScanEye,
- control: MousePointerClick,
- navigate: Compass,
- app: AppWindow,
- memory: Bookmark,
- profile: UserRound,
- contact: Contact,
- call: Phone,
- worker: Bot,
- shell: Terminal,
- model: Cpu,
- mcp_admin: Plug,
- settings: Settings2,
- verify: ShieldCheck,
- mcp: Plug,
- service: Puzzle,
- other: Puzzle,
-};
-
-/**
- * The small spinner shown on an active row. A plain ring instead of an
- * animated SVG so it stays crisp at 14px; under reduced motion it stands
- * still as a ring, which still reads as "open".
- */
-function Spinner({ className }: { className?: string }) {
- return (
- <span
- aria-hidden
- data-testid="turn-step-spinner"
- className={cn(
- "inline-block rounded-full border-2 border-primary/25 border-t-primary motion-safe:animate-spin",
- className,
- )}
- />
- );
-}
-
-/** The gutter box every mark sits in: opaque, so it masks the connector line. */
-function markBox(compact: boolean): string {
- return cn(
- "relative z-10 grid shrink-0 place-items-center bg-background",
- compact ? "h-[18px] w-[18px]" : "h-5 w-5",
- );
-}
-
-/** The tile at the left of a tool row: the brand SVG, or the family's icon. */
-function ToolMark({
- logoUrl,
- Icon,
- label,
- active,
- error,
- compact,
-}: {
- logoUrl?: string;
- Icon: LucideIcon;
- label: string;
- active: boolean;
- error: boolean;
- compact: boolean;
-}) {
- const [failed, setFailed] = useState(false);
- const showLogo = Boolean(logoUrl) && !failed;
- const size = compact ? "h-3 w-3" : "h-3.5 w-3.5";
- if (showLogo) {
- return (
- <span
- data-testid="turn-step-brand"
- data-brand-tier="logo"
- title={label}
- className={cn(markBox(compact), "overflow-hidden rounded-md")}
- >
- <span aria-hidden className="absolute inset-0 rounded-md border border-sheen/10 bg-sheen/[0.07]" />
- <img
- src={logoUrl}
- alt=""
- className={cn("relative", size)}
- loading="lazy"
- onError={() => setFailed(true)}
- />
- </span>
- );
- }
- return (
- <span data-testid="turn-step-brand" data-brand-tier="icon" title={label} className={markBox(compact)}>
- {active ? (
- <Spinner className={size} />
- ) : (
- <Icon
- aria-hidden
- className={cn(size, error ? "text-destructive" : "text-muted-foreground/80")}
- />
- )}
- </span>
- );
-}
-
-/** The gutter mark of a non-tool row: spinner while active, the kind's icon otherwise. */
-function KindMark({ step, compact }: { step: ThinkingStep; compact: boolean }) {
- const size = compact ? "h-3 w-3" : "h-3.5 w-3.5";
- const box = markBox(compact);
- if (step.status === "active") {
- return (
- <span className={box}>
- <Spinner className={size} />
- </span>
- );
- }
- if (step.status === "error") {
- return (
- <span className={box}>
- <CircleAlert aria-hidden className={cn(size, "text-destructive")} />
- </span>
- );
- }
- const Icon = KIND_ICON[step.kind as Exclude<ThinkingStepKind, "tool" | "thought">] ?? Info;
- return (
- <span className={box}>
- <Icon aria-hidden className={cn(size, "text-muted-foreground/70")} />
- </span>
- );
-}
-
-/** A muted, italic line in the model's own words — no mark, a quiet dot in the gutter. */
-function ThoughtRow({ step, compact }: { step: ThinkingStep; compact: boolean }) {
- return (
- <li
- data-testid="turn-step"
- data-kind="thought"
- data-status={step.status}
- className={cn("relative flex min-w-0 items-start", compact ? "gap-2 py-[3px]" : "gap-2.5 py-1")}
- >
- <span className={markBox(compact)}>
- <span aria-hidden className="h-1 w-1 rounded-full bg-muted-foreground/50" />
- </span>
- <span
- className={cn(
- "min-w-0 flex-1 italic leading-5 text-muted-foreground/85",
- compact ? "text-xs" : "text-sm",
- )}
- >
- {step.detail}
- </span>
- </li>
- );
-}
-
-/** Arguments / result / error of a finished tool call, shown when a row is unfolded. */
-function ToolDetails({ step, compact }: { step: ThinkingStep; compact: boolean }) {
- const t = useT();
- const args = step.args ? Object.entries(step.args) : [];
- return (
- <div
- data-testid="turn-step-details"
- className={cn(
- "mb-1 ml-[30px] mr-1 flex flex-col gap-1 rounded-md border border-border/70 bg-secondary/40 px-2.5 py-2",
- compact ? "text-xs" : "text-xs",
- )}
- >
- {args.length > 0 && (
- <dl className="grid grid-cols-[max-content_1fr] gap-x-3 gap-y-0.5">
- {args.map(([k, v]) => (
- <div key={k} className="contents">
- <dt className="font-mono text-muted-foreground/70">{k}</dt>
- <dd className="min-w-0 break-words text-foreground/85">{formatArg(v)}</dd>
- </div>
- ))}
- </dl>
- )}
- {step.result && (
- <div className="flex min-w-0 gap-2">
- <span className="shrink-0 text-muted-foreground/70">{t("turn_steps.result")}</span>
- <span className="min-w-0 break-words text-foreground/85">{step.result}</span>
- </div>
- )}
- {step.error && (
- <div className="flex min-w-0 gap-2">
- <span className="shrink-0 text-destructive/80">{t("turn_steps.error")}</span>
- <span className="min-w-0 break-words text-destructive">{step.error}</span>
- </div>
- )}
- {args.length === 0 && !step.result && !step.error && (
- <span className="text-muted-foreground/70">{t("turn_steps.no_details")}</span>
- )}
- </div>
- );
-}
-function formatArg(v: unknown): string {
- if (typeof v === "string") return v;
- if (v === null || v === undefined) return "—";
- if (typeof v === "number" || typeof v === "boolean") return String(v);
- try {
- return JSON.stringify(v);
- } catch {
- return String(v);
- }
-}
-
-function ToolRow({ step, compact }: { step: ThinkingStep; compact: boolean }) {
- const t = useT();
- const [open, setOpen] = useState(false);
- const active = step.status === "active";
- const error = step.status === "error";
- const view = describeToolStep(step.detail ?? "", step.args);
- const line = view.labelKey ? t(view.labelKey) : view.label;
- const hasDetails = !active && (Boolean(step.args) || Boolean(step.result) || Boolean(step.error));
- const Icon = FAMILY_ICON[view.family];
- const detailsId = useId();
-
- const body = (
- <>
- <ToolMark
- logoUrl={view.brand?.logoUrl}
- Icon={Icon}
- label={line}
- active={active}
- error={error}
- compact={compact}
- />
- <span
- className={cn(
- "min-w-0 flex-1 truncate leading-5",
- compact ? "text-xs" : "text-sm",
- error ? "text-destructive" : "text-foreground/85",
- active && "thinking-shimmer font-medium",
- )}
- >
- {line}
- {view.detail && (
- <span className={cn("ml-1.5 font-normal text-muted-foreground/80")}>· {view.detail}</span>
- )}
- </span>
- {active && <Spinner className={compact ? "h-3 w-3" : "h-3.5 w-3.5"} />}
- {error && (
- <span className="shrink-0 text-micro uppercase tracking-[0.08em] text-destructive/80">
- {t("turn_steps.failed")}
- </span>
- )}
- {!active && step.durationMs !== undefined && step.durationMs > 0 && (
- <span className="shrink-0 font-mono text-micro tabular-nums text-muted-foreground/60">
- {formatStepDuration(step.durationMs)}
- </span>
- )}
- {hasDetails && (
- <ChevronRight
- aria-hidden
- className={cn(
- "h-3 w-3 shrink-0 opacity-0 transition-transform duration-200 group-hover/row:opacity-60 motion-reduce:transition-none",
- open && "rotate-90 opacity-60",
- )}
- />
- )}
- </>
- );
-
- return (
- <li
- data-testid="turn-step"
- data-kind="tool"
- data-family={view.family}
- data-status={step.status}
- className="relative flex min-w-0 flex-col"
- >
- {hasDetails ? (
- <button
- type="button"
- onClick={() => setOpen((v) => !v)}
- aria-expanded={open}
- aria-controls={detailsId}
- data-testid="turn-step-toggle"
- className={cn(
- "group/row -mx-1 flex min-w-0 items-center rounded-md px-1 text-left hover:bg-secondary/50",
- compact ? "gap-2 py-[3px]" : "gap-2.5 py-1",
- )}
- >
- {body}
- </button>
- ) : (
- <div className={cn("flex min-w-0 items-center", compact ? "gap-2 py-[3px]" : "gap-2.5 py-1")}>
- {body}
- </div>
- )}
- {hasDetails && open && (
- <div id={detailsId}>
- <ToolDetails step={step} compact={compact} />
- </div>
- )}
- </li>
- );
-}
-
-function StepRow({ step, compact }: { step: ThinkingStep; compact: boolean }) {
- const t = useT();
- if (step.kind === "tool") return <ToolRow step={step} compact={compact} />;
- if (step.kind === "thought") return <ThoughtRow step={step} compact={compact} />;
- const active = step.status === "active";
- const error = step.status === "error";
-
- return (
- <li
- data-testid="turn-step"
- data-kind={step.kind}
- data-status={step.status}
- className={cn(
- "relative flex min-w-0 items-center",
- compact ? "gap-2 py-[3px]" : "gap-2.5 py-1",
- )}
- >
- <KindMark step={step} compact={compact} />
- <span
- className={cn(
- "min-w-0 flex-1 truncate leading-5",
- compact ? "text-xs" : "text-sm",
- error ? "text-destructive" : "text-muted-foreground",
- active && "thinking-shimmer font-medium",
- )}
- >
- {t(step.labelKey)}
- {step.detail && (
- <span className="ml-1.5 font-normal text-muted-foreground/80">{step.detail}</span>
- )}
- {error && step.error && (
- <span className="ml-1.5 font-normal text-destructive/80">{step.error}</span>
- )}
- </span>
- {error && (
- <span className="shrink-0 text-micro uppercase tracking-[0.08em] text-destructive/80">
- {t("turn_steps.failed")}
- </span>
- )}
- {!active && step.durationMs !== undefined && step.durationMs > 0 && (
- <span className="shrink-0 font-mono text-micro tabular-nums text-muted-foreground/60">
- {formatStepDuration(step.durationMs)}
- </span>
- )}
- </li>
- );
-}
-
-/**
- * Is a finished trace worth a line on screen?
- *
- * A turn that only saw the brain call come and go within a second — no tool,
- * no worker, no computer use — has nothing to show, and "Thought for 0s"
- * above an answer is noise, not information (maintainer, 2026-08-23). Live
- * traces are always shown: the person should see the assistant is working.
- */
export function traceWorthShowing(
steps: ThinkingStep[],
durationMs: number | undefined,
@@ -465,115 +32,11 @@ export function traceWorthShowing(
): boolean {
if (live) return true;
if (steps.length === 0) return false;
- const substantial = steps.some((s) => s.kind !== "brain" && s.kind !== "note");
+ const substantial = steps.some((s) => s.status === "error" || (s.kind !== "brain" && s.kind !== "note"));
return substantial || (durationMs ?? 0) >= 1000;
}
-export function TurnSteps({
- steps,
- live = false,
- durationMs,
- model,
- compact = false,
- defaultOpen,
- className,
-}: TurnStepsProps) {
- const t = useT();
- const listId = useId();
- const [open, setOpen] = useState<boolean>(defaultOpen ?? live);
-
- // A finished turn with nothing observed has nothing to say; a live one
- // still shows its header so the person sees the assistant is working.
+export function TurnSteps({ steps, live = false, durationMs, className }: TurnStepsProps) {
if (!traceWorthShowing(steps, durationMs, live)) return null;
-
- const toolRows = steps.filter((s) => s.kind === "tool");
- const visible = open ? steps : toolRows;
- const headerText = live
- ? t("thinking.label")
- : thoughtFor(t("turn_steps.thought_for"), formatThoughtDuration(durationMs ?? 0));
- const elapsed = live && durationMs !== undefined ? formatThoughtDuration(durationMs) : null;
- const modelLine = !live && open && model ? model : null;
-
- return (
- <div
- data-testid="turn-steps"
- data-live={live ? "true" : "false"}
- data-open={open ? "true" : "false"}
- className={cn("flex min-w-0 flex-col", className)}
- role={live ? "status" : undefined}
- aria-live={live ? "polite" : undefined}
- >
- <button
- type="button"
- onClick={() => setOpen((v) => !v)}
- aria-expanded={open}
- aria-controls={listId}
- data-testid="turn-steps-toggle"
- className={cn(
- "group -ml-1 flex w-fit max-w-full items-center gap-1.5 rounded-md px-1 text-left text-muted-foreground transition-colors hover:text-foreground",
- compact ? "py-0.5 text-xs" : "py-1 text-sm",
- )}
- >
- {live ? (
- <Spinner className={compact ? "h-3 w-3" : "h-3.5 w-3.5"} />
- ) : (
- <Clock aria-hidden className={cn("shrink-0", compact ? "h-3 w-3" : "h-3.5 w-3.5")} />
- )}
- <span className={cn("truncate", live && "thinking-shimmer font-medium")}>{headerText}</span>
- {elapsed && (
- <span className="shrink-0 font-mono text-xs tabular-nums text-muted-foreground/70">
- {elapsed}
- </span>
- )}
- {modelLine && (
- <span
- data-testid="turn-steps-model"
- className="truncate font-mono text-micro text-muted-foreground/60"
- >
- · {modelLine}
- </span>
- )}
- <ChevronRight
- aria-hidden
- className={cn(
- "h-3 w-3 shrink-0 opacity-60 transition-transform duration-200 motion-reduce:transition-none group-hover:opacity-100",
- open && "rotate-90",
- )}
- />
- </button>
-
- {visible.length > 0 && (
- <ol
- id={listId}
- data-testid="turn-steps-list"
- data-folded={open ? "false" : "true"}
- className={cn("relative", compact ? "ml-0.5 mt-0.5" : "ml-0.5 mt-1")}
- >
- {/* The connector: one thin line behind the gutter marks, which mask
- it with their own background so it reads as joining them. */}
- <span
- aria-hidden
- className={cn(
- "absolute bottom-2 top-2 w-px bg-border",
- compact ? "left-[8.5px]" : "left-[9.5px]",
- )}
- />
- {visible.map((s) => (
- <StepRow key={s.id} step={s} compact={compact} />
- ))}
- </ol>
- )}
- </div>
- );
-}
-
-/**
- * "Thought for {duration}" — the locale decides the word order. Should a
- * locale (or an un-hydrated test) hand back a template without the token,
- * the duration is still appended so the number is never lost.
- */
-function thoughtFor(template: string, duration: string): string {
- return template.includes("{duration}")
- ? fill(template, { duration })
- : `${template} ${duration}`;
+ return <VoiceWorkTrace steps={steps} live={live} durationMs={durationMs} className={className} />;
}
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
index aae92cd373..9cbf65bd23 100644
--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
@@ -8,8 +8,7 @@ import { InternalMessageBubble } from "@/components/agentchat/InternalMessageBub
* voice stage use (`useAgentChatStore`, the "jarvis" surface): one history,
* whatever a person said or typed anywhere. "@Name" hands the task to that
* agent; "@gmail" (and the other catalog tags) pins that plugin, MCP server
- * or tool for the turn. The reasoning trail stays readable: a centred
- * "Thought for 4s" pill above the answer, never a second wall of text.
+ * or tool for the turn. The shared work trace preserves the order of thoughts, tools and replies.
*
* Jarvis' card alone also has a `Voice | Chat` switch (maintainer,
* 2026-09-02): Jarvis is the one agent a person talks to by voice, so the
@@ -21,7 +20,7 @@ import { InternalMessageBubble } from "@/components/agentchat/InternalMessageBub
* runner can drive. The header says so while voice is showing.
*/
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
-import { Brain, ChevronRight, MessageSquare, Mic, Paperclip, Plus, RotateCcw, Send, Square } from "lucide-react";
+import { MessageSquare, Mic, Paperclip, Plus, RotateCcw, Send, Square } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
@@ -37,15 +36,12 @@ import { DictationStatus } from "@/components/agentchat/DictationStatus";
import { useComposerDictation } from "@/components/agentchat/useComposerDictation";
import type {
NoticeItem,
- ReasoningBlock,
TimelineItem,
- ToolBlock,
TurnItem,
UserItem,
} from "@/components/agentchat/reduce";
-import { formatThoughtDuration } from "@/components/home/TurnSteps";
+import { TurnTrace } from "@/components/agentchat/WorkTrace";
import { VoiceStage } from "@/components/home/VoiceStage";
-import { LiveCore } from "@/components/LiveCore";
import { ProviderLogo } from "@/components/providers/ProviderLogo";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
@@ -850,36 +846,7 @@ function TurnBubble({
item: TurnItem;
onDecide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;
}) {
- const t = useT();
- const running = item.status === "running";
- return (
- <div className="flex w-full flex-col gap-1.5">
- {item.blocks.map((block) => {
- if (block.kind === "reasoning") return <ReasoningTrace key={block.id} block={block} turnLive={running} />;
- if (block.kind === "tool") return <ToolLine key={block.callId} block={block} onDecide={onDecide} />;
- if (!block.text.trim()) return null;
- return (
- <div
- key={block.id}
- className="max-w-[88%] self-start rounded-2xl rounded-bl-md bg-popover px-3.5 py-2 text-foreground"
- >
- <Prose text={block.text} />
- </div>
- );
- })}
- {running && item.blocks.every((b) => b.kind !== "text") ? (
- <div
- className="flex items-center gap-1 self-start rounded-2xl rounded-bl-md bg-popover px-3.5 py-2.5"
- aria-label={t("society.chat.thinking")}
- >
- <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground" />
- <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground [animation-delay:150ms]" />
- <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground [animation-delay:300ms]" />
- </div>
- ) : null}
- {item.error ? <p className="self-start text-xs text-destructive">{item.error}</p> : null}
- </div>
- );
+ return <TurnTrace turn={item} onDecide={onDecide} renderText={(text) => <Prose text={text} />} />;
}
/**
@@ -912,184 +879,6 @@ function Prose({ text, muted }: { text: string; muted?: boolean }) {
);
}
-/** Live elapsed readout for a running thought; 1 s is fine — the label shows whole seconds. */
-function useElapsedMs(startedMs: number | null): number {
- const [now, setNow] = useState(() => Date.now());
- useEffect(() => {
- if (startedMs === null) return;
- setNow(Date.now());
- const id = window.setInterval(() => setNow(Date.now()), 1000);
- return () => window.clearInterval(id);
- }, [startedMs]);
- return startedMs === null ? 0 : Math.max(0, now - startedMs);
-}
-
-/**
- * The reasoning trace — the model's thinking, centred above the answer.
- *
- * Modelled on the Claude and ChatGPT desktop apps (maintainer, 2026-09-02:
- * the old `<details>` row was a bare summary with a wall of pre-wrapped text
- * under it). Three states, one shape:
- *
- * WHILE IT THINKS a centred live line — the product's one live core, a
- * shimmering "Thinking for 8s" and a ticking clock — sits over an open card
- * whose text is anchored to its NEWEST lines, so the reader watches the
- * thought arrive instead of chasing a scrollbar. Older lines fade out at the
- * top rather than being cut.
- *
- * ONCE IT CLOSES the line becomes a centred pill: a brain mark, "Thought for
- * 8s", a chevron. It stays open while the turn still works — watching the
- * work is the point of a running turn — and folds itself the moment the turn
- * lands, because a finished conversation should read as its answer.
- *
- * A REDACTED thought (the vendor hides its reasoning) is the same pill
- * without a chevron and without a card: it still says the thinking happened.
- *
- * The trace is centred on purpose: it is not the agent speaking, it is the
- * turn's own state, and the column already places its meta rows — the time
- * stamps — down the middle.
- */
-export function ReasoningTrace({ block, turnLive }: { block: ReasoningBlock; turnLive: boolean }) {
- const t = useT();
- // `null` until the person decides; until then the turn's own state decides.
- const [manual, setManual] = useState<boolean | null>(null);
- const text = block.text.trim();
- const live = block.live;
- const elapsed = useElapsedMs(live ? block.startedMs : null);
- const open = live || (text !== "" && (manual ?? turnLive));
-
- const label = live
- ? t("society.chat.thinking_for").replace("{0}", formatThoughtDuration(elapsed))
- : block.durationMs !== null && block.durationMs > 0
- ? t("society.chat.thought_for").replace("{0}", formatThoughtDuration(block.durationMs))
- : t("society.chat.thought");
-
- return (
- <div
- className="my-0.5 flex flex-col items-center gap-1.5"
- data-testid="society-reasoning"
- data-state={live ? "live" : text === "" ? "silent" : open ? "open" : "folded"}
- >
- {live ? (
- <div className="flex items-center gap-2 text-xs" role="status" aria-live="polite">
- <LiveCore />
- <span className="thinking-shimmer font-medium tabular-nums">{label}</span>
- </div>
- ) : (
- <button
- type="button"
- onClick={() => setManual(!open)}
- aria-expanded={open}
- disabled={text === ""}
- title={text === "" ? t("society.chat.thought_hidden") : undefined}
- className={cn(
- "inline-flex items-center gap-1.5 rounded-full border border-border/60 bg-secondary/40 px-2.5 py-1",
- "text-xs text-muted-foreground transition-colors",
- text === "" ? "cursor-default" : "hover:border-border hover:bg-secondary hover:text-foreground",
- )}
- >
- <Brain className="h-3.5 w-3.5 shrink-0 opacity-70" aria-hidden />
- <span className="tabular-nums">{label}</span>
- {text === "" ? null : (
- <ChevronRight className={cn("h-3.5 w-3.5 shrink-0 transition-transform", open && "rotate-90")} aria-hidden />
- )}
- </button>
- )}
-
- {open ? (
- <div className="w-full rounded-2xl border border-border/60 bg-secondary/25 px-4 py-3">
- {live ? <ThoughtTail text={text} /> : <Prose text={text} muted />}
- </div>
- ) : null}
- </div>
- );
-}
-
-/**
- * The streaming thought, pinned to its newest lines.
- *
- * A fixed window with the text against its bottom edge: new words push the
- * old ones up and out. Once more has been written than fits, the top fades
- * so the clipping reads as depth rather than as a cut; a thought that fits
- * shows whole and unfaded.
- */
-function ThoughtTail({ text }: { text: string }) {
- const outer = useRef<HTMLDivElement>(null);
- const inner = useRef<HTMLDivElement>(null);
- const [clipped, setClipped] = useState(false);
- useLayoutEffect(() => {
- const box = outer.current;
- const body = inner.current;
- if (!box || !body) return;
- setClipped(body.offsetHeight > box.clientHeight + 1);
- }, [text]);
- return (
- <div
- ref={outer}
- className={cn(
- "flex max-h-40 flex-col justify-end overflow-hidden",
- clipped && "[mask-image:linear-gradient(to_bottom,transparent,black_2.5rem)]",
- )}
- data-testid="society-reasoning-tail"
- data-clipped={clipped ? "true" : undefined}
- >
- <div ref={inner}>
- {text ? <Prose text={text} muted /> : null}
- </div>
- </div>
- );
-}
-
-function ToolLine({
- block,
- onDecide,
-}: {
- block: ToolBlock;
- onDecide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;
-}) {
- const t = useT();
- const pending = block.approval && block.approval.decision === null;
- const state = block.isError
- ? t("society.chat.tool_failed")
- : block.output === null && !pending
- ? t("society.chat.tool_running")
- : pending
- ? t("society.chat.tool_waiting")
- : t("society.chat.tool_done");
- return (
- <div className="flex flex-wrap items-center gap-2 px-1 text-xs text-muted-foreground">
- <span className="font-mono">{block.name}</span>
- <span>· {state}</span>
- {pending && block.approval ? (
- <span className="flex items-center gap-1">
- <button
- type="button"
- onClick={() => void onDecide(block.approval!.approvalId, "allow")}
- className="rounded-full border border-border px-2 py-0.5 text-foreground hover:bg-secondary"
- >
- {t("society.chat.approve")}
- </button>
- <button
- type="button"
- onClick={() => void onDecide(block.approval!.approvalId, "allow_always")}
- title={t("society.chat.allow_always")}
- className="rounded-full border border-border px-2 py-0.5 text-foreground hover:bg-secondary"
- >
- {t("society.chat.allow_always")}
- </button>
- <button
- type="button"
- onClick={() => void onDecide(block.approval!.approvalId, "deny")}
- className="rounded-full border border-border px-2 py-0.5 hover:bg-secondary"
- >
- {t("society.chat.deny")}
- </button>
- </span>
- ) : null}
- </div>
- );
-}
-
// ---------------------------------------------------------------------------
// composer
// ---------------------------------------------------------------------------
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ReasoningTrace.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ReasoningTrace.test.tsx
index 8b513988b1..f807878ba3 100644
--- a/jarvis/ui/web/frontend/src/components/society/chat/ReasoningTrace.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/chat/ReasoningTrace.test.tsx
@@ -1,86 +1,19 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
-import { afterEach, describe, expect, it } from "vitest";
-
-import { ReasoningTrace } from "@/components/society/chat/AgentChatPanel";
+import { afterEach, expect, it } from "vitest";
+import { ReasoningTrace } from "@/components/agentchat/WorkTrace";
import type { ReasoningBlock } from "@/components/agentchat/reduce";
-
-/**
- * The agent card's reasoning trace — what the maintainer asked for on
- * 2026-09-02: the bare `<details>` summary over a wall of pre-wrapped text
- * was replaced by the Claude/ChatGPT shape — a centred live line, a centred
- * "Thought for 8s" pill, and the thought itself as prose.
- *
- * The rules this file holds: the trace is CENTRED, it renders Markdown as
- * prose rather than as marks, it stays open while the turn still works and
- * folds when the turn lands, and a redacted thought still says it happened
- * without pretending there is something to open.
- */
-
-function block(over: Partial<ReasoningBlock> = {}): ReasoningBlock {
- return {
- kind: "reasoning",
- id: "r1",
- text: "**Plan:** add the minutes first, then the two stops.",
- durationMs: 8_000,
- live: false,
- startedMs: 1_000,
- ...over,
- };
-}
-
+const block: ReasoningBlock = { kind: "reasoning", id: "r", text: "**Inspect** the files.", durationMs: 8000, live: false, startedMs: 0 };
afterEach(cleanup);
-
-describe("society reasoning trace", () => {
- it("centres itself instead of hanging off the bubble's edge", () => {
- render(<ReasoningTrace block={block()} turnLive={false} />);
- expect(screen.getByTestId("society-reasoning").className).toContain("items-center");
- });
-
- it("shows the live core and a running clock while the thought streams", () => {
- // `startedMs` is a wall clock, so a live block has to start about now.
- render(<ReasoningTrace block={block({ live: true, durationMs: null, startedMs: Date.now() })} turnLive />);
- const trace = screen.getByTestId("society-reasoning");
- expect(trace.dataset.state).toBe("live");
- expect(screen.getByTestId("live-core")).toBeTruthy();
- expect(screen.getByRole("status").textContent).toMatch(/Thinking for \d+s/);
- // A live thought is open, and anchored to its newest lines.
- expect(screen.getByTestId("society-reasoning-tail")).toBeTruthy();
- });
-
- it("reads the thought as prose, not as Markdown marks", () => {
- render(<ReasoningTrace block={block()} turnLive />);
- expect(screen.getByText("Plan:").tagName).toBe("STRONG");
- expect(screen.queryByText(/\*\*Plan/)).toBeNull();
- });
-
- it("stays open while the turn still works and folds once it lands", () => {
- const { rerender } = render(<ReasoningTrace block={block()} turnLive />);
- expect(screen.getByTestId("society-reasoning").dataset.state).toBe("open");
- rerender(<ReasoningTrace block={block()} turnLive={false} />);
- expect(screen.getByTestId("society-reasoning").dataset.state).toBe("folded");
- });
-
- it("names the duration on the folded pill and opens on a click", () => {
- render(<ReasoningTrace block={block()} turnLive={false} />);
- const pill = screen.getByRole("button", { name: /Thought for 8s/ });
- expect(pill.getAttribute("aria-expanded")).toBe("false");
- fireEvent.click(pill);
- expect(screen.getByTestId("society-reasoning").dataset.state).toBe("open");
- expect(screen.getByRole("button").getAttribute("aria-expanded")).toBe("true");
- });
-
- it("says a redacted thought happened without offering a fold", () => {
- render(<ReasoningTrace block={block({ text: "" })} turnLive={false} />);
- const trace = screen.getByTestId("society-reasoning");
- expect(trace.dataset.state).toBe("silent");
- const pill = screen.getByRole("button", { name: /Thought for 8s/ });
- expect((pill as HTMLButtonElement).disabled).toBe(true);
- fireEvent.click(pill);
- expect(screen.getByTestId("society-reasoning").dataset.state).toBe("silent");
- });
-
- it("falls back to a bare label when the vendor sent no duration", () => {
- render(<ReasoningTrace block={block({ durationMs: null, text: "" })} turnLive={false} />);
- expect(screen.getByRole("button").textContent).toBe("Thought");
- });
+it("keeps the thought open during work and folds on completion", () => {
+ const { rerender } = render(<ReasoningTrace block={block} turnLive />);
+ expect(screen.getByText("Inspect").tagName).toBe("STRONG");
+ rerender(<ReasoningTrace block={block} turnLive={false} />);
+ const button = screen.getByRole("button", { name: "Thought for 8.0s" });
+ expect(button.getAttribute("aria-expanded")).toBe("false");
+ fireEvent.click(button);
+ expect(screen.getByText("Inspect").tagName).toBe("STRONG");
+});
+it("does not offer an empty disclosure for redacted thought", () => {
+ render(<ReasoningTrace block={{...block, text: ""}} turnLive={false} />);
+ expect((screen.getByRole("button") as HTMLButtonElement).disabled).toBe(true);
});
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 1cc16e48ba..009bcdaad0 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -5493,5 +5493,39 @@
"next_message": "Für die nächste Nachricht ausgewählt",
"hint": "Wähle Tools für die nächste Nachricht. Berechtigungen gelten weiterhin.",
"done": "Fertig"
- }
+ },
+ "work_trace": {
+ "thought": "Nachgedacht",
+ "thinking_for": "Denkt seit {duration}",
+ "thought_for": "Nachgedacht für {duration}",
+ "tool": "Werkzeug",
+ "input": "Eingabe",
+ "output": "Ergebnis",
+ "error": "Fehler",
+ "diff": "Änderungen",
+ "empty_output": "Ohne Ausgabe abgeschlossen",
+ "truncated": "{count} weitere Zeilen in der Eingabe",
+ "read": "Datei lesen",
+ "list": "Dateien auflisten",
+ "search": "Dateien durchsuchen",
+ "group_read": "{count} Dateien gelesen",
+ "group_list": "Dateien an {count} Orten aufgelistet",
+ "group_search": "Dateien {count}-mal durchsucht",
+ "approval": "Freigabe erforderlich",
+ "denied": "Nicht freigegeben",
+ "failed": "Fehlgeschlagen",
+ "running": "Wird ausgeführt",
+ "interrupted": "Ohne Ergebnis unterbrochen",
+ "completed": "Abgeschlossen",
+ "allow": "Freigeben",
+ "allow_always": "Immer erlauben",
+ "deny": "Ablehnen",
+ "approval_elsewhere": "Diese Anfrage im aktiven Chat prüfen.",
+ "working": "In Arbeit",
+ "stopped": "Gestoppt",
+ "done": "Fertig",
+ "command": "Befehl ausführen",
+ "edit": "Datei bearbeiten",
+ "write": "Datei schreiben"
+}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 6d1ccf5097..dd5e5ba0af 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -5526,5 +5526,39 @@
"next_message": "Selected for the next message",
"hint": "Pick tools for your next message. Permissions still apply.",
"done": "Done"
- }
+ },
+ "work_trace": {
+ "thought": "Thought",
+ "thinking_for": "Thinking for {duration}",
+ "thought_for": "Thought for {duration}",
+ "tool": "Tool",
+ "input": "Input",
+ "output": "Output",
+ "error": "Error",
+ "diff": "Changes",
+ "empty_output": "Completed without output",
+ "truncated": "{count} more lines in the input",
+ "read": "Read file",
+ "list": "List files",
+ "search": "Search files",
+ "group_read": "Read {count} files",
+ "group_list": "Listed files in {count} locations",
+ "group_search": "Searched files {count} times",
+ "approval": "Approval required",
+ "denied": "Not approved",
+ "failed": "Failed",
+ "running": "Running",
+ "interrupted": "Interrupted without a result",
+ "completed": "Completed",
+ "allow": "Approve",
+ "allow_always": "Always allow",
+ "deny": "Deny",
+ "approval_elsewhere": "Review this request in the active chat.",
+ "working": "Working",
+ "stopped": "Stopped",
+ "done": "Done",
+ "command": "Run command",
+ "edit": "Edit file",
+ "write": "Write file"
+}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 812bbfdc87..04d06a17b3 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -5493,5 +5493,39 @@
"next_message": "Seleccionadas para el próximo mensaje",
"hint": "Elige herramientas para el próximo mensaje. Se siguen aplicando los permisos.",
"done": "Listo"
- }
+ },
+ "work_trace": {
+ "thought": "Razonamiento",
+ "thinking_for": "Pensando durante {duration}",
+ "thought_for": "Pensó durante {duration}",
+ "tool": "Herramienta",
+ "input": "Entrada",
+ "output": "Resultado",
+ "error": "Error",
+ "diff": "Cambios",
+ "empty_output": "Completado sin salida",
+ "truncated": "{count} líneas más en la entrada",
+ "read": "Leer archivo",
+ "list": "Listar archivos",
+ "search": "Buscar archivos",
+ "group_read": "{count} archivos leídos",
+ "group_list": "Archivos listados en {count} ubicaciones",
+ "group_search": "Archivos buscados {count} veces",
+ "approval": "Aprobación necesaria",
+ "denied": "No aprobado",
+ "failed": "Falló",
+ "running": "En curso",
+ "interrupted": "Interrumpido sin resultado",
+ "completed": "Completado",
+ "allow": "Aprobar",
+ "allow_always": "Permitir siempre",
+ "deny": "Denegar",
+ "approval_elsewhere": "Revisa esta solicitud en el chat activo.",
+ "working": "Trabajando",
+ "stopped": "Detenido",
+ "done": "Listo",
+ "command": "Ejecutar comando",
+ "edit": "Editar archivo",
+ "write": "Escribir archivo"
+}
}