Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(chat): the agent chat shows it is thinking — a live status line, thought rows that survive redaction, tool rows that match the log, and a receipt per turn
rubenluetke10-beep595ca6d27e3f
diff --git a/jarvis/agent_chat/events.py b/jarvis/agent_chat/events.pyindex caa4a93e93..663d0dd064 100644--- a/jarvis/agent_chat/events.py+++ b/jarvis/agent_chat/events.py@@ -12,8 +12,15 @@ Kinds (``payload`` keys in brackets):``turn_started`` [turn_id, provider, model, effort, runner]``text_delta`` [turn_id, message_id, text] — live only, never stored``assistant_text`` [turn_id, message_id, text] — the finished block+``reasoning_started`` [turn_id, message_id] — live only: the model began+ to think (its thinking may be redacted, so this is the+ only sign of it until the finished block arrives)``reasoning_delta`` [turn_id, text] — live only-``reasoning`` [turn_id, text, duration_ms] — the finished block+``reasoning`` [turn_id, text, duration_ms] — the finished block; text+ may be "" when the vendor redacts thinking — the+ duration still says how long it thought+``usage_delta`` [turn_id, usage] — live only: tokens so far+ (cumulative {input_tokens, output_tokens, …})``tool_call`` [turn_id, call_id, name, input]``tool_result`` [turn_id, call_id, output, is_error, duration_ms]``approval_required`` [turn_id, approval_id, call_id, name, input, summary]@@ -23,8 +30,9 @@ Kinds (``payload`` keys in brackets):``session_updated`` [title?, provider?, model?, effort?, cwd?, permission_mode?]``error`` [turn_id?, message]-``text_delta`` / ``reasoning_delta`` are the only transient kinds: the-finished block carries the whole text, so the log never stores token dust.+``text_delta`` / ``reasoning_delta`` / ``reasoning_started`` / ``usage_delta``+are the transient kinds: the finished block carries the whole text and the+``turn_finished`` event the whole usage, so the log never stores token dust."""from __future__ import annotations@@ -32,7 +40,9 @@ from __future__ import annotationsimport timefrom typing import Any, Final-TRANSIENT_KINDS: Final[frozenset[str]] = frozenset({"text_delta", "reasoning_delta"})+TRANSIENT_KINDS: Final[frozenset[str]] = frozenset(+ {"text_delta", "reasoning_delta", "reasoning_started", "usage_delta"}+)def now_ms() -> int:diff --git a/jarvis/agent_chat/runner_api.py b/jarvis/agent_chat/runner_api.pyindex 3c83221e70..e7eec55328 100644--- a/jarvis/agent_chat/runner_api.py+++ b/jarvis/agent_chat/runner_api.py@@ -336,6 +336,16 @@ async def run_api_turn(handle: TurnHandle, user_text: str) -> None:if delta.usage:for k, v in delta.usage.items():usage_total[k] = usage_total.get(k, 0) + int(v or 0)+ # Tokens as they are counted, so the live line can+ # say what the turn has spent so far. Providers+ # report usage a handful of times per turn, not per+ # token, so this needs no throttling of its own.+ await handle.emit(+ make_event(+ "usage_delta",+ {"turn_id": handle.turn_id, "usage": dict(usage_total)},+ )+ )except asyncio.CancelledError:raiseexcept Exception as exc: # noqa: BLE001 — provider error ends the turn honestlydiff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.pyindex c97db9ba78..73345a3f32 100644--- a/jarvis/agent_chat/runner_cli.py+++ b/jarvis/agent_chat/runner_cli.py@@ -545,6 +545,17 @@ def supports_cli_runner(runner: str) -> bool:# ------------------------------------------------------------ translation+#: The token fields a Claude CLI message reports. The two cache fields carry+#: the bulk of a real turn — a warm session reads tens of thousands of cached+#: tokens while ``input_tokens`` counts only the handful that were new — so a+#: counter that skips them under-reports by orders of magnitude (BUG-173).+_CLAUDE_USAGE_KEYS: Final[tuple[str, ...]] = (+ "input_tokens",+ "output_tokens",+ "cache_read_input_tokens",+ "cache_creation_input_tokens",+)+@dataclass(slots=True)class _ClaudeState:@@ -554,6 +565,10 @@ class _ClaudeState:text_acc: dict[str, str] = field(default_factory=dict)thinking_acc: dict[str, str] = field(default_factory=dict)thinking_started: dict[str, float] = field(default_factory=dict)+ #: Message ids whose thinking block was announced live (one card each).+ thinking_announced: set[str] = field(default_factory=set)+ #: Per-message usage as the CLI reports it — summed into the live counter.+ usage_by_message: dict[str, dict[str, int]] = field(default_factory=dict)emitted_tool_ids: set[str] = field(default_factory=set)emitted_text: bool = Falsestatus: str = "done"@@ -613,6 +628,17 @@ def translate_claude_line(obj: dict[str, Any], st: _ClaudeState) -> list[dict[stmid = st.current_message_id or uuid.uuid4().hexst.current_message_id = midst.thinking_started.setdefault(mid, time.perf_counter())+ # Claude Code redacts thinking text in its stream, so without+ # this the UI learned of eight seconds of thought only once it+ # was over. Announce the block the moment it opens.+ if mid not in st.thinking_announced:+ st.thinking_announced.add(mid)+ out.append(+ make_event(+ "reasoning_started",+ {"turn_id": st.turn_id, "message_id": mid},+ )+ )elif et == "content_block_delta":delta = ev.get("delta") or {}mid = st.current_message_id or uuid.uuid4().hex@@ -638,6 +664,34 @@ def translate_claude_line(obj: dict[str, Any], st: _ClaudeState) -> list[dict[stmessage = obj.get("message") or {}mid = str(message.get("id") or st.current_message_id or uuid.uuid4().hex)st.current_message_id = mid+ usage_now = message.get("usage")+ if isinstance(usage_now, dict):+ counted = {+ k: int(usage_now[k])+ for k in _CLAUDE_USAGE_KEYS+ if isinstance(usage_now.get(k), int | float)+ }+ # A message's first usage report is the ``message_start`` snapshot:+ # the input side is already final, ``output_tokens`` is a placeholder+ # that only becomes true later. Keep the largest value seen so a+ # placeholder can never walk a real count back down (BUG-173).+ previous = st.usage_by_message.get(mid)+ if previous:+ counted = {+ k: max(counted.get(k, 0), previous.get(k, 0)) for k in (*counted, *previous)+ }+ if counted and counted != previous:+ st.usage_by_message[mid] = counted+ totals: dict[str, int] = {}+ for per_message in st.usage_by_message.values():+ for k, v in per_message.items():+ totals[k] = totals.get(k, 0) + v+ out.append(+ make_event(+ "usage_delta",+ {"turn_id": st.turn_id, "usage": totals},+ )+ )content = message.get("content") or []if not isinstance(content, list):content = [{"type": "text", "text": str(content)}]@@ -837,6 +891,14 @@ def translate_codex_line(obj: dict[str, Any], st: _CodexState) -> list[dict[str,return outif itype == "reasoning":text = str(item.get("text") or "")+ if phase == "started":+ out.append(+ make_event(+ "reasoning_started",+ {"turn_id": st.turn_id, "message_id": item_id},+ )+ )+ return outif phase == "completed" and text.strip():out.append(make_event(diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsxindex af23d099b4..5884ca6c8b 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx@@ -1,24 +1,25 @@-import { memo, useEffect, useState } from "react";+import { memo, useEffect, useMemo, useState } from "react";import ReactMarkdown from "react-markdown";import remarkGfm from "remark-gfm";import {+ ArrowDown,+ ArrowUp,Check,ChevronRight,CircleAlert,- FileDiff,- FilePen,- FileText,- FolderSearch,- Globe,+ Clock,ShieldQuestion,- TerminalSquare,- Wrench,X,- type LucideIcon,} from "lucide-react";import { ProviderLogo } from "@/components/providers/ProviderLogo";import { formatThoughtDuration } from "@/components/home/TurnSteps";+import {+ agentToolView,+ formatTokens,+ inputTokens,+ outputTokens,+} from "@/components/agentchat/toolView";import type {ReasoningBlock,TextBlock,@@ -34,10 +35,21 @@ 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). Inside a turn, in- * the order they happened: reasoning folded to "Thought for Ns", tool- * calls as rows you can open to read the input and output, approval cards- * where the runner asked, and the answer as Markdown.+ * answered (the provider's mark, the model, the effort).+ *+ * A turn hangs off a hairline rail that GLOWS while the turn runs, so the+ * whole block reads as one live unit instead of a list of disconnected+ * rows. On the rail, in the order they happened: what the model thought+ * (folded to "Thought for Ns"; a vendor that redacts its thinking still+ * gets the 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.+ *+ * While it works there is ALWAYS a line saying so (maintainer, 2026-08-23:+ * "man sieht nicht, dass es nachdenkt"): a turning glyph, a word that+ * changes as the minutes pass, the elapsed time and the tokens counted so+ * far — the Claude CLI's "✳ Vibing… (1m 57s · ↓ 4.8k tokens)", in the+ * product's own colours.*/export function AgentTimeline({items,@@ -107,17 +119,19 @@ const Turn = memo(function Turn({const t = useT();const live = turn.status === "running";const elapsed = useElapsedMs(live ? turn.startedMs : null);- const hasText = turn.blocks.some((b) => b.kind === "text" && b.text.trim());return (<div- className="flex flex-col gap-1.5 px-1"+ className="flex flex-col gap-1.5"data-testid="agent-turn"data-message-id={turn.id}data-status={turn.status}>- <div className="flex items-center gap-2 font-mono text-[10px] uppercase tracking-[0.14em] text-primary">- <span className="h-1 w-1 rounded-full bg-primary" aria-hidden />+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 px-1 font-mono text-[10px] uppercase tracking-[0.14em] text-primary">+ <span+ className={cn("h-1 w-1 rounded-full bg-primary", live && "motion-safe:animate-pulse")}+ aria-hidden+ /><span>{assistantName}</span><span className="inline-flex items-center gap-1.5 normal-case tracking-normal text-muted-foreground"><ProviderLogo providerId={turn.provider} label={providerLabel} size="sm" />@@ -129,64 +143,151 @@ const Turn = memo(function Turn({</span></div>- {turn.blocks.length > 0 && (- <div className="flex flex-col gap-1">- {turn.blocks.map((block) => {- if (block.kind === "text") return <Prose key={block.id} block={block} />;- if (block.kind === "reasoning") return <Reasoning key={block.id} block={block} />;- return <ToolRow key={block.callId} block={block} onDecide={onDecide} />;- })}- </div>- )}+ {/* The rail: everything the turn produced hangs off one line. */}+ <div className="relative flex flex-col gap-1.5 pl-4">+ <span+ aria-hidden+ data-testid="agent-turn-rail"+ className={cn(+ "absolute bottom-1 left-[3px] top-1 w-px rounded-full",+ live ? "agent-rail-live" : "bg-border",+ )}+ />- {live && !hasText && (- <div- className="flex items-center gap-2 text-xs text-muted-foreground"- data-testid="agent-turn-live"- >- <Spinner />- <span>- {elapsed > 0- ? fill(t("agent_chat.working_for"), { duration: formatThoughtDuration(elapsed) })- : t("agent_chat.working")}- </span>- </div>- )}+ {turn.blocks.map((block) => {+ if (block.kind === "text") return <Prose key={block.id} block={block} />;+ if (block.kind === "reasoning") return <Reasoning key={block.id} block={block} />;+ return <ToolRow key={block.callId} block={block} onDecide={onDecide} />;+ })}- {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>- )}- {turn.status === "cancelled" && (- <div className="text-xs italic text-muted-foreground">{t("agent_chat.turn_cancelled")}</div>- )}- {turn.status !== "running" && (turn.durationMs || turn.costUsd !== null) && (- <div className="flex items-center gap-2 font-mono text-[10px] text-muted-foreground/70">- {turn.durationMs ? <span>{formatThoughtDuration(turn.durationMs)}</span> : null}- {usageLine(turn.usage) && <span>· {usageLine(turn.usage)}</span>}- {turn.costUsd !== null && turn.costUsd > 0 && <span>· ${turn.costUsd.toFixed(4)}</span>}- </div>- )}+ {live && <LiveStatus turn={turn} elapsed={elapsed} />}++ {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>+ )}+ {turn.status === "cancelled" && (+ <div className="text-xs italic text-muted-foreground">+ {t("agent_chat.turn_cancelled")}+ </div>+ )}++ {!live && <TurnFooter turn={turn} />}+ </div></div>);});-function usageLine(usage: Record<string, unknown> | null): string {- if (!usage) return "";- const inp = num(usage.input_tokens ?? usage.input);- const out = num(usage.output_tokens ?? usage.output);- if (inp === null && out === null) return "";- return `${inp ?? 0} in · ${out ?? 0} out`;+/**+ * The line that says the turn is alive.+ *+ * A turning glyph, a word, the elapsed time and the tokens 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.+ */+function LiveStatus({ turn, elapsed }: { turn: TurnItem; elapsed: number }) {+ 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(turn.liveUsage);+ const inp = inputTokens(turn.liveUsage);++ return (+ <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"+ >+ <PulseGlyph />+ <span className="thinking-shimmer font-medium">{word}</span>+ <span className="font-mono text-[11px] tabular-nums text-muted-foreground/80">+ ({formatThoughtDuration(elapsed)}+ {((inp ?? 0) > 0 || (out ?? 0) > 0) && (+ <>+ {" · "}+ <ArrowUp className="inline h-3 w-3 -translate-y-px" aria-hidden />+ {formatTokens(inp ?? 0)}+ <ArrowDown className="ml-1 inline h-3 w-3 -translate-y-px" aria-hidden />+ {formatTokens(out ?? 0)} {t("agent_chat.tokens")}+ </>+ )}+ )+ </span>+ <span className="text-muted-foreground/60">{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…"];+}++/** The turning asterisk: one small SVG, animated by CSS (index.css). */+function PulseGlyph() {+ return (+ <svg+ viewBox="0 0 12 12"+ className="agent-glyph h-3.5 w-3.5 shrink-0 text-primary"+ aria-hidden+ data-testid="agent-glyph"+ >+ <g stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">+ <line x1="6" y1="1.2" x2="6" y2="10.8" />+ <line x1="1.85" y1="3.6" x2="10.15" y2="8.4" />+ <line x1="1.85" y1="8.4" x2="10.15" y2="3.6" />+ </g>+ </svg>+ );}-function num(v: unknown): number | null {- return typeof v === "number" && Number.isFinite(v) ? v : null;+/** What the finished turn cost: time, tokens, money — the receipt. */+function TurnFooter({ turn }: { turn: TurnItem }) {+ const t = useT();+ const usage = turn.usage ?? turn.liveUsage;+ const inp = inputTokens(usage);+ const out = outputTokens(usage);+ const hasTokens = (inp ?? 0) > 0 || (out ?? 0) > 0;+ if (!turn.durationMs && !hasTokens && !turn.costUsd) return null;++ return (+ <div+ className="flex flex-wrap items-center gap-x-2.5 gap-y-0.5 pt-0.5 font-mono text-[10px] tabular-nums text-muted-foreground/70"+ data-testid="agent-turn-footer"+ >+ {turn.durationMs ? (+ <span className="inline-flex items-center gap-1">+ <Clock className="h-3 w-3" aria-hidden />+ {formatThoughtDuration(turn.durationMs)}+ </span>+ ) : null}+ {hasTokens && (+ <span className="inline-flex items-center gap-1" title={t("agent_chat.tokens")}>+ <ArrowUp className="h-3 w-3" aria-hidden />+ {formatTokens(inp ?? 0)}+ <ArrowDown className="ml-1 h-3 w-3" aria-hidden />+ {formatTokens(out ?? 0)}+ <span className="ml-0.5">{t("agent_chat.tokens")}</span>+ </span>+ )}+ {turn.costUsd !== null && turn.costUsd > 0 && <span>${turn.costUsd.toFixed(4)}</span>}+ </div>+ );}function Prose({ block }: { block: TextBlock }) {@@ -208,34 +309,57 @@ function Prose({ block }: { block: TextBlock }) {);}+/**+ * What the model thought.+ *+ * Live: a shimmering "Thinking…" with the seconds ticking — shown even when+ * the vendor never streams the thought itself (Claude Code redacts it), so+ * eight silent seconds are visibly eight seconds of thinking. Finished:+ * "Thought for 8s", opening to the text when there IS text; when there is+ * none the row says so instead of opening onto emptiness.+ */function Reasoning({ block }: { block: ReasoningBlock }) {const t = useT();const [open, setOpen] = useState(false);+ const elapsed = useElapsedMs(block.live ? block.startedMs : null);+ const hasText = Boolean(block.text.trim());+ const duration = block.live ? elapsed : (block.durationMs ?? 0);const header = block.live- ? t("agent_chat.thinking")- : block.durationMs- ? fill(t("agent_chat.thought_for"), { duration: formatThoughtDuration(block.durationMs) })+ ? duration > 900+ ? fill(t("agent_chat.thinking_for"), { duration: formatThoughtDuration(duration) })+ : t("agent_chat.thinking")+ : duration > 0+ ? fill(t("agent_chat.thought_for"), { duration: formatThoughtDuration(duration) }): t("agent_chat.thought");+return (<div data-testid="agent-reasoning" data-live={block.live || undefined}><buttontype="button"onClick={() => setOpen((v) => !v)}aria-expanded={open}- className="inline-flex items-center gap-1.5 rounded-md py-0.5 pr-2 text-xs text-muted-foreground transition-colors hover:text-foreground"+ disabled={!hasText}+ className={cn(+ "inline-flex items-center gap-1.5 rounded-md py-0.5 pr-2 text-xs text-muted-foreground transition-colors",+ hasText ? "hover:text-foreground" : "cursor-default",+ )}>{block.live ? (- <Spinner />+ <PulseGlyph />) : (<ChevronRight- className={cn("h-3.5 w-3.5 transition-transform", open && "rotate-90")}+ className={cn(+ "h-3.5 w-3.5 shrink-0 transition-transform",+ open && "rotate-90",+ !hasText && "opacity-30",+ )}aria-hidden/>)}- <span>{header}</span>+ <span className={cn(block.live && "thinking-shimmer font-medium")}>{header}</span></button>- {open && block.text && (- <div className="ml-2 mt-1 border-l border-border pl-3 text-xs italic leading-relaxed text-muted-foreground whitespace-pre-wrap">+ {open && hasText && (+ <div className="ml-2 mt-1 whitespace-pre-wrap border-l border-border pl-3 text-xs italic leading-relaxed text-muted-foreground">{block.text}</div>)}@@ -243,34 +367,6 @@ function Reasoning({ block }: { block: ReasoningBlock }) {);}-const TOOL_ICON: Array<[RegExp, LucideIcon]> = [- [/^(bash|run_?command|shell|command|exec)/i, TerminalSquare],- [/^(edit|multi_?edit|apply_?patch|str_replace)/i, FileDiff],- [/^(write|create_?file|notebook_?edit)/i, FilePen],- [/^(read|cat|view|open_?file)/i, FileText],- [/^(glob|grep|ls|list|search|find)/i, FolderSearch],- [/^(web_?fetch|web_?search|fetch|browse)/i, Globe],-];--function toolIcon(name: string): LucideIcon {- for (const [re, icon] of TOOL_ICON) if (re.test(name)) return icon;- return Wrench;-}--/** A one-line gist of a tool's input: the command, the path, the pattern. */-function inputSummary(input: unknown): string {- if (input === null || input === undefined) return "";- if (typeof input === "string") return input;- if (typeof input !== "object") return String(input);- const obj = input as Record<string, unknown>;- for (const key of ["command", "cmd", "file_path", "path", "pattern", "query", "url", "description"]) {- const v = obj[key];- if (typeof v === "string" && v.trim()) return v;- }- const first = Object.values(obj).find((v) => typeof v === "string" && v.trim());- return typeof first === "string" ? first : "";-}-function pretty(value: unknown): string {if (typeof value === "string") return value;try {@@ -280,6 +376,15 @@ function pretty(value: unknown): string {}}+/**+ * One tool call.+ *+ * 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. Click to read what went in and+ * what came back.+ */function ToolRow({block,onDecide,@@ -289,20 +394,32 @@ function ToolRow({}) {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 Icon = toolIcon(block.name);- const summary = inputSummary(block.input);+ const view = agentToolView(block.name, block.input);+ const summary = view.summary;+ const showLogo = Boolean(view.logoUrl) && !logoFailed;return (<divdata-testid="agent-tool"data-tool={block.name}- data-state={pending ? "pending" : denied ? "denied" : done ? (block.isError ? "error" : "done") : "running"}+ data-family={view.family}+ data-state={+ pending ? "pending" : denied ? "denied" : done ? (block.isError ? "error" : "done") : "running"+ }className={cn(- "rounded-lg border text-xs",- pending ? "border-primary/40 bg-primary/5" : "border-border/70 bg-secondary/30",+ "overflow-hidden rounded-lg border text-xs transition-colors",+ pending+ ? "border-primary/40 bg-primary/5"+ : block.isError+ ? "border-destructive/30 bg-destructive/5"+ : running+ ? "border-primary/25 bg-secondary/40"+ : "border-border/60 bg-secondary/25 hover:border-border",)}><button@@ -312,30 +429,49 @@ function ToolRow({className="flex w-full min-w-0 items-center gap-2 px-2.5 py-1.5 text-left"><span className="grid h-5 w-5 shrink-0 place-items-center">- {!done && !pending && !denied ? (+ {running ? (<Spinner />) : block.isError ? (<CircleAlert className="h-3.5 w-3.5 text-destructive" aria-hidden />) : 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)}+ />) : (- <Icon className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />+ <view.Icon className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />)}</span>- <span className="shrink-0 font-medium text-foreground">{block.name}</span>- {summary && (+ <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-[11px] text-muted-foreground">{summary}</span>+ ) : (+ <span className="flex-1" />)}- {!summary && <span className="flex-1" />}- {block.durationMs !== null && (- <span className="shrink-0 font-mono text-[10px] text-muted-foreground/70">+ {block.durationMs !== null && block.durationMs > 0 && (+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground/70">{formatStepDuration(block.durationMs)}</span>)}<ChevronRight- className={cn("h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform", open && "rotate-90")}+ className={cn(+ "h-3.5 w-3.5 shrink-0 text-muted-foreground/70 transition-transform",+ open && "rotate-90",+ )}aria-hidden/></button>@@ -385,15 +521,15 @@ function ToolRow({{block.input !== undefined && block.input !== null && (<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 && (+ {denied && <div className="text-muted-foreground">{t("agent_chat.approval_denied")}</div>}+ {block.output !== null ? (<Detaillabel={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>)}</div>)}@@ -434,13 +570,19 @@ function Spinner() {);}-/** Elapsed wall-clock since `startedTs`, ticking once a second while set. */+/**+ * 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()), 1000);+ 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/reduce.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.tsindex 6edf747439..f6fe79d650 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts@@ -69,4 +69,55 @@ describe("agent-chat reduce", () => {expect(tl.sessionPatch).toBeNull();expect((tl.items[0] as TurnItem).status).toBe("cancelled");});++ it("shows redacted thinking: announced live, closed by the textless finished block", () => {+ let tl = reduceEvents(EMPTY_TIMELINE, [+ ev("turn_started", { turn_id: "t5" }),+ ev("reasoning_started", { turn_id: "t5", message_id: "m1" }, false),+ ]);+ let turn = tl.items[0] as TurnItem;+ expect(turn.blocks[0]).toMatchObject({ kind: "reasoning", text: "", live: true });+ // A second announcement for the same thought does not add a row.+ tl = reduceEvent(tl, ev("reasoning_started", { turn_id: "t5", message_id: "m1" }, false));+ expect((tl.items[0] as TurnItem).blocks).toHaveLength(1);+ tl = reduceEvent(tl, ev("reasoning", { turn_id: "t5", text: "", duration_ms: 8500 }));+ turn = tl.items[0] as TurnItem;+ expect(turn.blocks[0]).toMatchObject({ kind: "reasoning", text: "", live: false, durationMs: 8500 });+ // A textless finished block with a duration and no live row still lands.+ tl = reduceEvent(tl, ev("reasoning", { turn_id: "t5", text: "", duration_ms: 1200 }));+ expect((tl.items[0] as TurnItem).blocks).toHaveLength(2);+ // ...but one with neither text nor time is nothing.+ tl = reduceEvent(tl, ev("reasoning", { turn_id: "t5", text: "", duration_ms: 0 }));+ expect((tl.items[0] as TurnItem).blocks).toHaveLength(2);+ });++ it("ends a live thought when text or a tool call follows, and times tool calls from the log", () => {+ let tl = reduceEvents(EMPTY_TIMELINE, [+ ev("turn_started", { turn_id: "t6" }),+ ev("reasoning_started", { turn_id: "t6", message_id: "m1" }, false),+ ev("tool_call", { turn_id: "t6", call_id: "c1", name: "Grep", input: { pattern: "x" } }),+ ]);+ let turn = tl.items[0] as TurnItem;+ expect(turn.blocks[0]).toMatchObject({ kind: "reasoning", live: false });+ expect(turn.blocks[1]).toMatchObject({ kind: "tool", name: "Grep" });+ const callTs = (turn.blocks[1] as { startedMs: number }).startedMs;+ const result = ev("tool_result", { turn_id: "t6", call_id: "c1", output: "hit", is_error: false });+ result.ts_ms = callTs + 340;+ tl = reduceEvent(tl, result);+ turn = tl.items[0] as TurnItem;+ expect(turn.blocks[1]).toMatchObject({ kind: "tool", output: "hit", durationMs: 340 });+ });++ it("counts tokens live and keeps them when the finished turn brings no usage", () => {+ let tl = reduceEvents(EMPTY_TIMELINE, [+ ev("turn_started", { turn_id: "t7" }),+ ev("usage_delta", { turn_id: "t7", usage: { input_tokens: 3, output_tokens: 40 } }, false),+ ev("usage_delta", { turn_id: "t7", usage: { input_tokens: 4, output_tokens: 65 } }, false),+ ]);+ expect((tl.items[0] as TurnItem).liveUsage).toEqual({ input_tokens: 4, output_tokens: 65 });+ tl = reduceEvent(tl, ev("turn_finished", { turn_id: "t7", status: "done" }));+ const turn = tl.items[0] as TurnItem;+ expect(turn.usage).toEqual({ input_tokens: 4, output_tokens: 65 });+ expect(turn.durationMs).not.toBeNull();+ });});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.tsindex baf382b855..2332c9206c 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts@@ -25,10 +25,13 @@ export interface TextBlock {export interface ReasoningBlock {kind: "reasoning";id: string;+ /** Empty when the vendor redacts its thinking — the block still says it happened. */text: string;durationMs: number | null;/** Still streaming — the finished block carries the duration. */live: boolean;+ /** When the model began to think (drives the live elapsed counter). */+ startedMs: number;}export interface ApprovalState {@@ -47,6 +50,8 @@ export interface ToolBlock {isError: boolean;durationMs: number | null;approval: ApprovalState | null;+ /** When the call was made; a result without its own duration is timed from here. */+ startedMs: number;}export type TurnBlock = TextBlock | ReasoningBlock | ToolBlock;@@ -72,6 +77,8 @@ export interface TurnItem {startedMs: number;durationMs: number | null;usage: Record<string, unknown> | null;+ /** Tokens so far while the turn runs (``usage_delta``); the finished usage replaces it. */+ liveUsage: Record<string, number> | null;costUsd: number | null;error: string | null;}@@ -145,6 +152,21 @@ function updateTurn(return { ...tl, items: replaceAt(tl.items, idx, next) };}+/** A live reasoning block that text or a tool call is about to follow is over. */+function closeLiveReasoning(turn: TurnItem, nowMs: number): TurnItem {+ const i = turn.blocks.findIndex((b) => b.kind === "reasoning" && b.live);+ if (i < 0) return turn;+ const block = turn.blocks[i] as ReasoningBlock;+ return {+ ...turn,+ blocks: replaceAt(turn.blocks, i, {+ ...block,+ live: false,+ durationMs: block.durationMs ?? Math.max(0, nowMs - block.startedMs),+ }),+ };+}+function upsertBlock<B extends TurnBlock>(turn: TurnItem,match: (b: TurnBlock) => boolean,@@ -193,6 +215,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {startedMs: ev.ts_ms,durationMs: null,usage: null,+ liveUsage: null,costUsd: null,error: null,},@@ -205,7 +228,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {if (!delta) return base;return updateTurn(base, turnId, (turn) =>upsertBlock<TextBlock>(- turn,+ closeLiveReasoning(turn, ev.ts_ms),(b) => b.kind === "text" && b.id === id,(ex) => ({ kind: "text", id, text: (ex?.text ?? "") + delta }),),@@ -217,13 +240,36 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {const text = str(p.text);return updateTurn(base, turnId, (turn) =>upsertBlock<TextBlock>(- turn,+ closeLiveReasoning(turn, ev.ts_ms),(b) => b.kind === "text" && b.id === id,(ex) => (ex && ex.text === text ? ex : { kind: "text", id, text }),),);}+ case "reasoning_started":+ // The model began to think. Its thinking may never stream (Claude Code+ // redacts it), so this is what the person sees meanwhile: one live+ // row, "Thinking…", counting the seconds until the finished block.+ return updateTurn(base, turnId, (turn) => {+ const last = turn.blocks[turn.blocks.length - 1];+ if (last && last.kind === "reasoning" && last.live) return turn;+ return {+ ...turn,+ blocks: [+ ...turn.blocks,+ {+ kind: "reasoning",+ id: `r-${turn.blocks.length}`,+ text: "",+ durationMs: null,+ live: true,+ startedMs: ev.ts_ms,+ },+ ],+ };+ });+case "reasoning_delta": {const delta = str(p.text);if (!delta) return base;@@ -243,7 +289,14 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {...turn,blocks: [...turn.blocks,- { kind: "reasoning", id: `r-${turn.blocks.length}`, text: delta, durationMs: null, live: true },+ {+ kind: "reasoning",+ id: `r-${turn.blocks.length}`,+ text: delta,+ durationMs: null,+ live: true,+ startedMs: ev.ts_ms,+ },],};});@@ -260,17 +313,26 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {blocks: replaceAt(turn.blocks, turn.blocks.length - 1, {...last,text: text || last.text,- durationMs,+ durationMs: durationMs ?? Math.max(0, ev.ts_ms - last.startedMs),live: false,}),};}- if (!text) return turn;+ // A finished block with no text is still a fact worth a row when it+ // took time ("Thought for 8s") — redacted thinking is thinking too.+ if (!text && !(durationMs && durationMs > 0)) return turn;return {...turn,blocks: [...turn.blocks,- { kind: "reasoning", id: `r-${turn.blocks.length}`, text, durationMs, live: false },+ {+ kind: "reasoning",+ id: `r-${turn.blocks.length}`,+ text,+ durationMs,+ live: false,+ startedMs: ev.ts_ms - (durationMs ?? 0),+ },],};});@@ -280,7 +342,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {const callId = str(p.call_id);return updateTurn(base, turnId, (turn) =>upsertBlock<ToolBlock>(- turn,+ closeLiveReasoning(turn, ev.ts_ms),(b) => b.kind === "tool" && b.callId === callId,(ex) =>ex ?? {@@ -292,6 +354,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {isError: false,durationMs: null,approval: null,+ startedMs: ev.ts_ms,},),);@@ -310,13 +373,29 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {input: ex?.input,output: str(p.output, ""),isError: Boolean(p.is_error),- durationMs: num(p.duration_ms),+ // The runner rarely knows how long a call took; the log does —+ // the result's timestamp minus the call's.+ durationMs:+ num(p.duration_ms) ?? (ex ? Math.max(0, ev.ts_ms - ex.startedMs) : null),approval: ex?.approval ?? null,+ startedMs: ex?.startedMs ?? ev.ts_ms,}),),);}+ case "usage_delta": {+ const usage = p.usage;+ if (!usage || typeof usage !== "object") return base;+ const counts: Record<string, number> = {};+ for (const [k, v] of Object.entries(usage as Record<string, unknown>)) {+ const n = num(v);+ if (n !== null) counts[k] = n;+ }+ if (Object.keys(counts).length === 0) return base;+ return updateTurn(base, turnId, (turn) => ({ ...turn, liveUsage: counts }));+ }+case "approval_required": {const approvalId = str(p.approval_id);const callId = str(p.call_id);@@ -341,6 +420,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {isError: ex?.isError ?? false,durationMs: ex?.durationMs ?? null,approval: { approvalId, summary: pending.summary, decision: null },+ startedMs: ex?.startedMs ?? ev.ts_ms,}),),);@@ -382,9 +462,16 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {...turn,status: status === "running" ? "done" : status,// A turn that ended mid-stream closes its live reasoning block.- blocks: turn.blocks.map((b) => (b.kind === "reasoning" && b.live ? { ...b, live: false } : b)),- durationMs: num(p.duration_ms),- usage: p.usage && typeof p.usage === "object" ? (p.usage as Record<string, unknown>) : null,+ blocks: turn.blocks.map((b) =>+ b.kind === "reasoning" && b.live+ ? { ...b, live: false, durationMs: b.durationMs ?? Math.max(0, ev.ts_ms - b.startedMs) }+ : b,+ ),+ durationMs: num(p.duration_ms) ?? Math.max(0, ev.ts_ms - turn.startedMs),+ usage:+ p.usage && typeof p.usage === "object" && Object.keys(p.usage as object).length > 0+ ? (p.usage as Record<string, unknown>)+ : turn.liveUsage,costUsd: num(p.cost_usd),error: str(p.error, "") || null,}));diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolView.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/toolView.test.tsnew file mode 100644index 0000000000..012edea087--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolView.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it } from "vitest";++import {+ agentToolView,+ formatTokens,+ inputSummary,+ inputTokens,+ outputTokens,+} from "@/components/agentchat/toolView";++describe("agentToolView", () => {+ it("keeps the agent's own tool name — the row must match the log", () => {+ expect(agentToolView("PowerShell", { command: "Get-ChildItem" })).toMatchObject({+ label: "PowerShell",+ family: "shell",+ summary: "Get-ChildItem",+ });+ expect(agentToolView("ToolSearch", { query: "chrome tabs" })).toMatchObject({+ label: "ToolSearch",+ family: "tools",+ summary: "chrome tabs",+ });+ // A Grep shows WHAT was searched for, not the folder it looked in — the+ // path alone reads as the wrong call next to the agent's log.+ const grep = agentToolView("Grep", {+ path: "C:\\Users\\Administrator\\Desktop",+ pattern: "permissionMode",+ });+ expect(grep.label).toBe("Grep");+ expect(grep.summary).toBe("permissionMode");+ expect(agentToolView("Read", { file_path: "a.py", pattern: "x" }).summary).toBe("a.py");+ expect(agentToolView("Read", { file_path: "a.py" }).family).toBe("read");+ expect(agentToolView("MultiEdit", {}).family).toBe("edit");+ expect(agentToolView("Bash", { command: "ls -la\nsecond line" }).summary).toBe("ls -la");+ expect(agentToolView("TodoWrite", {}).family).toBe("plan");+ expect(agentToolView("Task", { prompt: "go" }).family).toBe("agent");+ });++ it("names an MCP call after its server and wears the vendor mark when there is one", () => {+ const gh = agentToolView("mcp__github__create_issue", { title: "Bug" });+ expect(gh.family).toBe("mcp");+ expect(gh.label).toBe("GitHub · Create Issue");+ expect(gh.logoUrl).toBeTruthy();+ const slash = agentToolView("blender/get_scene_info", {});+ expect(slash.family).toBe("mcp");+ expect(slash.label).toContain("Blender");+ });++ it("falls back to a wrench for a tool nobody knows, never to nothing", () => {+ const odd = agentToolView("frobnicate", { thing: "x" });+ expect(odd.label).toBe("frobnicate");+ expect(odd.family).toBe("other");+ expect(agentToolView("", {}).label).toBe("tool");+ });+});++describe("inputSummary", () => {+ it("prefers the human field and keeps it to one line", () => {+ expect(inputSummary({ command: "pytest -q" })).toBe("pytest -q");+ expect(inputSummary({ nothing: 3, note: "hello" })).toBe("hello");+ expect(inputSummary("plain string")).toBe("plain string");+ expect(inputSummary(null)).toBe("");+ expect(inputSummary({ command: "x".repeat(300) })).toHaveLength(200);+ });+});++describe("token formatting", () => {+ it("reads like the Claude CLI: 4.8k, 1.2M", () => {+ expect(formatTokens(219)).toBe("219");+ expect(formatTokens(4800)).toBe("4.8k");+ expect(formatTokens(12000)).toBe("12k");+ expect(formatTokens(1_200_000)).toBe("1.2M");+ expect(formatTokens(-5)).toBe("0");+ });++ it("reads either usage shape", () => {+ expect(outputTokens({ output_tokens: 5 })).toBe(5);+ expect(outputTokens({ output: 7 })).toBe(7);+ expect(inputTokens({ prompt_tokens: 9 })).toBe(9);+ expect(outputTokens(null)).toBeNull();+ expect(outputTokens({})).toBeNull();+ });++ it("counts the cache into the input side, and never twice", () => {+ // Anthropic keeps the cached part beside input_tokens; both are paid for.+ expect(+ inputTokens({+ input_tokens: 2,+ cache_creation_input_tokens: 30420,+ cache_read_input_tokens: 21355,+ }),+ ).toBe(51777);+ // The OpenAI shape counts cached tokens INSIDE prompt_tokens already.+ expect(inputTokens({ prompt_tokens: 900, cached_input_tokens: 800 })).toBe(900);+ expect(inputTokens({ cache_read_input_tokens: 40 })).toBe(40);+ expect(inputTokens({})).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolView.ts b/jarvis/ui/web/frontend/src/components/agentchat/toolView.tsnew file mode 100644index 0000000000..cde5940da6--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolView.ts@@ -0,0 +1,223 @@+/**+ * Tool call → how the agent chat draws its row: an icon (or the vendor mark+ * for an MCP server), the name the way the agent's own log spells it, and a+ * one-line gist of the input.+ *+ * The name is NOT translated or renamed — a row that says "PowerShell" when+ * the agent's transcript says "PowerShell" is the whole point (maintainer,+ * 2026-08-23: the row has to match the log). What this module adds is the+ * right mark per tool: Claude Code's and Codex's tool names first, then MCP+ * calls ("mcp__server__tool" / "server/tool") with the server's brand,+ * then the Jarvis tool families of the API runner, then a plain wrench.+ *+ * Pure — no React — so the mapping is unit-testable and identical wherever+ * a tool row is drawn.+ */++import {+ Bot,+ FileDiff,+ FilePen,+ FileText,+ FolderSearch,+ Globe,+ ListChecks,+ Map as MapIcon,+ MessageCircleQuestion,+ PackageSearch,+ Plug,+ Search,+ TerminalSquare,+ Wand2,+ Wrench,+ type LucideIcon,+} from "lucide-react";++import { describeToolStep } from "@/lib/toolStepLabel";++export interface AgentToolView {+ /** The name as the log spells it (MCP: "server · tool"). */+ label: string;+ Icon: LucideIcon;+ /** A vendor SVG for the tile when the call belongs to a known MCP server. */+ logoUrl?: string;+ /** One-line gist of the input: the command, the path, the pattern, the query. */+ summary: string;+ /** Coarse family for styling hooks and tests. */+ family: "shell" | "edit" | "write" | "read" | "search" | "web" | "agent" | "plan" | "ask" | "skill" | "tools" | "mcp" | "jarvis" | "other";+}++/** Claude Code, Codex and agy tool names — the agent's own vocabulary. */+const CLI_TOOLS: Array<[RegExp, AgentToolView["family"], LucideIcon]> = [+ [/^(bash|powershell|shell|run_?command|command|exec|terminal|cmd)$/i, "shell", TerminalSquare],+ [/^(edit|multi_?edit|apply_?patch|str_replace(_based_edit_tool)?|notebook_?edit)$/i, "edit", FileDiff],+ [/^(write|create_?file|write_?file)$/i, "write", FilePen],+ [/^(read|cat|view|open_?file|read_?file)$/i, "read", FileText],+ [/^(glob|ls|list_?dir(ectory)?)$/i, "search", FolderSearch],+ [/^(grep|search|find|rg|code_?search)$/i, "search", Search],+ [/^tool_?search$/i, "tools", PackageSearch],+ [/^(web_?fetch|web_?search|fetch|browse|http)$/i, "web", Globe],+ [/^(agent|task|sub_?agent|spawn(_?agents?)?|delegate)$/i, "agent", Bot],+ [/^(todo_?write|todo_?read|update_?plan|plan)$/i, "plan", ListChecks],+ [/^(enter|exit)_?plan_?mode$/i, "plan", MapIcon],+ [/^(ask_?user(_?question)?|question)$/i, "ask", MessageCircleQuestion],+ [/^skill$/i, "skill", Wand2],+];++/**+ * Which argument IS the call, per family.+ *+ * The order matters more than it looks: a Grep carries both a pattern and a+ * path, and a row that shows the path says nothing about what was searched+ * for — next to the agent's own log it reads as the wrong call+ * (maintainer, 2026-08-23). So each family names its own headline field+ * first and falls through to the generic list after.+ */+const SUMMARY_KEYS: Record<string, string[]> = {+ shell: ["command", "cmd", "script"],+ search: ["pattern", "query", "glob", "path", "file_path"],+ read: ["file_path", "path", "notebook_path", "url"],+ write: ["file_path", "path"],+ edit: ["file_path", "path", "notebook_path"],+ web: ["url", "query", "prompt"],+ agent: ["description", "prompt", "task"],+ plan: ["description", "plan", "todos"],+ ask: ["question", "prompt", "description"],+ skill: ["skill", "command", "name"],+ tools: ["query"],+};++const GENERIC_SUMMARY_KEYS = [+ "command",+ "cmd",+ "pattern",+ "query",+ "file_path",+ "path",+ "url",+ "prompt",+ "description",+ "skill",+ "title",+ "name",+];++/**+ * A one-line gist of a tool's input: the command, the pattern, the path.+ *+ * ``family`` picks the headline field for that kind of call; without one the+ * generic order applies. Anything else falls back to the first readable+ * string in the arguments, so a row is never blank when there was an input.+ */+export function inputSummary(input: unknown, family?: string): string {+ if (input === null || input === undefined) return "";+ if (typeof input === "string") return firstLine(input);+ if (typeof input !== "object") return String(input);+ const obj = input as Record<string, unknown>;+ const keys = [...(family ? (SUMMARY_KEYS[family] ?? []) : []), ...GENERIC_SUMMARY_KEYS];+ for (const key of keys) {+ const v = obj[key];+ if (typeof v === "string" && v.trim()) return firstLine(v);+ }+ const first = Object.values(obj).find((v) => typeof v === "string" && v.trim());+ return typeof first === "string" ? firstLine(first) : "";+}++function firstLine(text: string): string {+ const line = text.trim().split(/\r?\n/, 1)[0] ?? "";+ return line.length > 200 ? `${line.slice(0, 199)}…` : line;+}++function humanise(token: string): string {+ return token+ .split(/[_\s]+/)+ .filter(Boolean)+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))+ .join(" ");+}++/** "mcp__github__create_issue" → ["github", "create_issue"]; "github/create_issue" → same. */+function splitMcp(name: string): [string, string] | null {+ const m = /^mcp__(.+?)__(.+)$/.exec(name);+ if (m) return [m[1], m[2]];+ const slash = name.indexOf("/");+ if (slash > 0 && slash < name.length - 1) return [name.slice(0, slash), name.slice(slash + 1)];+ return null;+}++export function agentToolView(name: string, input: unknown): AgentToolView {+ const raw = (name ?? "").trim() || "tool";++ for (const [re, family, Icon] of CLI_TOOLS) {+ if (re.test(raw)) return { label: raw, Icon, summary: inputSummary(input, family), family };+ }+ const summary = inputSummary(input);++ const mcp = splitMcp(raw);+ if (mcp) {+ const [server, tool] = mcp;+ const view = describeToolStep(`${server}/${tool}`, input);+ return {+ label: view.label || `${humanise(server)} · ${humanise(tool)}`,+ Icon: Plug,+ logoUrl: view.brand?.logoUrl,+ summary,+ family: "mcp",+ };+ }++ // The API runner's own tools and anything Jarvis-shaped (wiki-recall,+ // create_artifact, …) keep their log name but borrow the family's mark.+ const jarvis = describeToolStep(raw, input);+ if (jarvis.family !== "other") {+ return {+ label: raw,+ Icon: jarvis.brand?.logoUrl ? Plug : Wrench,+ logoUrl: jarvis.brand?.logoUrl,+ summary: summary || jarvis.detail,+ family: "jarvis",+ };+ }+ return { label: raw, Icon: Wrench, summary, family: "other" };+}++/** "4800" → "4.8k", "1200000" → "1.2M"; small numbers stay as they are. */+export function formatTokens(n: number): string {+ if (!Number.isFinite(n) || n < 0) return "0";+ if (n < 1000) return String(Math.round(n));+ if (n < 1_000_000) return `${trimZero((n / 1000).toFixed(1))}k`;+ return `${trimZero((n / 1_000_000).toFixed(1))}M`;+}++function trimZero(s: string): string {+ return s.endsWith(".0") ? s.slice(0, -2) : s;+}++/** Output tokens so far, from whichever usage shape the runner reported. */+export function outputTokens(usage: Record<string, unknown> | null | undefined): number | null {+ if (!usage) return null;+ const v = usage.output_tokens ?? usage.output ?? usage.completion_tokens;+ return typeof v === "number" && Number.isFinite(v) ? v : null;+}++function finite(v: unknown): number | null {+ return typeof v === "number" && Number.isFinite(v) ? v : null;+}++/**+ * Everything the turn put IN, cache included.+ *+ * Anthropic reports the cached part separately from ``input_tokens`` and the+ * two never overlap, so a warm session that read 21k cached tokens and paid+ * for 2 new ones must read as 21k — not as 2 (BUG-173). The OpenAI shape+ * (``cached_input_tokens``) is a SUBSET of ``prompt_tokens`` and is therefore+ * deliberately not added here.+ */+export function inputTokens(usage: Record<string, unknown> | null | undefined): number | null {+ if (!usage) return null;+ const base = finite(usage.input_tokens ?? usage.input ?? usage.prompt_tokens);+ const cached = finite(usage.cache_read_input_tokens);+ const created = finite(usage.cache_creation_input_tokens);+ if (base === null && cached === null && created === null) return null;+ return (base ?? 0) + (cached ?? 0) + (created ?? 0);+}diff --git a/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx b/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsxindex 99268a8a14..0c8daf0dfd 100644--- a/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx+++ b/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx@@ -204,6 +204,47 @@ describe("ChatStage (agent chat)", () => {}});+ it("draws a different glyph per permission mode in the pill and the list", async () => {+ render(<ChatStage />);+ const pill = screen.getByTestId("composer-permission");+ // acceptEdits wears the pen, not the column's shield.+ expect(pill.querySelector("svg.lucide-file-pen")).not.toBeNull();+ expect(pill.querySelector("svg.lucide-shield-check")).toBeNull();+ fireEvent.click(pill);+ const panel = await screen.findByTestId("composer-permission-panel");+ const glyphs = within(panel)+ .getAllByRole("option")+ .map((el) => el.querySelector("svg")?.getAttribute("class") ?? "");+ // default → question shield, acceptEdits → pen, bypass → shield off; plan lives on the switch.+ expect(glyphs.some((c) => c.includes("lucide-shield-question"))).toBe(true);+ expect(glyphs.some((c) => c.includes("lucide-file-pen"))).toBe(true);+ expect(glyphs.some((c) => c.includes("lucide-shield-off"))).toBe(true);+ expect(new Set(glyphs).size).toBe(glyphs.length);+ });++ it("grows the text box with the typed text and caps it at its max height", () => {+ 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();+ }+ });+it("shows no restart notice when the catalog carries the permission ladders", () => {render(<ChatStage />);expect(screen.queryByTestId("composer-backend-outdated")).toBeNull();@@ -265,4 +306,73 @@ describe("ChatStage (agent chat)", () => {// The composer offers Stop while the turn runs.expect(screen.getByTestId("composer-stop")).toBeTruthy();});++ it("always shows that the turn is alive: glyph, a word, the clock and the tokens", () => {+ vi.useFakeTimers();+ try {+ const started = Date.now();+ const timeline = reduceEvents(EMPTY_TIMELINE, [+ ev("user_message", { text: "dig into it" }),+ { seq: 2, ts_ms: started, kind: "turn_started", payload: { turn_id: "t1", provider: "claude-api", model: "claude-opus-5", effort: "high", runner: "claude-cli" } },+ { seq: 0, ts_ms: started, kind: "reasoning_started", payload: { turn_id: "t1", message_id: "m1" } },+ { seq: 0, ts_ms: started, kind: "usage_delta", payload: { turn_id: "t1", usage: { input_tokens: 12, output_tokens: 4800 } } },+ ]);+ useAgentChatStore.setState({ activeSessionId: "s1", timeline });+ render(<ChatStage />);++ // The redacted thought is a row of its own — thinking you cannot read+ // is still thinking you can see.+ const reasoning = screen.getByTestId("agent-reasoning");+ expect(reasoning.getAttribute("data-live")).toBe("true");++ const live = screen.getByTestId("agent-turn-live");+ expect(within(live).getByTestId("agent-glyph")).toBeTruthy();+ expect(live.textContent).toMatch(/4\.8k/);+ // The clock moves on its own.+ act(() => {+ vi.advanceTimersByTime(12_000);+ });+ expect(live.textContent).toMatch(/1[0-9]s|12s/);+ // The rail marks the whole block as running.+ expect(screen.getByTestId("agent-turn-rail").className).toContain("agent-rail-live");+ // A running turn shows no receipt yet.+ expect(screen.queryByTestId("agent-turn-footer")).toBeNull();+ } finally {+ vi.useRealTimers();+ }+ });++ it("names tools the way the agent's log does and closes with time and tokens", () => {+ 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" }),+ ev("tool_call", { turn_id: "t9", call_id: "c1", name: "PowerShell", input: { command: "Get-ChildItem -Path 'C:\\Users'" } }),+ ev("tool_result", { turn_id: "t9", call_id: "c1", output: "ok", is_error: false }),+ ev("tool_call", { turn_id: "t9", call_id: "c2", name: "mcp__github__create_issue", input: { title: "Bug" } }),+ ev("tool_result", { turn_id: "t9", call_id: "c2", output: "#12", is_error: false }),+ ev("reasoning", { turn_id: "t9", text: "", duration_ms: 8585 }),+ ev("assistant_text", { turn_id: "t9", message_id: "m1", text: "Done." }),+ ev("turn_finished", { turn_id: "t9", status: "done", duration_ms: 12_000, usage: { input_tokens: 2, output_tokens: 219 }, cost_usd: 0.8483 }),+ ]);+ useAgentChatStore.setState({ activeSessionId: "s9", timeline });+ render(<ChatStage />);++ const tools = screen.getAllByTestId("agent-tool");+ expect(tools[0].getAttribute("data-tool")).toBe("PowerShell");+ 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 footer = screen.getByTestId("agent-turn-footer");+ expect(footer.textContent).toContain("12s");+ expect(footer.textContent).toContain("219");+ expect(footer.textContent).toContain("$0.8483");+ });});diff --git a/jarvis/ui/web/frontend/src/index.css b/jarvis/ui/web/frontend/src/index.cssindex 7ed222b37e..1f9af2f3f3 100644--- a/jarvis/ui/web/frontend/src/index.css+++ b/jarvis/ui/web/frontend/src/index.css@@ -1571,6 +1571,69 @@}}+ /* ===========================================================+ Agent chat — the live "it is working" glyph.+ A slow-turning asterisk that breathes with the accent colour,+ the way the Claude CLI marks a running turn. Under reduced+ motion it stands still and simply stays accent-coloured, which+ still reads as "in progress" beside the ticking timer.+ =========================================================== */+ @keyframes agent-glyph-spin {+ 0% {+ transform: rotate(0deg);+ }+ 100% {+ transform: rotate(360deg);+ }+ }+ @keyframes agent-glyph-breathe {+ 0%,+ 100% {+ opacity: 0.55;+ }+ 50% {+ opacity: 1;+ }+ }+ .agent-glyph {+ animation:+ agent-glyph-spin 3.6s linear infinite,+ agent-glyph-breathe 1.9s ease-in-out infinite;+ transform-origin: 50% 50%;+ }+ /* The row a running turn owns: a hairline rail that glows along the+ accent while it works, so the whole block reads as one live unit. */+ @keyframes agent-rail-travel {+ 0% {+ background-position: 50% 200%;+ }+ 100% {+ background-position: 50% -200%;+ }+ }+ .agent-rail-live {+ background: linear-gradient(+ 180deg,+ hsl(var(--border)) 0%,+ hsl(var(--border)) 30%,+ hsl(var(--primary)) 50%,+ hsl(var(--border)) 70%,+ hsl(var(--border)) 100%+ );+ background-size: 100% 200%;+ animation: agent-rail-travel 2.8s linear infinite;+ }+ @media (prefers-reduced-motion: reduce) {+ .agent-glyph {+ animation: none;+ opacity: 0.9;+ }+ .agent-rail-live {+ animation: none;+ background: hsl(var(--primary) / 0.5);+ }+ }+/* Soft float animation for the hero orb */@keyframes jarvis-float {0%,diff --git a/tests/unit/agent_chat/test_agent_chat_core.py b/tests/unit/agent_chat/test_agent_chat_core.pyindex a3ed581775..a7989df363 100644--- a/tests/unit/agent_chat/test_agent_chat_core.py+++ b/tests/unit/agent_chat/test_agent_chat_core.py@@ -318,3 +318,129 @@ def test_codex_stream_translation_maps_items_to_tools():assert st.vendor_session == "th-9"assert st.usage == {"input_tokens": 10, "output_tokens": 4}assert st.emitted_text+++def test_claude_redacted_thinking_is_announced_and_tokens_count_live():+ """Claude Code redacts thinking: the UI still learns WHEN it thinks and how many tokens flow."""+ st = _ClaudeState(turn_id="t")+ lines = [+ {"type": "stream_event", "event": {"type": "message_start", "message": {"id": "m1"}}},+ {+ "type": "stream_event",+ "event": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {"type": "thinking", "thinking": ""},+ },+ },+ # Redacted: the finished block carries no text, only that it happened.+ {+ "type": "assistant",+ "message": {+ "id": "m1",+ "content": [{"type": "thinking", "thinking": ""}],+ "usage": {"input_tokens": 3, "output_tokens": 40},+ },+ },+ {+ "type": "assistant",+ "message": {+ "id": "m1",+ "content": [{"type": "text", "text": "done"}],+ "usage": {"input_tokens": 3, "output_tokens": 55},+ },+ },+ {+ "type": "stream_event",+ "event": {"type": "message_start", "message": {"id": "m2"}},+ },+ {+ "type": "assistant",+ "message": {+ "id": "m2",+ "content": [{"type": "text", "text": "more"}],+ "usage": {"input_tokens": 1, "output_tokens": 10},+ },+ },+ ]+ events = [ev for obj in lines for ev in translate_claude_line(obj, st)]+ kinds = [ev["kind"] for ev in events]+ assert kinds[:3] == ["reasoning_started", "usage_delta", "reasoning"]+ # The same message re-reporting its usage replaces, a new message adds.+ usage = [ev["payload"]["usage"] for ev in events if ev["kind"] == "usage_delta"]+ assert usage[0] == {"input_tokens": 3, "output_tokens": 40}+ assert usage[1] == {"input_tokens": 3, "output_tokens": 55}+ assert usage[-1] == {"input_tokens": 4, "output_tokens": 65}+ reasoning = next(ev for ev in events if ev["kind"] == "reasoning")+ assert reasoning["payload"]["text"] == ""+ assert reasoning["payload"]["duration_ms"] is not None+++def test_claude_live_usage_counts_cache_and_never_walks_back():+ """The real CLI shape: the cache carries the turn, output starts as a placeholder.++ A warm session reports two new input tokens beside fifty thousand cached+ ones, and ``output_tokens: 1`` until the ``result`` line lands. Counting+ only the two uncached fields made a 50k-token turn read as "10 tokens"+ (BUG-173).+ """+ st = _ClaudeState(turn_id="t")+ lines = [+ {+ "type": "assistant",+ "message": {+ "id": "m1",+ "content": [{"type": "text", "text": "hi"}],+ "usage": {+ "input_tokens": 2,+ "cache_creation_input_tokens": 30420,+ "cache_read_input_tokens": 21355,+ "output_tokens": 1,+ },+ },+ },+ # The same message reported again with the true output count.+ {+ "type": "assistant",+ "message": {+ "id": "m1",+ "content": [{"type": "text", "text": "hi"}],+ "usage": {+ "input_tokens": 2,+ "cache_creation_input_tokens": 30420,+ "cache_read_input_tokens": 21355,+ "output_tokens": 412,+ },+ },+ },+ # …and once more as the placeholder: it must not undo the real count.+ {+ "type": "assistant",+ "message": {+ "id": "m1",+ "content": [{"type": "text", "text": "hi"}],+ "usage": {"input_tokens": 2, "output_tokens": 1},+ },+ },+ ]+ events = [ev for obj in lines for ev in translate_claude_line(obj, st)]+ usage = [ev["payload"]["usage"] for ev in events if ev["kind"] == "usage_delta"]+ assert usage[0] == {+ "input_tokens": 2,+ "cache_creation_input_tokens": 30420,+ "cache_read_input_tokens": 21355,+ "output_tokens": 1,+ }+ assert usage[-1]["output_tokens"] == 412+ assert usage[-1]["cache_read_input_tokens"] == 21355+ assert usage[-1]["cache_creation_input_tokens"] == 30420+++def test_codex_reasoning_start_is_announced():+ st = _CodexState(turn_id="t")+ lines = [+ {"type": "item.started", "item": {"id": "r1", "type": "reasoning"}},+ {"type": "item.completed", "item": {"id": "r1", "type": "reasoning", "text": "plan"}},+ ]+ kinds = [ev["kind"] for obj in lines for ev in translate_codex_line(obj, st)]+ assert kinds == ["reasoning_started", "reasoning"]