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(agents): live activity line and work inspector for agent chats (#897)
Ruben Lütke5d6e1ff8fd51
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/MessengerTurn.tsx b/dodaios/ui/web/frontend/src/components/agentchat/MessengerTurn.tsxindex 82506b9df8..74e7f0c6ba 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/MessengerTurn.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/MessengerTurn.tsx@@ -5,8 +5,11 @@ import { CredentialCard } from "./CredentialCard";import { QuestionCard } from "./QuestionCard";import type { ApprovalDecision } from "@/lib/agentChatApi";import type { TurnItem } from "./reduce";-import { actionNoticeOf, presenceOf, type ActionNotice } from "./messengerPresence";-import { BotStage, useDoneFlourish, useTypingPresence } from "./botStage/BotStage";+import { actionNoticeOf, type ActionNotice } from "./messengerPresence";+import { BotStage, useDoneFlourish } from "./botStage/BotStage";+import { ActivityLine } from "./activity/ActivityLine";+import type { NameOf } from "./activity/activityModel";+import { WorkDisclosure } from "./activity/WorkDisclosure";import { ApprovalPrompt, PROSE, THREAD_MEDIA } from "@/components/agentic/threads/ThreadTimeline";import { SubagentCard } from "@/components/agentic/threads/ThreadSubagents";import { isSubagentCall } from "@/components/agentic/threads/subagents";@@ -19,11 +22,13 @@ import { turnErrorText } from "./turnError";* are grey bubbles; what it changed for the person (a routine, a rule, a* saved skill) is a quiet centred line between them; while it works, its* own face plays a little scene of what it is doing on a stage below- * (BotStage) and hops once when the turn is done. No reasoning and no work- * log: the agent's own messages say what is happening, what is done and- * what comes next.+ * (BotStage) with one paced phrase for the step it is on (ActivityLine),+ * and hops once when the turn is done. No reasoning and no work log in the+ * conversation: the agent's own messages say what is happening, and one+ * quiet line under the turn (WorkDisclosure) opens the whole trace in the+ * work inspector.*/-export const MessengerTurn = memo(function MessengerTurn({ turn, avatar, color, onDecide, memoryLinks }: {+export const MessengerTurn = memo(function MessengerTurn({ turn, avatar, color, onDecide, memoryLinks, nameOf, peerFace, onShowWork, workOpen = false }: {turn: TurnItem;/** The agent's face at 30 px; it plays the scenes. */avatar: ReactNode;@@ -32,13 +37,21 @@ export const MessengerTurn = memo(function MessengerTurn({ turn, avatar, color,onDecide: (approvalId: string, decision: ApprovalDecision) => void | Promise<void>;/** Memory receipts posted after the turn: each a "Noted" quill line that opens the file. */memoryLinks?: MemoryLink[];+ /** A teammate's roster id or name → the name the activity line says. */+ nameOf?: NameOf;+ /** A teammate's face beside "Writing to …". */+ peerFace?: (peer: string) => ReactNode;+ /** Opens this turn's work in the inspector; without it the turn shows no "show work" line. */+ onShowWork?: () => void;+ /** The inspector shows this turn right now. */+ workOpen?: boolean;}) {const t = useT();const textLength = useMemo(() => turn.blocks.reduce((n, block) => n + (block.kind === "text" ? block.text.length : 0), 0), [turn.blocks]);- const presence = useTypingPresence(presenceOf(turn), textLength);const hasText = textLength > 0 && turn.blocks.some((block) => block.kind === "text" && block.text.trim());const flourish = useDoneFlourish(turn.status === "running", turn.status === "done");- const stage = presence ?? (flourish ? "done" : null);+ const running = turn.status === "running";+ const work = onShowWork ? <WorkDisclosure turn={turn} open={workOpen} onOpen={onShowWork} /> : null;let noteIndex = 0;return <div className="flex min-w-0 flex-col gap-1.5" data-testid="messenger-turn" data-status={turn.status}>{turn.blocks.map((block) => {@@ -57,7 +70,12 @@ export const MessengerTurn = memo(function MessengerTurn({ turn, avatar, color,return <ActionLine key={block.callId} notice={notice} link={link} />;})}{memoryLinks?.slice(noteIndex).map((link) => <ActionLine key={`memory:${link.key}`} notice={NOTED} link={link} />)}- {stage && <BotStage presence={stage} seed={turn.id} avatar={avatar} color={color} />}+ {/* While it works: the face and one paced phrase for the step it is on,+ with the live work one click away. Once done: a short flourish. */}+ {running ? <div className="flex min-w-0 flex-wrap items-center gap-x-2">+ <ActivityLine turn={turn} avatar={avatar} color={color} nameOf={nameOf} peerFace={peerFace} />+ {work}+ </div> : flourish ? <BotStage presence="done" seed={turn.id} avatar={avatar} color={color} /> : null}{turn.status === "error" && (<p role="alert" className="mx-auto flex max-w-[85%] items-center gap-1.5 py-1 text-center text-xs text-destructive"><CircleAlert aria-hidden className="h-3.5 w-3.5 shrink-0" />@@ -66,6 +84,7 @@ export const MessengerTurn = memo(function MessengerTurn({ turn, avatar, color,)}{turn.status === "cancelled" && <SystemLine>{t("thread_turn.stopped")}</SystemLine>}{turn.status === "done" && !hasText && !flourish && <SystemLine>{t("thread_turn.no_answer")}</SystemLine>}+ {!running ? work : null}</div>;});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/TraceTimeline.tsx b/dodaios/ui/web/frontend/src/components/agentchat/TraceTimeline.tsxindex 76dd1646a0..8d4d518c23 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/TraceTimeline.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/TraceTimeline.tsx@@ -170,10 +170,16 @@ function ActivityView({ entry, renderers }: { entry: ActivityEntry; renderers: T<CallLine call={current ?? entry.calls[0]} renderers={renderers} /></div>;}+ // A stretch that edited files says by how much, the way a single edit does.+ const added = entry.calls.reduce((n, call) => n + call.added, 0);+ const removed = entry.calls.reduce((n, call) => n + call.removed, 0);return <div className="min-w-0" data-trace-entry="activity"><button type="button" className={lineButton} aria-expanded={open} onClick={() => setOpen(!open)}><StretchMark calls={entry.calls} /><span className="min-w-0 truncate">{entry.summary}</span>+ {added || removed ? <span className="shrink-0 font-mono text-xs tabular-nums" data-trace-diffstat>+ <span className="diff-count-add">+{added}</span>{" "}<span className="diff-count-del">−{removed}</span>+ </span> : null}<Chevron open={open} /></button>{open ? <div className="mb-1 ml-[7px] min-w-0 border-l border-border pl-4">diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/ActivityLine.tsx b/dodaios/ui/web/frontend/src/components/agentchat/activity/ActivityLine.tsxnew file mode 100644index 0000000000..64cc1d9d66--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/ActivityLine.tsx@@ -0,0 +1,96 @@+import { memo, useEffect, useMemo, useRef, type ReactNode } from "react";+import { fill, useT } from "@/i18n";+import { BotStage, useTypingPresence } from "../botStage/BotStage";+import type { TurnItem } from "../reduce";+import { ToolChoiceIcon } from "../ToolChoiceChips";+import { toolIdentityStyle } from "../toolIdentity";+import type { ToolChoice } from "../toolChoices";+import { activityOf, activityPhrase, presenceForFamily, type Activity, type NameOf } from "./activityModel";+import { usePacedActivity } from "./usePacedActivity";+import "./runView.css";++/** The line shows how long the agent has been at it only past this. */+export const TIMER_AFTER_MS = 60_000;++/**+ * The one live line under a running turn: the agent's face playing what it+ * does, and a short phrase for the step it is on ("Editing app.ts",+ * "Working in Gmail"), with a slow light sweep while it works. A turn that+ * runs longer than a minute adds how long, in whole minutes, so short steps+ * never get a ticking counter.+ *+ * The phrase is paced (usePacedActivity): it changes at most once per+ * 800 ms and keeps its words while the step stays the same. The stage does+ * not announce itself; the transcript's own announcer says when the agent+ * starts, replies, finishes, stops or asks.+ */+export const ActivityLine = memo(function ActivityLine({ turn, avatar, color, nameOf, peerFace }: {+ turn: TurnItem;+ avatar: ReactNode;+ color: string;+ nameOf?: NameOf;+ /** The face of a teammate the agent writes to, shown beside the phrase. */+ peerFace?: (peer: string) => ReactNode;+}) {+ const t = useT();+ const raw = useMemo(() => activityOf(turn, nameOf), [turn, nameOf]);+ const textLength = useMemo(() => turn.blocks.reduce((n, block) => n + (block.kind === "text" ? block.text.length : 0), 0), [turn.blocks]);+ // Words that stopped arriving are thinking again, not typing.+ const typing = useTypingPresence(raw?.family === "composing" ? "typing" : null, textLength);+ const current = useMemo<Activity | null>(() => raw && raw.family === "composing" && typing !== "typing"+ ? { ...raw, family: "thinking", phrase: "thinking" }+ : raw, [raw, typing]);+ const shown = usePacedActivity(current);+ if (!shown) return null;+ const phrase = activityPhrase(shown, t);+ const words = <span className="run-activity-words">+ {shown.family === "connecting" && shown.brand ? <BrandDot brand={shown.brand} label={shown.target} /> : null}+ {shown.family === "messaging" && shown.peer && peerFace ? <span aria-hidden className="run-activity-peer">{peerFace(shown.peer)}</span> : null}+ <span className="run-activity-phrase" data-testid="activity-phrase" data-family={shown.family}>{phrase}</span>+ <ElapsedSince since={turn.startedMs} />+ </span>;+ return <div className="run-activity" data-testid="activity-line" data-family={shown.family}>+ <BotStage presence={presenceForFamily(shown.family)} seed={turn.id} avatar={avatar} color={color}+ words={words} wordsId={shown.family} announce={false} />+ </div>;+});++function BrandDot({ brand, label }: { brand: string; label: string }) {+ const row: ToolChoice = {+ id: `plugin:${brand}`, label, brand, group: "", skill: "", category: "plugins",+ description: "", available: true, tool_names: [],+ };+ return <span aria-hidden className="tool-identity run-activity-brand" style={toolIdentityStyle(row)}>+ <ToolChoiceIcon row={row} size={14} />+ </span>;+}++/** "3 min", "1 h 05 min": whole minutes, so the line never ticks every second. */+export function formatLongElapsed(ms: number, t: (key: string) => string): string {+ const minutes = Math.floor(Math.max(0, ms) / 60_000);+ if (minutes < 60) return fill(t("run_view.timer.min"), { count: minutes });+ return fill(t("run_view.timer.hour"), { hours: Math.floor(minutes / 60), minutes: String(minutes % 60).padStart(2, "0") });+}++/**+ * How long the turn has run, hidden for its first minute. It writes its own+ * text, so the line around it never re-renders to tick.+ */+function ElapsedSince({ since }: { since: number }) {+ const t = useT();+ const ref = useRef<HTMLSpanElement | null>(null);+ useEffect(() => {+ const paint = () => {+ const el = ref.current;+ if (!el) return;+ const elapsed = Date.now() - since;+ const show = since > 0 && elapsed >= TIMER_AFTER_MS;+ el.hidden = !show;+ if (show) el.textContent = `· ${formatLongElapsed(elapsed, t)}`;+ };+ paint();+ const timer = window.setInterval(paint, 5_000);+ return () => window.clearInterval(timer);+ }, [since, t]);+ return <span ref={ref} hidden className="run-activity-timer" data-testid="activity-timer" aria-hidden />;+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/MessengerRunView.test.tsx b/dodaios/ui/web/frontend/src/components/agentchat/activity/MessengerRunView.test.tsxnew file mode 100644index 0000000000..fbc68ebb71--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/MessengerRunView.test.tsx@@ -0,0 +1,95 @@+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { MessengerTurn } from "../MessengerTurn";+import type { ReasoningBlock, TextBlock, ToolBlock, TurnBlock, TurnItem } from "../reduce";+import { TIMER_AFTER_MS } from "./ActivityLine";++afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++function turn(blocks: TurnBlock[], status: TurnItem["status"] = "running", startedMs = Date.now()): TurnItem {+ return {+ type: "turn", id: "t1", provider: "p", model: "", effort: "", runner: "api", status, blocks,+ startedMs, durationMs: status === "running" ? null : 125_000, usage: null, liveUsage: null, costUsd: null, error: null,+ };+}+const text = (value: string, id = "x1"): TextBlock => ({ kind: "text", id, text: value });+const thought = (value: string): ReasoningBlock => ({ kind: "reasoning", id: "r1", text: value, durationMs: 800, live: false, startedMs: 1 });+function call(name: string, input: unknown, output: string | null = null, extra: Partial<ToolBlock> = {}): ToolBlock {+ return { kind: "tool", callId: `c-${name}`, name, input, output, isError: false, durationMs: null, approval: null, startedMs: 1, ...extra };+}++function draw(item: TurnItem, extra: Partial<Parameters<typeof MessengerTurn>[0]> = {}) {+ return render(<MessengerTurn turn={item} avatar={<span data-testid="face" />} color="#7ab6ef" onDecide={() => undefined} {...extra} />);+}++describe("activity line in the chat", () => {+ it("says what the running step is, in words", () => {+ draw(turn([call("Edit", { file_path: "src/app.ts", old_string: "a", new_string: "b" })]));+ expect(screen.getByTestId("activity-phrase").textContent).toBe("Editing app.ts");+ expect(screen.getByTestId("messenger-presence").dataset.presence).toBe("writing");+ // The stage does not announce each step; the transcript's announcer does.+ expect(screen.getByTestId("messenger-presence").getAttribute("role")).toBeNull();+ });++ it("names the teammate an agent writes to, with its face", () => {+ draw(turn([call("society_message_agent", { target: "a7", text: "hi" })]), {+ nameOf: (id) => (id === "a7" ? "Scout" : id),+ peerFace: () => <span data-testid="peer-face" />,+ });+ expect(screen.getByTestId("activity-phrase").textContent).toBe("Writing to Scout");+ expect(screen.getByTestId("peer-face")).toBeTruthy();+ });++ it("shows the time only after a minute", () => {+ vi.useFakeTimers();+ vi.setSystemTime(1_000_000);+ draw(turn([], "running", 1_000_000));+ const timer = screen.getByTestId("activity-timer");+ expect(timer.hidden).toBe(true);+ act(() => { vi.advanceTimersByTime(TIMER_AFTER_MS + 5_000); });+ expect(timer.hidden).toBe(false);+ expect(timer.textContent).toBe("· 1 min");+ });++ it("keeps reasoning and tool rows out of the conversation", () => {+ draw(turn([thought("secret plan"), call("Bash", { command: "ls" }, "a.txt"), text("Here you go.")], "done"));+ expect(screen.queryByText("secret plan")).toBeNull();+ expect(screen.queryByText("a.txt")).toBeNull();+ expect(screen.queryByText(/ls/)).toBeNull();+ expect(screen.getAllByTestId("agent-message-bubble")).toHaveLength(1);+ });+});++describe("show work", () => {+ it("sums the turn up in one line that opens the inspector", () => {+ const open = vi.fn();+ draw(turn([+ thought("x"),+ call("Edit", { file_path: "a.ts", old_string: "a", new_string: "b" }, "ok"),+ call("Read", { file_path: "b.ts" }, "ok"),+ text("Done."),+ ], "done"), { onShowWork: open });+ const line = screen.getByTestId("work-disclosure");+ expect(line.textContent).toContain("Worked for 2m 05s");+ expect(line.textContent).toContain("2 steps");+ expect(line.textContent).toContain("1 file");+ expect(line.textContent).toContain("+1");+ expect(line.textContent).toContain("−1");+ fireEvent.click(line);+ expect(open).toHaveBeenCalledTimes(1);+ });++ it("a plain reply has no work line", () => {+ draw(turn([text("Hello.")], "done"), { onShowWork: () => undefined });+ expect(screen.queryByTestId("work-disclosure")).toBeNull();+ });++ it("sits beside the activity line while the turn runs", () => {+ draw(turn([call("Read", { file_path: "b.ts" })]), { onShowWork: () => undefined });+ expect(screen.getByTestId("work-disclosure").textContent).toContain("Working");+ expect(screen.getByTestId("activity-line")).toBeTruthy();+ });+});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/TranscriptAids.tsx b/dodaios/ui/web/frontend/src/components/agentchat/activity/TranscriptAids.tsxnew file mode 100644index 0000000000..a41833b18a--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/TranscriptAids.tsx@@ -0,0 +1,169 @@+import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { ArrowDown, X } from "lucide-react";+import { fill, useT } from "@/i18n";+import type { TimelineItem } from "../reduce";+import { plural } from "../traceEntries";+import { localeForUiLanguage } from "@/components/runs/format";+import { announcementFor, openQuestionText, runSnapshot, type RunSnapshot } from "./runAnnouncer";+import { stampLabel } from "./transcriptTime";+import "./runView.css";++/**+ * The small aids a long transcript needs: time stamps that mark a pause, a+ * "N new" pill for a reader who scrolled up, rows that grow smoothly, and a+ * quiet live region that tells a screen reader when the agent starts,+ * replies, finishes, stops or asks.+ */++/** A pause in the conversation, as a hairline with the time in the middle. */+export function TranscriptStamp({ ms }: { ms: number }) {+ const t = useT();+ // The UI language, read through the dictionary like every trace line.+ const locale = localeForUiLanguage(t("trace_report.locale"));+ const label = stampLabel(ms, Date.now(), locale, t);+ return <p className="run-stamp" data-testid="transcript-stamp">+ <time dateTime={new Date(ms).toISOString()}>{label}</time>+ </p>;+}++/** Items that count as "new" for a reader who scrolled away. */+function countable(item: TimelineItem): boolean {+ return item.type === "turn" || item.type === "user" || item.type === "internal" || item.type === "notice";+}++/** How many countable items are not in `seen`. */+export function countUnseen(items: readonly TimelineItem[], seen: ReadonlySet<string>): number {+ let n = 0;+ for (const item of items) if (countable(item) && !seen.has(item.id)) n += 1;+ return n;+}++/**+ * Counts what arrived while the reader was away from the end. Everything on+ * screen while they sit at the end is seen; dismissing the pill marks the+ * rest seen too.+ */+export function useUnseen(items: readonly TimelineItem[], atEnd: boolean): { count: number; dismiss: () => void } {+ const seen = useRef<Set<string>>(new Set());+ const [, bump] = useState(0);+ if (atEnd) {+ for (const item of items) seen.current.add(item.id);+ }+ return {+ count: atEnd ? 0 : countUnseen(items, seen.current),+ dismiss: () => {+ for (const item of items) seen.current.add(item.id);+ bump((n) => n + 1);+ },+ };+}++/** True while the scroller sits more than `px` above its end. */+export function useFarFromEnd(el: HTMLElement | null, px = 80): boolean {+ const [far, setFar] = useState(false);+ useEffect(() => {+ if (!el) return;+ const read = () => setFar(el.scrollHeight - el.scrollTop - el.clientHeight > px);+ read();+ el.addEventListener("scroll", read, { passive: true });+ return () => el.removeEventListener("scroll", read);+ }, [el, px]);+ return far;+}++/** "3 new messages ↓" with a dismiss ×, floating over the conversation's end. */+export function CatchUpPill({ count, onJump, onDismiss }: { count: number; onJump: () => void; onDismiss: () => void }) {+ const t = useT();+ const lang = t("trace_report.locale");+ const label = fill(t(`run_view.pill.new_${plural(lang, count)}`), { count });+ return <div className="run-pill" data-testid="transcript-new-pill">+ <button type="button" className="run-pill-main" onClick={onJump}>+ <span>{label}</span>+ <ArrowDown aria-hidden className="h-3.5 w-3.5" />+ </button>+ <button type="button" className="run-pill-close" onClick={onDismiss} aria-label={t("run_view.pill.dismiss")} title={t("run_view.pill.dismiss")}>+ <X aria-hidden className="h-3 w-3" />+ </button>+ </div>;+}++function prefersReducedMotion(): boolean {+ return typeof window !== "undefined" && typeof window.matchMedia === "function"+ && window.matchMedia("(prefers-reduced-motion: reduce)").matches;+}++/** How long a row takes to settle into its new height. */+export const SETTLE_MS = 200;++/**+ * A row that glides to its new height instead of jumping, while `active`+ * (the live turn). The inner box is measured; the outer box animates from+ * the old height to the new one and lets go when it arrives. Off with+ * reduced motion and where there is no ResizeObserver.+ */+export function SettleBox({ active, children, className }: { active: boolean; children: ReactNode; className?: string }) {+ const outer = useRef<HTMLDivElement | null>(null);+ const inner = useRef<HTMLDivElement | null>(null);+ const last = useRef(0);+ useLayoutEffect(() => {+ const box = outer.current;+ const content = inner.current;+ if (!active || !box || !content || typeof ResizeObserver === "undefined" || prefersReducedMotion()) return;+ last.current = content.offsetHeight;+ let timer = 0;+ const ro = new ResizeObserver(() => {+ const next = content.offsetHeight;+ const from = box.getBoundingClientRect().height || last.current;+ last.current = next;+ if (next <= from + 1) {+ box.style.height = "";+ box.style.overflow = "";+ return;+ }+ box.style.transition = "none";+ box.style.height = `${from}px`;+ box.style.overflow = "clip";+ void box.offsetHeight;+ box.style.transition = `height ${SETTLE_MS}ms cubic-bezier(0.2, 0, 0, 1)`;+ box.style.height = `${next}px`;+ window.clearTimeout(timer);+ timer = window.setTimeout(() => {+ box.style.transition = "";+ box.style.height = "";+ box.style.overflow = "";+ }, SETTLE_MS + 20);+ });+ ro.observe(content);+ return () => {+ ro.disconnect();+ window.clearTimeout(timer);+ box.style.transition = "";+ box.style.height = "";+ box.style.overflow = "";+ };+ }, [active]);+ return <div ref={outer} className={className}><div ref={inner} className="flex flex-col gap-2">{children}</div></div>;+}++/**+ * The live region: one sentence per lifecycle change of the newest turn.+ * The first snapshot after mounting is only remembered, so opening a chat+ * never reads out old news.+ */+export function RunAnnouncer({ items, agentName }: { items: readonly TimelineItem[]; agentName: string }) {+ const t = useT();+ const snapshot = useMemo(() => runSnapshot(items), [items]);+ const question = useMemo(() => openQuestionText(items, snapshot), [items, snapshot]);+ const prev = useRef<RunSnapshot | null | undefined>(undefined);+ const [message, setMessage] = useState("");+ useEffect(() => {+ if (prev.current === undefined) {+ prev.current = snapshot;+ return;+ }+ const said = announcementFor(prev.current, snapshot, question);+ prev.current = snapshot;+ if (said) setMessage(fill(t(said.key), { agent: agentName, question: said.detail }));+ }, [snapshot, question, agentName, t]);+ return <p className="sr-only" role="status" aria-live="polite" data-testid="run-announcer">{message}</p>;+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/WorkDisclosure.tsx b/dodaios/ui/web/frontend/src/components/agentchat/activity/WorkDisclosure.tsxnew file mode 100644index 0000000000..492fa3aae7--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/WorkDisclosure.tsx@@ -0,0 +1,51 @@+import { memo, useMemo } from "react";+import { ChevronRight, ListTree } from "lucide-react";+import { fill, useT } from "@/i18n";+import type { TurnItem } from "../reduce";+import { plural, traceDuration } from "../traceEntries";+import { hasWork, workHeadKey, workSummary } from "./workSummary";+import "./runView.css";++/**+ * "Worked for 2m 05s · 14 steps · 3 files +40 −12": one quiet line under a+ * turn that did any work. The conversation stays clean; this line opens the+ * work inspector, where every thought and call of the turn can be read.+ */+export const WorkDisclosure = memo(function WorkDisclosure({ turn, open, onOpen }: {+ turn: TurnItem;+ /** The inspector shows this turn right now. */+ open: boolean;+ onOpen: () => void;+}) {+ const t = useT();+ const lang = t("trace_report.locale");+ const summary = useMemo(() => workSummary(turn.blocks), [turn.blocks]);+ if (!hasWork(summary)) return null;+ const parts: string[] = [];+ const head = fill(t(workHeadKey(turn)), { duration: traceDuration(turn.durationMs ?? 0) });+ const steps = summary.steps > 0 ? fill(t(`run_view.work.steps_${plural(lang, summary.steps)}`), { count: summary.steps }) : "";+ if (steps) parts.push(steps);+ if (summary.helpers > 0) parts.push(fill(t(`run_view.work.helpers_${plural(lang, summary.helpers)}`), { count: summary.helpers }));+ const files = summary.files > 0 ? fill(t(`run_view.work.files_${plural(lang, summary.files)}`), { count: summary.files }) : "";+ const showDuration = turn.status !== "running" && (turn.durationMs ?? 0) > 0;+ const lead = [showDuration || turn.status === "running" ? head : "", ...parts].filter(Boolean);+ // A turn that only thought, with no measured time, still says what the line does.+ if (!lead.length && !files) lead.push(t("run_view.work.open"));+ const label = [...lead, files].filter(Boolean).join(" · ");+ return <button type="button" className="run-work" onClick={onOpen} aria-expanded={open}+ aria-label={`${label}. ${t("run_view.work.open")}`} title={t("run_view.work.open")}+ data-testid="work-disclosure" data-turn={turn.id}>+ <ListTree aria-hidden className="h-3.5 w-3.5 shrink-0" strokeWidth={1.75} />+ <span className="min-w-0 truncate">+ {lead.map((part, i) => <span key={i}>+ {i > 0 ? <span className="run-work-sep" aria-hidden> · </span> : null}{part}+ </span>)}+ {files ? <span>+ {lead.length ? <span className="run-work-sep" aria-hidden> · </span> : null}{files}+ {summary.added > 0 ? <span className="run-diff-add tabular-nums"> +{summary.added}</span> : null}+ {summary.removed > 0 ? <span className="run-diff-del tabular-nums"> −{summary.removed}</span> : null}+ </span> : null}+ </span>+ <ChevronRight aria-hidden className="run-work-chev h-3 w-3 shrink-0" />+ </button>;+});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/activityModel.test.ts b/dodaios/ui/web/frontend/src/components/agentchat/activity/activityModel.test.tsnew file mode 100644index 0000000000..9009e09f63--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/activityModel.test.ts@@ -0,0 +1,148 @@+import { describe, expect, it } from "vitest";+import en from "@/i18n/locales/en.json";+import type { ReasoningBlock, TextBlock, ToolBlock, TurnBlock, TurnItem } from "../reduce";+import {+ activityOf, activityPhrase, capPhrase, PHRASE_MAX, phraseKey, presenceForFamily, sameStep, serviceName, toolActivity,+ type Activity, type ActivityFamily,+} from "./activityModel";++/** The English catalogue as `t`, so the phrases are the real ones. */+function t(key: string): string {+ let at: unknown = en;+ for (const part of key.split(".")) at = (at as Record<string, unknown>)?.[part];+ return typeof at === "string" ? at : key;+}++function turn(blocks: TurnBlock[], status: TurnItem["status"] = "running"): TurnItem {+ return {+ type: "turn", id: "t1", provider: "p", model: "", effort: "", runner: "api", status, blocks,+ startedMs: 1, durationMs: null, usage: null, liveUsage: null, costUsd: null, error: null,+ };+}+const text = (value: string, id = "x1"): TextBlock => ({ kind: "text", id, text: value });+const thought = (id = "r1"): ReasoningBlock => ({ kind: "reasoning", id, text: "…", durationMs: null, live: true, startedMs: 1 });+function call(name: string, input: unknown = {}, output: string | null = null, extra: Partial<ToolBlock> = {}): ToolBlock {+ return { kind: "tool", callId: `c-${name}`, name, input, output, isError: false, durationMs: null, approval: null, startedMs: 1, ...extra };+}++const phrase = (block: ToolBlock, nameOf?: (v: string) => string) => activityPhrase(toolActivity(block, nameOf), t);++describe("toolActivity: every family has its own words", () => {+ const cases: [ToolBlock, ActivityFamily, string][] = [+ [call("WebSearch", { query: "rust async traits" }), "searching", "Looking up “rust async traits”"],+ [call("web_search"), "searching", "Looking it up online"],+ [call("Grep", { pattern: "useStickToBottom" }), "searching", "Searching for “useStickToBottom”"],+ [call("Read", { file_path: "C:/repo/src/app.ts" }), "reading", "Opening app.ts"],+ [call("Read", { file_path: "shot.png" }), "reading", "Looking at an image"],+ [call("WebFetch", { url: "https://www.example.org/docs" }), "reading", "Reading a page on example.org"],+ [call("Edit", { file_path: "/repo/src/store.ts", old_string: "a", new_string: "b" }), "writing", "Editing store.ts"],+ [call("Write", { file_path: "notes.md", content: "x" }), "writing", "Writing notes.md"],+ [call("Bash", { command: "cd \"C:/repo\" && npm test" }), "running", "Running npm"],+ [call("shell", {}), "running", "At the terminal"],+ [call("browser_navigate", { url: "https://github.com/x" }), "browsing", "On github.com"],+ [call("mcp__dodaios__society_memory_recall", { query: "x" }), "recalling", "Checking its notes"],+ [call("mcp__dodaios__society_wiki_note", { title: "Plan" }), "noting", "Making a note"],+ [call("society_routines", {}), "setting_up", "Setting things up"],+ [call("unknown_tool", {}), "working", ""],+ ];+ it.each(cases)("%#: %s", (block, family, words) => {+ const activity = toolActivity(block);+ expect(activity.family).toBe(family);+ if (words) expect(activityPhrase(activity, t)).toBe(words);+ else expect(activityPhrase(activity, t)).not.toMatch(/run_view/);+ });++ it("names a connector after its service, never after its transport", () => {+ expect(phrase(call("mcp__gmail__send_email", { to: "[email protected]" }))).toBe("Working in Gmail");+ expect(phrase(call("mcp__linear-server__list_issues"))).toBe("Working in Linear");+ expect(toolActivity(call("mcp__linear-server__list_issues")).family).toBe("connecting");+ // Our own MCP server is the road; the plugin behind it is the destination.+ expect(phrase(call("mcp__dodaios__gmail_search", { q: "x" }))).toBe("Working in Gmail");+ expect(serviceName("github_mcp")).toBe("Github");+ });++ it("writes to a teammate by the name a person knows", () => {+ const block = call("mcp__dodaios__society_message_agent", { target: "a7", text: "hi" });+ expect(phrase(block, (id) => (id === "a7" ? "Scout" : id))).toBe("Writing to Scout");+ expect(toolActivity(block).peer).toBe("a7");+ expect(phrase(call("society_message_agent", {}))).toBe("Writing to a teammate");+ });++ it("the ask tool and the credential tool wait for the person", () => {+ expect(phrase(call("mcp__dodaios__society_ask_user", { questions: [] }))).toBe("Needs your answer");+ expect(toolActivity(call("AskUserQuestion")).family).toBe("waiting");+ expect(toolActivity(call("society_request_credential")).family).toBe("waiting");+ });++ it("a helper the agent starts is delegation", () => {+ expect(phrase(call("Task", { description: "Explore the auth code", prompt: "…" }))).toBe("Briefing a helper: Explore the auth code");+ expect(phrase(call("spawn_agent", {}))).toBe("A helper is on it");+ });+});++describe("activityOf", () => {+ it("thinks before anything happened and between steps", () => {+ expect(activityOf(turn([]))?.family).toBe("thinking");+ expect(activityOf(turn([thought()]))?.family).toBe("thinking");+ expect(activityOf(turn([call("Read", { file_path: "a.ts" }, "ok")]))?.family).toBe("thinking");+ });++ it("composes while words stream and names the running call", () => {+ expect(activityOf(turn([text("Checking.")]))?.family).toBe("composing");+ expect(activityOf(turn([text("x"), call("Bash", { command: "git status" })]))?.target).toBe("git");+ });++ it("a waiting card wins over every later block", () => {+ const question = call("society_ask_user", {}, null, { question: { closed: false } as ToolBlock["question"] });+ expect(activityOf(turn([question, thought("r2")]))?.phrase).toBe("waiting");+ const approval = call("Bash", { command: "rm -rf x" }, null, { approval: { approvalId: "a", summary: "", decision: null } });+ expect(activityOf(turn([approval]))?.phrase).toBe("waiting_approval");+ });++ it("question polls are plumbing, and running helpers keep the line on delegation", () => {+ const poll = call("society_ask_user", { wait_for: "q1" }, "{\"status\":\"waiting\"}");+ expect(activityOf(turn([thought(), poll]))?.family).toBe("thinking");+ const helper = call("Task", { description: "Run tests" }, "Async agent launched", {+ subagent: { status: "running", description: "Run tests" } as ToolBlock["subagent"],+ });+ expect(activityOf(turn([helper]))?.family).toBe("delegating");+ });++ it("says nothing once the turn is over", () => {+ expect(activityOf(turn([text("Done.")], "done"))).toBeNull();+ expect(activityOf(turn([], "cancelled"))).toBeNull();+ });+});++describe("phrasing", () => {+ const a = (episode: string): Activity => ({ family: "thinking", phrase: "thinking", target: "", episode, brand: "", peer: "" });++ it("keeps one variant per episode, and different episodes vary", () => {+ expect(phraseKey(a("r1"))).toBe(phraseKey(a("r1")));+ const keys = new Set(["r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8"].map((id) => phraseKey(a(id))));+ expect(keys.size).toBeGreaterThan(1);+ for (const key of keys) expect(t(key)).not.toBe(key);+ });++ it("caps at 60 characters and keeps the verb whole", () => {+ const long = toolActivity(call("Grep", { pattern: "x".repeat(200) }));+ const words = activityPhrase(long, t);+ expect(words.length).toBeLessThanOrEqual(PHRASE_MAX);+ expect(words.startsWith("Searching for “")).toBe(true);+ expect(words).toMatch(/x…”$/);+ expect(capPhrase(" a\n\n b ")).toBe("a b");+ });++ it("same family and target is the same step, whatever the episode", () => {+ const one = toolActivity(call("Read", { file_path: "a.ts" }));+ const two = { ...one, episode: "other" };+ expect(sameStep(one, two)).toBe(true);+ expect(sameStep(one, toolActivity(call("Read", { file_path: "b.ts" })))).toBe(false);+ });++ it("every family plays a scene on the face", () => {+ const families: ActivityFamily[] = ["thinking", "composing", "searching", "reading", "writing", "running", "browsing",+ "recalling", "noting", "messaging", "delegating", "connecting", "setting_up", "waiting", "working"];+ for (const family of families) expect(presenceForFamily(family)).toBeTruthy();+ });+});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/activityModel.ts b/dodaios/ui/web/frontend/src/components/agentchat/activity/activityModel.tsnew file mode 100644index 0000000000..20115ac813--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/activityModel.ts@@ -0,0 +1,328 @@+/**+ * What an agent is doing right now, as one short line.+ *+ * A running turn is a list of blocks: thoughts, words and tool calls. The+ * activity line under the conversation says what the newest of them means to+ * a person, in a phrase of a few words ("Editing app.ts", "Working in Gmail",+ * "Writing to Scout"), never a raw tool name. This module is the pure part:+ *+ * blocks → an Activity (a verb family, an optional target, an episode key)+ * Activity → the phrase, capped at PHRASE_MAX characters+ * Activity → the face's scene (BotStage presence)+ *+ * Generic families (thinking, working) have several phrasings. One is picked+ * per episode from a hash of the episode key, so the line does not flicker+ * between wordings while the same step lasts, and two steps rarely read the+ * same.+ *+ * Every runtime feeds the same event vocabulary, so this works the same for+ * our own agents, every CLI seat and the ACP runtimes. A runtime that sends+ * no stream simply shows "thinking" until its finished blocks arrive.+ */++import { fill } from "@/i18n";+import { resolveToolBrand } from "@/lib/toolBrand";+import type { Presence } from "../messengerPresence";+import { isCredentialTool, isQuestionTool, waitsOnCard, type ToolBlock, type TurnBlock, type TurnItem } from "../reduce";+import { isSubagentCall } from "@/components/agentic/threads/subagents";+import { commandBinary, ownServerTool, shortPath, withoutCd } from "../traceEntries";+import { traceAction, traceToolIdentity, traceToolName } from "../traceActivity";++/** The verb families the line speaks in. */+export type ActivityFamily =+ | "thinking"+ | "composing"+ | "searching"+ | "reading"+ | "writing"+ | "running"+ | "browsing"+ | "recalling"+ | "noting"+ | "messaging"+ | "delegating"+ | "connecting"+ | "setting_up"+ | "waiting"+ | "working";++export interface Activity {+ family: ActivityFamily;+ /**+ * The phrase key under `run_view.phrase.` without a variant suffix. Most+ * families have one or two shapes ("read_file" with a target, "read_any"+ * without one).+ */+ phrase: string;+ /** What the step is about: a file, a host, a teammate, a service. Untranslated. */+ target: string;+ /**+ * Stable while one step lasts (the call id, the thought id). The phrasing+ * variant is chosen from it, and the pacer treats a new key of the same+ * family and target as the same step.+ */+ episode: string;+ /** A connector's brand row id, for its logo; "" otherwise. */+ brand: string;+ /** The teammate an agent message goes to (roster id or name), for its face. */+ peer: string;+}++/** Lines longer than this end in an ellipsis. */+export const PHRASE_MAX = 60;++/** How many phrasings each generic family has (`thinking_0` … `thinking_3`). */+export const VARIANTS: Partial<Record<string, number>> = {+ thinking: 4,+ working: 3,+};++/** Resolves a roster id or name to the name a person sees. */+export type NameOf = (idOrName: string) => string;++const identity: NameOf = (value) => value;++function record(value: unknown): Record<string, unknown> {+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};+}++function firstString(input: Record<string, unknown>, keys: string[]): string {+ for (const key of keys) {+ const value = input[key];+ if (typeof value === "string" && value.trim()) return value.trim();+ }+ return "";+}++function hostOf(url: string): string {+ try {+ return new URL(url).hostname.replace(/^www\./, "");+ } catch {+ return "";+ }+}++/** "linear-server" → "Linear", "github_mcp" → "Github": an MCP server id as a name. */+export function serviceName(server: string): string {+ const words = server+ .replace(/^(?:mcp|plugin|cli)[-_]/i, "")+ .replace(/[-_](?:mcp|server|plugin|cli)$/i, "")+ .split(/[-_.\s]+/)+ .filter(Boolean);+ if (!words.length) return server;+ return words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");+}++function make(family: ActivityFamily, phrase: string, episode: string, extra: Partial<Activity> = {}): Activity {+ return { family, phrase, target: "", episode, brand: "", peer: "", ...extra };+}++const MEMORY_WRITE = /(wiki_?note|^remember$|memory_?(write|update|save))/;+const MEMORY_READ = /(recall|memory_?(read|search|get)|^memory$|wiki_?(recall|read|list|page))/;+const BROWSER = /(^browser|browser_|^navigate|^click|screenshot|^computer|^society_browser$)/;+const WEB_SEARCH = /(web_?search|search_?web|websearch|^google_search|^brave_search)/;+const WEB_FETCH = /^(web_?fetch|fetch_?url|fetch|read_?url|open_?url)$/;+const SHELL = /^(bash|powershell|shell|run_?shell(_command)?|exec(_command)?|run_?command|terminal|society_shell|society_sandbox)$/;+const SETUP = /(credential|routine|install|connect|plugin|connector|configure|setup|propose_change)/;+const MESSAGE = /^(society_message_agent|send_?message_?to_?agent|message_agent)$/;++/**+ * The family and phrase of one tool call. `nameOf` turns a teammate's id+ * into the name a person knows.+ */+export function toolActivity(block: ToolBlock, nameOf: NameOf = identity): Activity {+ const episode = block.callId;+ const input = record(block.input);+ if (isQuestionTool(block.name) || isCredentialTool(block.name)) return make("waiting", "waiting", episode);+ if (isSubagentCall(block)) {+ const title = block.subagent?.description || firstString(input, ["description", "title", "name"]);+ return title ? make("delegating", "delegate", episode, { target: title }) : make("delegating", "delegate_any", episode);+ }+ const traced = traceToolName(block.name);+ const own = ownServerTool(traced);+ // The app's own MCP server is the road, not the destination.+ const name = (own ?? traced).toLowerCase();+ const bare = name.split("/").pop() ?? name;++ if (MESSAGE.test(bare)) {+ const peer = firstString(input, ["target", "to", "agent", "recipient", "agent_id"]);+ return peer ? make("messaging", "message", episode, { target: nameOf(peer), peer }) : make("messaging", "message_any", episode);+ }+ if (MEMORY_WRITE.test(bare)) return make("noting", "note", episode);+ if (MEMORY_READ.test(bare)) return make("recalling", "recall", episode);+ if (WEB_SEARCH.test(bare)) {+ const query = firstString(input, ["query", "q", "search_query", "pattern"]);+ return query ? make("searching", "search_web_for", episode, { target: query }) : make("searching", "search_web", episode);+ }+ if (WEB_FETCH.test(bare)) {+ const host = hostOf(firstString(input, ["url", "uri", "href"]));+ return host ? make("reading", "read_page", episode, { target: host }) : make("reading", "read_any", episode);+ }+ if (BROWSER.test(bare)) {+ const host = hostOf(firstString(input, ["url", "uri", "href"]));+ return host ? make("browsing", "browse_site", episode, { target: host }) : make("browsing", "browse_any", episode);+ }++ const action = traceAction(own ?? traced);+ if (action === "command" || SHELL.test(bare)) {+ const raw = firstString(input, ["command", "cmd", "CommandLine", "commandLine", "script"]);+ const binary = raw ? commandBinary(withoutCd(raw.split(/\r?\n/).find((line) => line.trim()) ?? "")) : "";+ return binary ? make("running", "run_cmd", episode, { target: binary }) : make("running", "run_any", episode);+ }+ if (action === "edit" || action === "write") {+ const path = firstString(input, ["file_path", "path", "notebook_path", "filename"]);+ const file = path ? fileName(path) : "";+ if (!file) return make("writing", "write_any", episode);+ return make("writing", action === "edit" ? "edit_file" : "write_file", episode, { target: file });+ }+ if (action === "read") {+ const path = firstString(input, ["file_path", "path", "notebook_path", "filename"]);+ if (/\.(png|jpe?g|gif|webp|bmp|svg|heic|avif)$/i.test(path)) return make("reading", "view_image", episode);+ return path ? make("reading", "read_file", episode, { target: fileName(path) }) : make("reading", "read_any", episode);+ }+ if (action === "list") {+ const path = firstString(input, ["path", "directory", "dir"]);+ return path ? make("reading", "list_folder", episode, { target: shortPath(path) }) : make("reading", "read_any", episode);+ }+ if (action === "search") {+ const pattern = firstString(input, ["pattern", "query", "regex", "q"]);+ return pattern ? make("searching", "search_for", episode, { target: pattern }) : make("searching", "search_files", episode);+ }+ if (action === "memory") return make("recalling", "recall", episode);++ // A connector: an MCP server's tool, a plugin of ours, a branded service.+ if (own !== null) {+ const brand = resolveToolBrand(own);+ if (brand.logoUrl) return make("connecting", "connect", episode, { target: brand.label.split(" · ")[0], brand: brand.brandId ?? "" });+ } else {+ const view = traceToolIdentity(block);+ if (view.integration) {+ const label = view.row.brand ? view.service : serviceName(view.service || traced.split("/")[0]);+ return make("connecting", "connect", episode, { target: label, brand: view.row.brand });+ }+ }+ if (SETUP.test(bare)) return make("setting_up", "setup", episode);+ return make("working", "working", episode);+}++function fileName(path: string): string {+ return path.replace(/\\/g, "/").split("/").filter(Boolean).pop() ?? path;+}++/** The call waits on the person: an open question, a credential field, an approval. */+function waitsForPerson(block: TurnBlock): block is ToolBlock {+ return block.kind === "tool" && (waitsOnCard(block) || Boolean(block.approval && block.approval.decision === null));+}++/** Question and credential polls draw nothing: the card speaks for them. */+function isPoll(block: TurnBlock): boolean {+ return block.kind === "tool" && block.output !== null && (+ (isQuestionTool(block.name) && !block.question) || (isCredentialTool(block.name) && !block.credential)+ );+}++/**+ * What a running turn is doing now, or null once it is over. A card that+ * waits for the person wins over everything else: nothing moves until they+ * answer.+ */+export function activityOf(turn: TurnItem, nameOf: NameOf = identity): Activity | null {+ if (turn.status !== "running") return null;+ const blocks = turn.blocks;+ const waiting = blocks.find(waitsForPerson);+ if (waiting) {+ const approval = Boolean(waiting.approval && waiting.approval.decision === null) && !waiting.question && !waiting.credential;+ return make("waiting", approval ? "waiting_approval" : "waiting", `wait:${waiting.callId}`);+ }+ for (let i = blocks.length - 1; i >= 0; i--) {+ const block = blocks[i];+ if (isPoll(block)) continue;+ if (block.kind === "tool") {+ if (block.output === null) return toolActivity(block, nameOf);+ // A helper the agent started keeps working after its spawn call returned.+ const helpers = runningHelpers(blocks);+ if (helpers) return helpers;+ return make("thinking", "thinking", `after:${block.callId}`);+ }+ if (block.kind === "text") {+ return block.text.trim() ? make("composing", "composing", block.id) : make("thinking", "thinking", block.id);+ }+ return make("thinking", "thinking", block.id);+ }+ return make("thinking", "thinking", `start:${turn.id}`);+}++function runningHelpers(blocks: TurnBlock[]): Activity | null {+ const running = blocks.filter((block): block is ToolBlock => block.kind === "tool" && block.subagent?.status === "running");+ if (!running.length) return null;+ if (running.length === 1) {+ const title = running[0].subagent?.description ?? "";+ return title ? make("delegating", "delegate", running[0].callId, { target: title }) : make("delegating", "delegate_any", running[0].callId);+ }+ return make("delegating", "delegate_many", `helpers:${running.length}`, { target: String(running.length) });+}++/** Same family and same target: the same step, whatever its episode. */+export function sameStep(a: Activity | null, b: Activity | null): boolean {+ if (a === b) return true;+ if (!a || !b) return false;+ return a.family === b.family && a.phrase === b.phrase && a.target === b.target;+}++export function stepKey(activity: Activity | null): string {+ return activity ? `${activity.family}|${activity.phrase}|${activity.target}` : "";+}++function hash(text: string): number {+ let h = 2166136261;+ for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 16777619) >>> 0;+ return h;+}++/** The full i18n key of the phrase, with the episode's stable variant. */+export function phraseKey(activity: Activity): string {+ const count = VARIANTS[activity.phrase] ?? 0;+ const suffix = count > 1 ? `_${hash(activity.episode) % count}` : "";+ return `run_view.phrase.${activity.phrase}${suffix}`;+}++/** Collapse whitespace and cap at `max` characters with an ellipsis. */+export function capPhrase(text: string, max = PHRASE_MAX): string {+ const clean = text.replace(/\s+/g, " ").trim();+ return clean.length > max ? `${clean.slice(0, max - 1).trimEnd()}…` : clean;+}++/**+ * The line itself. The target is shortened first, so the verb always reads+ * whole ("Editing …/very/long/name.ts" rather than "Editi…").+ */+export function activityPhrase(activity: Activity, t: (key: string) => string): string {+ const template = t(phraseKey(activity));+ if (!activity.target || !template.includes("{target}")) return capPhrase(template);+ const room = Math.max(8, PHRASE_MAX - (template.replace("{target}", "").length));+ const target = capPhrase(activity.target, room);+ return capPhrase(fill(template, { target }));+}++/** The face's scene for each family (BotStage keeps its own pacing and crossfades). */+const PRESENCE: Record<ActivityFamily, Presence> = {+ thinking: "thinking",+ composing: "typing",+ searching: "searching",+ reading: "searching",+ writing: "writing",+ running: "command",+ browsing: "browsing",+ recalling: "recall",+ noting: "writing",+ messaging: "working",+ delegating: "working",+ connecting: "setting_up",+ setting_up: "setting_up",+ waiting: "reading",+ working: "working",+};++export function presenceForFamily(family: ActivityFamily): Presence {+ return PRESENCE[family];+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/runAnnouncer.ts b/dodaios/ui/web/frontend/src/components/agentchat/activity/runAnnouncer.tsnew file mode 100644index 0000000000..95141b23d8--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/runAnnouncer.ts@@ -0,0 +1,66 @@+/**+ * What a screen reader hears about an agent's turn: that it started, replied,+ * finished without a reply, stopped, failed, or asks the person something.+ * One sentence per change of the turn's lifecycle, never one per step, so a+ * long run never floods the reader. Visual only otherwise: nothing here is+ * ever spoken aloud by the app's own voice.+ */++import { waitsOnCard, type TimelineItem, type TurnItem } from "../reduce";++export interface RunSnapshot {+ turnId: string;+ status: TurnItem["status"];+ /** The id of the card that waits for the person, or "". */+ waitingOn: string;+ answered: boolean;+}++/** The newest turn's lifecycle, or null before the first turn. */+export function runSnapshot(items: readonly TimelineItem[]): RunSnapshot | null {+ for (let i = items.length - 1; i >= 0; i--) {+ const item = items[i];+ if (item.type !== "turn") continue;+ const waiting = item.blocks.find((block) => block.kind === "tool"+ && (waitsOnCard(block) || Boolean(block.approval && block.approval.decision === null)));+ return {+ turnId: item.id,+ status: item.status,+ waitingOn: waiting && waiting.kind === "tool" ? waiting.callId : "",+ answered: item.blocks.some((block) => block.kind === "text" && block.text.trim().length > 0),+ };+ }+ return null;+}++export interface Announcement {+ key: string;+ /** The question's text, for "asks". */+ detail: string;+}++/** The sentence a change deserves, or null when nothing worth saying changed. */+export function announcementFor(prev: RunSnapshot | null, next: RunSnapshot | null, question = ""): Announcement | null {+ if (!next) return null;+ const sameTurn = prev?.turnId === next.turnId;+ if (next.waitingOn && (!sameTurn || prev?.waitingOn !== next.waitingOn)) {+ return question ? { key: "run_view.announce.asked", detail: question } : { key: "run_view.announce.needs_ok", detail: "" };+ }+ if (sameTurn && prev?.status === next.status) return null;+ if (next.status === "running") return sameTurn ? null : { key: "run_view.announce.started", detail: "" };+ // A turn seen for the first time already finished was never live here.+ if (!sameTurn) return null;+ if (next.status === "done") return { key: next.answered ? "run_view.announce.replied" : "run_view.announce.finished", detail: "" };+ if (next.status === "cancelled") return { key: "run_view.announce.stopped", detail: "" };+ return { key: "run_view.announce.failed", detail: "" };+}++/** The first open question's text on the newest turn, for "asks". */+export function openQuestionText(items: readonly TimelineItem[], snapshot: RunSnapshot | null): string {+ if (!snapshot?.waitingOn) return "";+ const turn = items.find((item): item is TurnItem => item.type === "turn" && item.id === snapshot.turnId);+ const block = turn?.blocks.find((b) => b.kind === "tool" && b.callId === snapshot.waitingOn);+ if (!block || block.kind !== "tool" || !block.question) return "";+ const index = block.question.answers.findIndex((answer) => answer === null);+ return block.question.questions[Math.max(0, index)]?.question ?? "";+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/runView.css b/dodaios/ui/web/frontend/src/components/agentchat/activity/runView.cssnew file mode 100644index 0000000000..b26f75f484--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/runView.css@@ -0,0 +1,177 @@+/*+ * The run view: the live activity line, the per-turn "show work" line, the+ * transcript's time stamps and catch-up pills. Theme variables only; the+ * agent's own colour (--agent) is the one accent.+ */++/* ---- activity line ------------------------------------------------------ */++.run-activity {+ min-height: 36px;+}+.run-activity .bs-label {+ /* The phrase carries its own light sweep; the stage's pulse would fight it. */+ animation: bs-label-in 0.3s ease-out both;+ max-width: 100%;+ overflow: hidden;+}+.run-activity-words {+ display: inline-flex;+ min-width: 0;+ align-items: center;+ gap: 6px;+}+.run-activity-phrase {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ background-image: linear-gradient(+ 90deg,+ hsl(var(--muted-foreground)) 0%,+ hsl(var(--muted-foreground)) 36%,+ hsl(var(--foreground-strong)) 50%,+ hsl(var(--muted-foreground)) 64%,+ hsl(var(--muted-foreground)) 100%+ );+ background-size: 250% 100%;+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ animation: run-sweep 2.6s linear infinite;+}+.run-activity[data-family="waiting"] .run-activity-phrase {+ /* Nothing moves until the person answers: the words rest. */+ animation: none;+ background-image: none;+ color: hsl(var(--foreground-secondary));+}+.run-activity-timer {+ flex: none;+ color: hsl(var(--muted-foreground));+ font-variant-numeric: tabular-nums;+}+.run-activity-brand,+.run-activity-peer {+ display: inline-flex;+ flex: none;+ align-items: center;+}+@keyframes run-sweep {+ from { background-position: 100% 0; }+ to { background-position: -150% 0; }+}++/* ---- show work ------------------------------------------------------------ */++.run-work {+ display: inline-flex;+ max-width: 100%;+ align-items: center;+ gap: 6px;+ align-self: flex-start;+ margin-top: 2px;+ padding: 3px 8px 3px 6px;+ border-radius: 10px;+ color: hsl(var(--muted-foreground));+ font-size: 12px;+ line-height: 18px;+ transition: background-color 150ms ease, color 150ms ease;+}+.run-work:hover,+.run-work[aria-expanded="true"] {+ background: hsl(var(--secondary));+ color: hsl(var(--foreground));+}+.run-work:focus-visible {+ outline: none;+ box-shadow: 0 0 0 2px hsl(var(--ring));+}+.run-work-sep {+ opacity: 0.5;+}+.run-work-chev {+ opacity: 0;+ transition: opacity 150ms ease, transform 150ms ease;+}+.run-work:hover .run-work-chev,+.run-work:focus-visible .run-work-chev,+.run-work[aria-expanded="true"] .run-work-chev {+ opacity: 0.7;+}+@media (hover: none) {+ .run-work-chev { opacity: 0.7; }+}+.run-diff-add { color: hsl(var(--diff-add)); }+.run-diff-del { color: hsl(var(--diff-del)); }++/* ---- time stamps ---------------------------------------------------------- */++.run-stamp {+ display: flex;+ align-items: center;+ gap: 12px;+ margin: 14px 0 6px;+ color: hsl(var(--muted-foreground));+ font-size: 11px;+ line-height: 16px;+ letter-spacing: 0.01em;+}+.run-stamp::before,+.run-stamp::after {+ content: "";+ flex: 1;+ height: 1px;+ background: hsl(var(--border));+}++/* ---- catch-up pill ---------------------------------------------------------- */++.run-pill {+ position: absolute;+ bottom: 12px;+ left: 50%;+ z-index: 10;+ display: inline-flex;+ align-items: center;+ transform: translateX(-50%);+ border-radius: 999px;+ border: 1px solid hsl(var(--border-strong));+ background: hsl(var(--card));+ box-shadow: 0 12px 32px -8px rgb(var(--scrim-rgb) / 0.55), 0 1px 2px rgb(var(--scrim-rgb) / 0.18);+ font-size: 12px;+ line-height: 18px;+ animation: run-pill-in 200ms cubic-bezier(0.2, 0.8, 0.2, 1) both;+}+.run-pill button {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ border-radius: 999px;+ color: hsl(var(--foreground));+ transition: background-color 150ms ease;+}+.run-pill button:hover { background: hsl(var(--secondary)); }+.run-pill button:focus-visible { outline: none; box-shadow: 0 0 0 2px hsl(var(--ring)); }+.run-pill-main { padding: 5px 6px 5px 12px; }+.run-pill-close { padding: 6px; color: hsl(var(--muted-foreground)) !important; }+@keyframes run-pill-in {+ from { opacity: 0; transform: translate(-50%, 6px); }+ to { opacity: 1; transform: translate(-50%, 0); }+}++/* ---- new rows settle in --------------------------------------------------- */++.run-settle {+ will-change: height;+}++@media (prefers-reduced-motion: reduce) {+ .run-activity-phrase {+ animation: none;+ background-image: none;+ color: hsl(var(--foreground-secondary));+ }+ .run-pill { animation: none; }+ .run-work, .run-work-chev { transition: none; }+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/runViewModels.test.ts b/dodaios/ui/web/frontend/src/components/agentchat/activity/runViewModels.test.tsnew file mode 100644index 0000000000..11d416c86b--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/runViewModels.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from "vitest";+import en from "@/i18n/locales/en.json";+import type { ReasoningBlock, TimelineItem, ToolBlock, TurnBlock, TurnItem, UserItem } from "../reduce";+import { announcementFor, openQuestionText, runSnapshot } from "./runAnnouncer";+import { stampLabel, stampPlan, STAMP_GAP_MS } from "./transcriptTime";+import { countUnseen } from "./TranscriptAids";+import { hasWork, workHeadKey, workSummary } from "./workSummary";++function t(key: string): string {+ let at: unknown = en;+ for (const part of key.split(".")) at = (at as Record<string, unknown>)?.[part];+ return typeof at === "string" ? at : key;+}++function turn(blocks: TurnBlock[], status: TurnItem["status"] = "done", id = "t1", startedMs = 1): TurnItem {+ return {+ type: "turn", id, provider: "p", model: "", effort: "", runner: "api", status, blocks,+ startedMs, durationMs: 4_000, usage: null, liveUsage: null, costUsd: null, error: null,+ };+}+function call(name: string, input: unknown = {}, output: string | null = "ok", extra: Partial<ToolBlock> = {}): ToolBlock {+ return { kind: "tool", callId: `c-${name}-${JSON.stringify(input).length}`, name, input, output, isError: false, durationMs: 10, approval: null, startedMs: 1, ...extra };+}+const thought: ReasoningBlock = { kind: "reasoning", id: "r1", text: "", durationMs: 900, live: false, startedMs: 1 };+const user = (id: string, tsMs: number): UserItem => ({ type: "user", id, text: "hi", attachments: [], tsMs });++describe("workSummary", () => {+ it("counts steps, helpers and changed files, without card polls or memory notes", () => {+ const blocks: TurnBlock[] = [+ thought,+ call("Read", { file_path: "a.ts" }),+ call("Edit", { file_path: "a.ts", old_string: "one\ntwo", new_string: "one\n2\nthree" }),+ call("Write", { file_path: "b.ts", content: "x\ny" }),+ call("society_wiki_note", { title: "Plan", body: "x" }, "{\"path\":\"society/a/x.md\",\"before\":\"\",\"after\":\"x\"}"),+ call("society_ask_user", { wait_for: "q1" }, "{\"status\":\"waiting\"}"),+ call("Task", { description: "Explore" }, "done"),+ call("Bash", { command: "false" }, "exit 1", { isError: true }),+ ];+ const summary = workSummary(blocks);+ expect(summary.steps).toBe(6);+ expect(summary.thoughts).toBe(1);+ expect(summary.helpers).toBe(1);+ expect(summary.files).toBe(2);+ expect(summary.added).toBe(4);+ expect(summary.removed).toBe(1);+ expect(summary.failed).toBe(1);+ expect(hasWork(summary)).toBe(true);+ });++ it("a plain reply has no work to show", () => {+ expect(hasWork(workSummary([{ kind: "text", id: "x", text: "Hello" }]))).toBe(false);+ });++ it("the line opens with how the turn ended", () => {+ expect(workHeadKey(turn([], "running"))).toBe("run_view.work.working");+ expect(workHeadKey(turn([], "cancelled"))).toBe("run_view.work.stopped_after");+ expect(workHeadKey(turn([], "error"))).toBe("run_view.work.failed_after");+ expect(workHeadKey(turn([]))).toBe("run_view.work.worked_for");+ });+});++describe("stampPlan", () => {+ const base = new Date(2026, 9, 26, 10, 0).getTime();+ it("stamps the first message, a 15-minute pause and a new day", () => {+ const plan = stampPlan([+ { id: "a", ts: base, author: "person" },+ { id: "b", ts: base + 60_000, author: "agent" },+ { id: "c", ts: base + 60_000 + STAMP_GAP_MS, author: "person" },+ { id: "d", ts: base + 60_000 + STAMP_GAP_MS + 1_000, author: "agent" },+ { id: "e", ts: new Date(2026, 9, 27, 8, 0).getTime(), author: "person" },+ ]);+ expect([...plan]).toEqual(["a", "c", "e"]);+ });++ it("never splits one speaker's run, and ignores entries without a time", () => {+ const plan = stampPlan([+ { id: "a", ts: base, author: "agent" },+ { id: "x", ts: 0, author: "notice" },+ { id: "b", ts: base + 2 * STAMP_GAP_MS, author: "agent" },+ { id: "c", ts: base + 2 * STAMP_GAP_MS + 1, author: "person" },+ ]);+ expect([...plan]).toEqual(["a"]);+ });++ it("says today, yesterday, a weekday date, then a full date", () => {+ const now = new Date(2026, 9, 26, 18, 0).getTime();+ expect(stampLabel(new Date(2026, 9, 26, 9, 5).getTime(), now, "en-GB", t)).toBe("Today 09:05");+ expect(stampLabel(new Date(2026, 9, 25, 9, 5).getTime(), now, "en-GB", t)).toBe("Yesterday 09:05");+ expect(stampLabel(new Date(2026, 2, 3, 9, 5).getTime(), now, "en-GB", t)).toMatch(/Tue.*3.*Mar.*09:05/);+ expect(stampLabel(new Date(2025, 2, 3, 9, 5).getTime(), now, "en-GB", t)).toMatch(/2025.*09:05/);+ });+});++describe("countUnseen", () => {+ it("counts only what the reader has not seen", () => {+ const items: TimelineItem[] = [user("u1", 1), turn([], "done", "t1"), user("u2", 2), turn([], "running", "t2")];+ expect(countUnseen(items, new Set(["u1", "t1"]))).toBe(2);+ expect(countUnseen(items, new Set(items.map((item) => item.id)))).toBe(0);+ });+});++describe("run announcer", () => {+ const question = call("society_ask_user", {}, null, {+ callId: "q", question: { questionId: "q1", asker: "", questions: [{ question: "Which branch?", options: [], recommendationReason: "" }],+ answers: [null], expiresMs: null, closed: false },+ });++ it("says started, asks, replied, stopped and failed, once per change", () => {+ const running = runSnapshot([turn([], "running")]);+ expect(announcementFor(null, running)?.key).toBe("run_view.announce.started");+ expect(announcementFor(running, running)).toBeNull();+ const asking = [turn([question], "running")];+ const snap = runSnapshot(asking);+ expect(announcementFor(running, snap, openQuestionText(asking, snap))).toEqual({ key: "run_view.announce.asked", detail: "Which branch?" });+ const replied = runSnapshot([turn([{ kind: "text", id: "x", text: "Done." }], "done")]);+ expect(announcementFor(running, replied)?.key).toBe("run_view.announce.replied");+ expect(announcementFor(running, runSnapshot([turn([], "done")]))?.key).toBe("run_view.announce.finished");+ expect(announcementFor(running, runSnapshot([turn([], "cancelled")]))?.key).toBe("run_view.announce.stopped");+ expect(announcementFor(running, runSnapshot([turn([], "error")]))?.key).toBe("run_view.announce.failed");+ });++ it("never reads out a turn that was already over when it first appeared", () => {+ const old = runSnapshot([turn([], "done", "t0")]);+ expect(announcementFor(old, runSnapshot([turn([], "done", "t9")]))).toBeNull();+ });++ it("an approval card is announced as needing an OK", () => {+ const running = runSnapshot([turn([], "running")]);+ const gate = call("Bash", { command: "rm x" }, null, { approval: { approvalId: "a1", summary: "", decision: null } });+ expect(announcementFor(running, runSnapshot([turn([gate], "running")]))?.key).toBe("run_view.announce.needs_ok");+ });+});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/transcriptTime.ts b/dodaios/ui/web/frontend/src/components/agentchat/activity/transcriptTime.tsnew file mode 100644index 0000000000..5cf1d84c8e--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/transcriptTime.ts@@ -0,0 +1,77 @@+/**+ * When a conversation shows a time stamp, and what it says.+ *+ * A stamp marks a pause: 15 minutes or more of silence, or a new day. It+ * sits in front of a whole run of messages by the same author, never in the+ * middle of one, so a reply that came after a long think is not cut off+ * from its question. The first message of a conversation always gets one.+ *+ * The words are short and relative: "Today 14:05", "Yesterday 09:12",+ * "Tue, 14 Oct 18:30" inside the year, a full date before it.+ */++/** Silence this long earns a fresh stamp. */+export const STAMP_GAP_MS = 15 * 60_000;++export interface StampEntry {+ id: string;+ /** When the entry happened; 0 when it carries no time (it neither earns nor breaks a stamp). */+ ts: number;+ /** When it ended, for an entry that lasts (a turn); a pause is counted from here. */+ end?: number;+ /** Who spoke: consecutive entries by the same author share one stamp. */+ author: string;+}++function dayOf(ms: number): string {+ return new Date(ms).toDateString();+}++/** The ids of the entries that get a stamp in front of them. */+export function stampPlan(entries: readonly StampEntry[], gapMs = STAMP_GAP_MS): Set<string> {+ const out = new Set<string>();+ let lastTs = 0;+ let lastAuthor: string | null = null;+ for (const entry of entries) {+ if (!entry.ts) continue;+ const newGroup = entry.author !== lastAuthor;+ if (newGroup) {+ const pause = lastTs === 0 || entry.ts - lastTs >= gapMs || dayOf(entry.ts) !== dayOf(lastTs);+ if (pause) out.add(entry.id);+ }+ lastTs = Math.max(lastTs, entry.end ?? entry.ts);+ lastAuthor = entry.author;+ }+ return out;+}++const formatters = new Map<string, Intl.DateTimeFormat>();++function formatter(locale: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {+ const key = `${locale}|${JSON.stringify(options)}`;+ let found = formatters.get(key);+ if (!found) {+ try {+ found = new Intl.DateTimeFormat(locale, options);+ } catch {+ found = new Intl.DateTimeFormat(undefined, options);+ }+ formatters.set(key, found);+ }+ return found;+}++/** The stamp's words, relative to `now`. `t` fills `run_view.time.*`. */+export function stampLabel(ms: number, now: number, locale: string, t: (key: string) => string): string {+ const date = new Date(ms);+ const time = formatter(locale, { hour: "2-digit", minute: "2-digit" }).format(date);+ const today = new Date(now);+ if (date.toDateString() === today.toDateString()) return t("run_view.time.today").replace("{time}", time);+ const yesterday = new Date(now);+ yesterday.setDate(yesterday.getDate() - 1);+ if (date.toDateString() === yesterday.toDateString()) return t("run_view.time.yesterday").replace("{time}", time);+ if (date.getFullYear() === today.getFullYear()) {+ return `${formatter(locale, { weekday: "short", day: "numeric", month: "short" }).format(date)} ${time}`;+ }+ return `${formatter(locale, { day: "numeric", month: "short", year: "numeric" }).format(date)} ${time}`;+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/usePacedActivity.test.tsx b/dodaios/ui/web/frontend/src/components/agentchat/activity/usePacedActivity.test.tsxnew file mode 100644index 0000000000..f0ff452ab0--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/usePacedActivity.test.tsx@@ -0,0 +1,77 @@+import { act, cleanup, render } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Activity } from "./activityModel";+import { HOLD_MS, usePacedActivity } from "./usePacedActivity";++const step = (family: Activity["family"], target = "", episode = `${family}:${target}`): Activity =>+ ({ family, phrase: family, target, episode, brand: "", peer: "" });++/** Records every value the hook hands to the line, one entry per commit. */+function Probe({ next, seen, times }: { next: Activity | null; seen: (Activity | null)[]; times?: number[] }) {+ const shown = usePacedActivity(next);+ seen.push(shown);+ times?.push(Date.now());+ return null;+}++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(10_000);+});+afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++function changes(seen: (Activity | null)[]): (Activity | null)[] {+ return seen.filter((value, i) => i === 0 || value !== seen[i - 1]);+}++describe("usePacedActivity", () => {+ it("holds a step for 800 ms and keeps only the newest waiting one", () => {+ const seen: (Activity | null)[] = [];+ const { rerender } = render(<Probe next={step("reading", "a.ts")} seen={seen} />);+ act(() => { vi.advanceTimersByTime(100); });+ rerender(<Probe next={step("searching", "x")} seen={seen} />);+ act(() => { vi.advanceTimersByTime(100); });+ rerender(<Probe next={step("running", "npm")} seen={seen} />);+ // Nothing changed yet: the first step still has its 800 ms.+ expect(seen.at(-1)?.family).toBe("reading");+ act(() => { vi.advanceTimersByTime(HOLD_MS); });+ // The queue keeps one slot: "searching" was replaced before it showed.+ expect(changes(seen).map((value) => value?.family)).toEqual(["reading", "running"]);+ });++ it("does not re-show the same step under a new episode", () => {+ const seen: (Activity | null)[] = [];+ const first = step("thinking", "", "r1");+ const { rerender } = render(<Probe next={first} seen={seen} />);+ act(() => { vi.advanceTimersByTime(2_000); });+ rerender(<Probe next={step("thinking", "", "r2")} seen={seen} />);+ act(() => { vi.advanceTimersByTime(2_000); });+ expect(seen.at(-1)).toBe(first);+ });++ it("a step after a long one shows at once", () => {+ const seen: (Activity | null)[] = [];+ const { rerender } = render(<Probe next={step("reading", "a.ts")} seen={seen} />);+ act(() => { vi.advanceTimersByTime(5_000); });+ rerender(<Probe next={step("writing", "a.ts")} seen={seen} />);+ expect(seen.at(-1)?.family).toBe("writing");+ });++ it("a storm of steps changes the line at most once per 800 ms", () => {+ const seen: (Activity | null)[] = [];+ const times: number[] = [];+ const { rerender } = render(<Probe next={step("thinking")} seen={seen} times={times} />);+ for (let i = 0; i < 120; i++) {+ act(() => { vi.advanceTimersByTime(50); });+ rerender(<Probe next={step(i % 2 ? "reading" : "running", String(i))} seen={seen} times={times} />);+ }+ // When the shown value changed, as the line committed it.+ const stamps = seen.flatMap((value, i) => (i === 0 || value !== seen[i - 1] ? [times[i]] : []));+ expect(stamps.length).toBeGreaterThan(2);+ expect(stamps.length).toBeLessThanOrEqual(Math.ceil(6_000 / HOLD_MS) + 1);+ for (let i = 1; i < stamps.length; i++) expect(stamps[i] - stamps[i - 1]).toBeGreaterThanOrEqual(HOLD_MS);+ });+});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/usePacedActivity.ts b/dodaios/ui/web/frontend/src/components/agentchat/activity/usePacedActivity.tsnew file mode 100644index 0000000000..2503e7c351--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/usePacedActivity.ts@@ -0,0 +1,46 @@+import { useEffect, useRef, useState } from "react";+import { sameStep, stepKey, type Activity } from "./activityModel";++/** No step leaves the line sooner than this, however fast the next one arrives. */+export const HOLD_MS = 800;++/**+ * Paces the activity line so it reads instead of flickering.+ *+ * - A shown step stays at least `holdMs`. A newer step waits in a one-slot+ * queue meanwhile; only the latest waiting step is kept, so a burst of+ * ten short calls costs one change, not ten.+ * - A step of the same family and target as the shown one is the same step+ * (`sameStep`): the line keeps its words and does not animate again.+ *+ * The line therefore changes at most once per `holdMs`, and the component+ * re-renders only when it does.+ */+export function usePacedActivity(next: Activity | null, holdMs = HOLD_MS): Activity | null {+ const [shown, setShown] = useState<Activity | null>(next);+ const shownAt = useRef(Date.now());+ const latest = useRef(next);+ latest.current = next;+ const shownRef = useRef(shown);+ shownRef.current = shown;+ const key = stepKey(next);++ useEffect(() => {+ if (sameStep(shownRef.current, latest.current)) return;+ const show = () => {+ const pending = latest.current;+ if (sameStep(shownRef.current, pending)) return;+ shownAt.current = Date.now();+ setShown(pending);+ };+ const wait = holdMs - (Date.now() - shownAt.current);+ if (wait <= 0) {+ show();+ return;+ }+ const timer = window.setTimeout(show, wait);+ return () => window.clearTimeout(timer);+ }, [key, shown, holdMs]);++ return shown;+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/workSummary.ts b/dodaios/ui/web/frontend/src/components/agentchat/activity/workSummary.tsnew file mode 100644index 0000000000..62bc16566a--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/workSummary.ts@@ -0,0 +1,87 @@+/**+ * A turn's work in one line: how long, how many steps, which files changed.+ *+ * The specialist chat keeps tool calls and thoughts out of the conversation.+ * Under each turn that did any work, one quiet line says how much there was+ * ("Worked for 2m 05s · 14 steps · 3 files +40 −12") and opens the work+ * inspector. Pure, so the counts are testable and the same everywhere.+ */++import { isSubagentCall } from "@/components/agentic/threads/subagents";+import { isCredentialTool, isQuestionTool, type ToolBlock, type TurnBlock, type TurnItem } from "../reduce";+import { toolDiff } from "../toolDiff";+import { traceAction, traceToolName } from "../traceActivity";++export interface WorkSummary {+ /** Tool calls the agent made itself, without the polls behind a card. */+ steps: number;+ /** Thoughts, worded or not. */+ thoughts: number;+ /** Helpers (sub-agents) it started. */+ helpers: number;+ /** Distinct files its edits touched. */+ files: number;+ added: number;+ removed: number;+ /** Calls that failed. */+ failed: number;+}++/** A call that only waits on a card the person answers: never a step. */+export function isCardPoll(block: ToolBlock): boolean {+ return (isQuestionTool(block.name) && !block.question) || (isCredentialTool(block.name) && !block.credential);+}++/** Files, added and removed lines of one edit, from the diff the trace paints. */+export function editStat(block: ToolBlock): { paths: string[]; added: number; removed: number } {+ // Memory notes paint a diff too, but they are notes, not changed files.+ const action = traceAction(traceToolName(block.name));+ if (action !== "edit" && action !== "write") return { paths: [], added: 0, removed: 0 };+ const files = toolDiff(block.name, block.input, block.output) ?? [];+ let added = 0;+ let removed = 0;+ for (const file of files) {+ added += file.added;+ removed += file.removed;+ }+ return { paths: files.map((file) => file.path || "?"), added, removed };+}++export function workSummary(blocks: readonly TurnBlock[]): WorkSummary {+ const paths = new Set<string>();+ const out: WorkSummary = { steps: 0, thoughts: 0, helpers: 0, files: 0, added: 0, removed: 0, failed: 0 };+ for (const block of blocks) {+ if (block.kind === "reasoning") {+ out.thoughts += 1;+ continue;+ }+ if (block.kind !== "tool" || isCardPoll(block)) continue;+ out.steps += 1;+ if (block.isError) out.failed += 1;+ if (isSubagentCall(block)) {+ out.helpers += 1;+ continue;+ }+ // A denied edit changed nothing.+ if (block.isError || block.approval?.decision === "deny") continue;+ const stat = editStat(block);+ for (const path of stat.paths) paths.add(path);+ out.added += stat.added;+ out.removed += stat.removed;+ }+ out.files = paths.size;+ return out;+}++/** The turn did something worth opening: a call, a thought, a helper. */+export function hasWork(summary: WorkSummary): boolean {+ return summary.steps > 0 || summary.thoughts > 0;+}++/** How the line opens: still working, or how the turn ended. */+export function workHeadKey(turn: TurnItem): string {+ if (turn.status === "running") return "run_view.work.working";+ if (turn.status === "cancelled") return "run_view.work.stopped_after";+ if (turn.status === "error") return "run_view.work.failed_after";+ return "run_view.work.worked_for";+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/botStage/BotStage.tsx b/dodaios/ui/web/frontend/src/components/agentchat/botStage/BotStage.tsxindex 6889e4be41..2a876fcba0 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/botStage/BotStage.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/botStage/BotStage.tsx@@ -21,7 +21,7 @@ import "./botStage.css";* scene never cuts: the outgoing face, prop and word stay mounted, still* playing their scene, and fade off over the incoming ones (Crossfade).*/-export function BotStage({ presence, seed, avatar, color }: {+export function BotStage({ presence, seed, avatar, color, words, wordsId, announce = true }: {presence: Presence;/** Stable per turn: picks which scene of a family this turn plays. */seed: string;@@ -29,6 +29,18 @@ export function BotStage({ presence, seed, avatar, color }: {avatar: ReactNode;/** The agent's colour, for the accents of the props. */color: string;+ /**+ * Words in place of the scene's own word (the activity line's phrase).+ * `wordsId` keys their crossfade, so new words of the same step swap in+ * place instead of fading.+ */+ words?: ReactNode;+ wordsId?: string;+ /**+ * The stage is its own status region. Off where the surface announces the+ * lifecycle itself, so a phrase per step never floods a screen reader.+ */+ announce?: boolean;}) {const t = useT();const scene = useSceneDirector(presence, seed);@@ -36,7 +48,8 @@ export function BotStage({ presence, seed, avatar, color }: {// The tick on the finished turn's badge takes the ink that reads on the agent's colour.const ink = bubbleTint(color)?.color ?? "#ffffff";return <div className="bot-stage" data-scene={scene} style={{ "--bot": color, "--bot-ink": ink } as CSSProperties}- role="status" aria-label={label} data-testid="messenger-presence" data-presence={presence}>+ role={announce ? "status" : undefined} aria-label={announce ? label : undefined}+ data-testid="messenger-presence" data-presence={presence}><span className="bs-set" aria-hidden><Crossfade id={scene} className="bs-face">{/* A face that wears a pet plays the scene's pet row instead of moving its eyes. */}@@ -49,7 +62,7 @@ export function BotStage({ presence, seed, avatar, color }: {{PROP[scene] && <svg className="bs-prop" viewBox="0 0 20 20" width="20" height="20">{PROP[scene]}</svg>}</Crossfade></span>- <span className="bs-label"><Crossfade id={scene} className="bs-word">{label}</Crossfade></span>+ <span className="bs-label"><Crossfade id={wordsId ?? scene} className="bs-word">{words ?? label}</Crossfade></span></div>;}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/inspector/WorkInspector.test.tsx b/dodaios/ui/web/frontend/src/components/agentchat/inspector/WorkInspector.test.tsxnew file mode 100644index 0000000000..378908a056--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/inspector/WorkInspector.test.tsx@@ -0,0 +1,195 @@+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import en from "@/i18n/locales/en.json";+import { EMPTY_TIMELINE, reduceEvents, type TurnItem } from "../reduce";+import type { AgentChatEvent } from "@/lib/agentChatApi";+import { inspectorRows, previewOf, rowCounts } from "./inspectorRows";+import { clampWidth, inspectorDocked, INSPECTOR_MAX, INSPECTOR_MIN } from "./inspectorWidth";+import { WorkInspector } from "./WorkInspector";++afterEach(cleanup);++function t(key: string): string {+ let at: unknown = en;+ for (const part of key.split(".")) at = (at as Record<string, unknown>)?.[part];+ return typeof at === "string" ? at : key;+}++let seq = 0;+const ev = (kind: string, payload: Record<string, unknown>): AgentChatEvent =>+ ({ seq: ++seq, ts_ms: 1_000 + seq, kind, payload } as AgentChatEvent);+const turnOf = (events: AgentChatEvent[]) =>+ reduceEvents(EMPTY_TIMELINE, events).items.find((item) => item.type === "turn") as TurnItem;++/** Our own agent on a provider API: a thought, an edit and a reply. */+function brainTurn(): TurnItem {+ return turnOf([+ ev("user_message", { text: "Fix the typo" }),+ ev("turn_started", { turn_id: "t1", provider: "openai", model: "gpt-x", runner: "brain" }),+ ev("reasoning", { turn_id: "t1", message_id: "r1", text: "The typo is in the header.", duration_ms: 1200 }),+ ev("tool_call", { turn_id: "t1", call_id: "e1", name: "Edit", input: { file_path: "src/head.ts", old_string: "Helo", new_string: "Hello" } }),+ ev("tool_result", { turn_id: "t1", call_id: "e1", output: "ok", is_error: false, duration_ms: 40 }),+ ev("assistant_text", { turn_id: "t1", message_id: "m1", text: "Fixed it." }),+ ev("turn_finished", { turn_id: "t1", status: "done", duration_ms: 5_000 }),+ ]);+}++/** A coding CLI that reported a sub-agent with its own steps (Claude Code, Codex). */+function cliTurn(): TurnItem {+ return turnOf([+ ev("turn_started", { turn_id: "t2", provider: "claude-cli", runner: "claude-cli" }),+ ev("tool_call", { turn_id: "t2", call_id: "spawn", name: "Agent", input: { description: "Count files", prompt: "Run ls" } }),+ ev("subagent_started", { turn_id: "t2", agent_id: "spawn", description: "Count files", agent_type: "Explore", prompt: "Run ls", background: false }),+ ev("tool_call", { turn_id: "t2", agent_id: "spawn", call_id: "ls", name: "Bash", input: { command: "ls" } }),+ ev("tool_result", { turn_id: "t2", agent_id: "spawn", call_id: "ls", output: "a\nb", is_error: false }),+ ev("subagent_finished", { turn_id: "t2", agent_id: "spawn", status: "done", summary: "Two files.", duration_ms: 900 }),+ ev("tool_result", { turn_id: "t2", call_id: "spawn", output: "Two files.", is_error: false }),+ ev("assistant_text", { turn_id: "t2", message_id: "m2", text: "There are two files." }),+ ev("turn_finished", { turn_id: "t2", status: "done", duration_ms: 3_000 }),+ ]);+}++/** A runtime that streams nothing: only finished blocks arrive (Kimi, dsh). */+function quietTurn(): TurnItem {+ return turnOf([+ ev("turn_started", { turn_id: "t3", provider: "kimi", runner: "kimi-cli" }),+ ev("assistant_text", { turn_id: "t3", message_id: "m3", text: "All done." }),+ ev("turn_finished", { turn_id: "t3", status: "done", duration_ms: 2_000 }),+ ]);+}++function draw(turn: TurnItem, extra: Partial<Parameters<typeof WorkInspector>[0]> = {}) {+ const onClose = vi.fn();+ render(<WorkInspector turn={turn} agentName="Scout" color="#7ab6ef" width={420} onWidth={() => undefined}+ floating={false} onClose={onClose} {...extra} />);+ return { onClose };+}++describe("inspectorRows", () => {+ it("reads a brain turn in order: request, thought, call, reply", () => {+ const turn = brainTurn();+ const rows = inspectorRows(turn.blocks, { t, lang: "en", status: turn.status, prompt: "Fix the typo" });+ expect(rows.map((row) => row.kind)).toEqual(["prompt", "thought", "call", "reply"]);+ const edit = rows[2];+ expect(edit.label).toContain("head.ts");+ expect(edit.added).toBe(1);+ expect(edit.removed).toBe(1);+ expect(rowCounts(rows)).toEqual({ steps: 1, thoughts: 1, failed: 0 });+ });++ it("a CLI's helper is one row in the main trace; its steps stay in its own", () => {+ const turn = cliTurn();+ const rows = inspectorRows(turn.blocks, { t, lang: "en", status: turn.status });+ expect(rows.map((row) => row.kind)).toEqual(["helper", "reply"]);+ expect(rows[0].preview).toBe("Count files");+ });++ it("an ACP runtime (Hermes, OpenClaw) reads the same as any other", () => {+ const turn = turnOf([+ ev("turn_started", { turn_id: "t4", provider: "openrouter", runner: "hermes-cli" }),+ ev("reasoning", { turn_id: "t4", message_id: "r4", text: "", duration_ms: 300 }),+ ev("tool_call", { turn_id: "t4", call_id: "w1", name: "mcp__dodaios__society_wiki_note", input: { title: "Plan" } }),+ ev("tool_result", { turn_id: "t4", call_id: "w1", output: "{\"ok\":true}", is_error: false }),+ ev("assistant_text", { turn_id: "t4", message_id: "m4", text: "Noted." }),+ ev("turn_finished", { turn_id: "t4", status: "done", duration_ms: 1_000 }),+ ]);+ const rows = inspectorRows(turn.blocks, { t, lang: "en", status: turn.status });+ expect(rows.map((row) => row.kind)).toEqual(["thought", "call", "reply"]);+ // A thought whose words the provider keeps private still says it happened.+ expect(rows[0].label).toBe(en.run_view.row.thought_hidden);+ });++ it("a CLI that reports no sub-agent events still shows its spawn call as a helper", () => {+ const turn = turnOf([+ ev("turn_started", { turn_id: "t5", provider: "opencode", runner: "opencode-cli" }),+ ev("tool_call", { turn_id: "t5", call_id: "s1", name: "task", input: { description: "Scan logs", prompt: "Look for errors" } }),+ ev("tool_result", { turn_id: "t5", call_id: "s1", output: "No errors.", is_error: false }),+ ev("turn_finished", { turn_id: "t5", status: "done", duration_ms: 1_000 }),+ ]);+ const [row] = inspectorRows(turn.blocks, { t, lang: "en", status: turn.status });+ expect(row.kind).toBe("helper");+ expect(row.status).toBe("done");+ });++ it("a runtime without a stream degrades to its finished blocks", () => {+ const turn = quietTurn();+ expect(inspectorRows(turn.blocks, { t, lang: "en", status: turn.status }).map((row) => row.kind)).toEqual(["reply"]);+ });++ it("previews take the first meaningful line, capped", () => {+ expect(previewOf("## Title\n\nbody")).toBe("Title");+ expect(previewOf("x".repeat(200)).length).toBe(80);+ });+});++describe("WorkInspector", () => {+ it("shows the reasoning the chat never shows, and opens a call to its diff", () => {+ draw(brainTurn(), { prompt: "Fix the typo" });+ const rows = screen.getAllByTestId("work-inspector-row");+ expect(rows).toHaveLength(4);+ fireEvent.click(within(rows[1]).getByRole("button"));+ expect(rows[1].querySelector(".wi-detail")?.textContent).toContain("The typo is in the header.");+ fireEvent.click(within(rows[2]).getByRole("button"));+ expect(screen.getByText("Changes")).toBeTruthy();+ const added = rows[2].querySelector(".wi-diff-line[data-kind=\"add\"]");+ expect(added?.textContent).toContain("Hello");+ });++ it("gives every helper a tab with its own trace and status", () => {+ draw(cliTurn());+ const tabs = screen.getAllByRole("tab");+ expect(tabs.map((tab) => tab.textContent)).toEqual([expect.stringContaining("Scout"), expect.stringContaining("Count files")]);+ expect(tabs[0].getAttribute("aria-selected")).toBe("true");+ fireEvent.keyDown(tabs[0], { key: "ArrowRight" });+ expect(screen.getAllByRole("tab")[1].getAttribute("aria-selected")).toBe("true");+ const kinds = screen.getAllByTestId("work-inspector-row").map((row) => row.dataset.kind);+ expect(kinds).toEqual(["prompt", "call", "reply"]);+ });++ it("hides the tab strip when nobody else worked on the turn", () => {+ draw(brainTurn());+ expect(screen.queryByRole("tablist")).toBeNull();+ });++ it("opens a helper's tab from its row", () => {+ draw(cliTurn());+ fireEvent.click(within(screen.getAllByTestId("work-inspector-row")[0]).getByRole("button"));+ fireEvent.click(screen.getByText("Open the helper's trace"));+ expect(screen.getAllByRole("tab")[1].getAttribute("aria-selected")).toBe("true");+ });++ it("Esc closes it, but not while typing", () => {+ const { onClose } = draw(brainTurn());+ const input = document.createElement("textarea");+ document.body.appendChild(input);+ fireEvent.keyDown(input, { key: "Escape" });+ expect(onClose).not.toHaveBeenCalled();+ fireEvent.keyDown(document.body, { key: "Escape" });+ expect(onClose).toHaveBeenCalledTimes(1);+ input.remove();+ });++ it("an empty live turn says that steps will show up", () => {+ draw(turnOf([ev("turn_started", { turn_id: "t9", provider: "kimi" })]));+ expect(screen.getByText(en.run_view.inspector.empty_live)).toBeTruthy();+ });++ it("the edge resizes within bounds by keyboard", () => {+ const widths: number[] = [];+ draw(brainTurn(), { onWidth: (w) => widths.push(w) });+ const edge = screen.getByTestId("work-inspector-edge");+ fireEvent.keyDown(edge, { key: "ArrowLeft" });+ fireEvent.keyDown(edge, { key: "End" });+ expect(widths).toEqual([436, INSPECTOR_MIN]);+ });+});++describe("inspector width", () => {+ it("clamps and decides between side by side and floating", () => {+ expect(clampWidth(10)).toBe(INSPECTOR_MIN);+ expect(clampWidth(5_000)).toBe(INSPECTOR_MAX);+ expect(clampWidth(600, 500)).toBe(500);+ expect(inspectorDocked(1200, 420)).toBe(true);+ expect(inspectorDocked(700, 420)).toBe(false);+ });+});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/inspector/WorkInspector.tsx b/dodaios/ui/web/frontend/src/components/agentchat/inspector/WorkInspector.tsxnew file mode 100644index 0000000000..313ecfe62f--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/inspector/WorkInspector.tsx@@ -0,0 +1,415 @@+import { memo, useCallback, useEffect, useId, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from "react";+import {+ Bot, Brain, ChevronRight, ChevronsDownUp, ChevronsUpDown, CircleX, KeyRound, ListTree,+ Loader2, MessageCircleQuestion, MessageSquareText, ShieldQuestion, User, X,+} from "lucide-react";+import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { useStickToBottom } from "@/hooks/useStickToBottom";+import { listSubagents, subagentTurn, type SubagentEntry } from "@/components/agentic/threads/subagents";+import { ChatMarkdown } from "../ChatMarkdown";+import type { SubagentStatus, ToolBlock, TurnItem } from "../reduce";+import { toolDiff } from "../toolDiff";+import { CallMark } from "../TraceTimeline";+import { plural, readableOutput, traceDuration } from "../traceEntries";+import { formatTokens, outputTokens } from "../toolView";+import { inspectorRows, rowCounts, type InspectorRow } from "./inspectorRows";+import { clampWidth, INSPECTOR_MAX, INSPECTOR_MIN } from "./inspectorWidth";+import "./inspector.css";++/**+ * The work inspector: the full account of one turn, one click from the+ * conversation and out of its way. A side pane with the turn's whole trace+ * as rows (the request, thoughts, replies, calls, cards, helpers), each+ * opening to what it ran and what came back. Every helper the agent started+ * gets a tab of its own with its own trace and a status dot.+ *+ * Reasoning lives here, never in the conversation. The rows come from the+ * event log, so they are the same for every runtime; a runtime that sends+ * only finished blocks shows those, and one that sends nothing live shows an+ * empty state until its turn lands.+ */+export interface WorkInspectorProps {+ turn: TurnItem;+ /** The person's message that started the turn. */+ prompt?: string;+ agentName: string;+ /** The agent's colour, the pane's one accent. */+ color: string;+ avatar?: ReactNode;+ width: number;+ onWidth: (width: number) => void;+ /** The pane floats over the conversation (a narrow window) instead of sitting beside it. */+ floating: boolean;+ onClose: () => void;+ /** Open on a helper's tab (the spawning call's id). */+ initialTab?: string;+}++const MAIN = "main";++const STATUS_DOT: Record<SubagentStatus, string> = { running: "running", done: "done", failed: "failed", stopped: "stopped" };++function turnDot(status: TurnItem["status"]): string {+ return status === "running" ? "running" : status === "error" ? "failed" : status === "cancelled" ? "stopped" : "done";+}++export const WorkInspector = memo(function WorkInspector({+ turn, prompt, agentName, color, avatar, width, onWidth, floating, onClose, initialTab,+}: WorkInspectorProps) {+ const t = useT();+ const titleId = useId();+ const helpers = useMemo(() => listSubagents([turn]), [turn]);+ const [tab, setTab] = useState(initialTab ?? MAIN);+ const active: SubagentEntry | null = tab === MAIN ? null : helpers.find((entry) => entry.id === tab) ?? null;+ // A helper that vanished (another turn opened) falls back to the main tab.+ useEffect(() => {+ if (tab !== MAIN && !helpers.some((entry) => entry.id === tab)) setTab(MAIN);+ }, [helpers, tab]);+ useEffect(() => {+ if (initialTab) setTab(initialTab);+ }, [initialTab]);++ const pane = useRef<HTMLElement | null>(null);+ // Esc closes the pane, unless someone is typing or another layer owns Esc.+ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (event.key !== "Escape" || event.defaultPrevented) return;+ const target = event.target as HTMLElement | null;+ if (target && target.closest("input, textarea, select, [contenteditable='true'], [role='dialog']")) return;+ event.preventDefault();+ onClose();+ };+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ }, [onClose]);+ // Declared first, so it sees the opener before the pane takes focus.+ // Closing hands focus back to what opened the pane (the "show work" line),+ // when focus was still in the pane and would otherwise drop to the page.+ useEffect(() => {+ const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;+ const node = pane.current;+ return () => {+ const focus = document.activeElement;+ const lost = !focus || focus === document.body || Boolean(node && node.contains(focus));+ if (lost && opener && opener.isConnected) opener.focus({ preventScroll: true });+ };+ }, []);+ // Opening moves focus into the pane, so the keyboard can read it at once.+ useEffect(() => {+ pane.current?.focus({ preventScroll: true });+ }, [turn.id]);++ const tokens = outputTokens(turn.usage ?? turn.liveUsage);+ const meta: string[] = [agentName];+ if (turn.status === "running") meta.push(t("run_view.work.working"));+ else if (turn.durationMs) meta.push(fill(t("run_view.work.worked_for"), { duration: traceDuration(turn.durationMs) }));+ if (tokens && tokens > 0) meta.push(fill(t("run_view.inspector.tokens"), { count: formatTokens(tokens) }));+ if (turn.costUsd !== null && turn.costUsd > 0) meta.push(`$${turn.costUsd.toFixed(4)}`);+ if (turn.model) meta.push(turn.model);++ return <aside ref={pane} tabIndex={-1} aria-labelledby={titleId}+ className={cn("work-inspector", floating && "is-floating")}+ style={{ width, "--agent": color } as CSSProperties}+ data-testid="work-inspector" data-turn={turn.id}>+ <ResizeEdge width={width} onWidth={onWidth} />+ <header className="wi-head">+ <span className="wi-head-mark" aria-hidden>{avatar ?? <ListTree className="h-4 w-4" />}</span>+ <div className="min-w-0 flex-1">+ <h2 id={titleId} className="wi-title">{t("run_view.inspector.title")}</h2>+ <p className="wi-meta">{meta.join(" · ")}</p>+ </div>+ <button type="button" className="wi-icon-btn" onClick={onClose} aria-label={t("run_view.inspector.close")} title={t("run_view.inspector.close")}+ data-testid="work-inspector-close">+ <X aria-hidden className="h-4 w-4" />+ </button>+ </header>+ {helpers.length > 0 ? <InspectorTabs agentName={agentName} turn={turn} helpers={helpers} tab={tab} onTab={setTab} /> : null}+ <TracePanel key={tab} turn={turn} entry={active} prompt={active ? undefined : prompt} onOpenHelper={setTab}+ label={active ? active.title : agentName} />+ </aside>;+});++/** The pane's left edge: drag it, or focus it and use the arrow keys. */+function ResizeEdge({ width, onWidth }: { width: number; onWidth: (width: number) => void }) {+ const t = useT();+ const start = useRef<{ x: number; width: number } | null>(null);+ const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {+ start.current = { x: event.clientX, width };+ event.currentTarget.setPointerCapture?.(event.pointerId);+ event.preventDefault();+ };+ const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {+ if (!start.current) return;+ onWidth(clampWidth(start.current.width + (start.current.x - event.clientX)));+ };+ const onPointerUp = () => {+ start.current = null;+ };+ const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {+ const step = event.shiftKey ? 64 : 16;+ if (event.key === "ArrowLeft") onWidth(clampWidth(width + step));+ else if (event.key === "ArrowRight") onWidth(clampWidth(width - step));+ else if (event.key === "Home") onWidth(INSPECTOR_MAX);+ else if (event.key === "End") onWidth(INSPECTOR_MIN);+ else return;+ event.preventDefault();+ };+ return <div className="wi-edge" role="separator" aria-orientation="vertical" tabIndex={0}+ aria-label={t("run_view.inspector.resize")} aria-valuemin={INSPECTOR_MIN} aria-valuemax={INSPECTOR_MAX} aria-valuenow={width}+ onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} onPointerCancel={onPointerUp}+ onKeyDown={onKeyDown} data-testid="work-inspector-edge" />;+}++function InspectorTabs({ agentName, turn, helpers, tab, onTab }: {+ agentName: string; turn: TurnItem; helpers: SubagentEntry[]; tab: string; onTab: (id: string) => void;+}) {+ const t = useT();+ const ids = [MAIN, ...helpers.map((entry) => entry.id)];+ const refs = useRef(new Map<string, HTMLButtonElement>());+ const move = (event: ReactKeyboardEvent<HTMLDivElement>) => {+ const at = ids.indexOf(tab);+ let next = -1;+ if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (at + 1) % ids.length;+ else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (at - 1 + ids.length) % ids.length;+ else if (event.key === "Home") next = 0;+ else if (event.key === "End") next = ids.length - 1;+ if (next < 0) return;+ event.preventDefault();+ onTab(ids[next]);+ refs.current.get(ids[next])?.focus();+ };+ const tabButton = (id: string, label: string, dot: string, depth = 0, kind = "") => <button key={id} type="button" role="tab"+ ref={(node) => { if (node) refs.current.set(id, node); else refs.current.delete(id); }}+ aria-selected={tab === id} tabIndex={tab === id ? 0 : -1} onClick={() => onTab(id)}+ className="wi-tab" data-depth={depth || undefined} title={label} data-testid="work-inspector-tab">+ <span className="wi-dot" data-state={dot} aria-hidden />+ {kind ? <span className="wi-tab-kind">{kind}</span> : null}+ <span className="min-w-0 truncate">{label}</span>+ <span className="sr-only">{t(`run_view.status.${dot}`)}</span>+ </button>;+ return <div role="tablist" aria-label={t("run_view.inspector.tabs")} className="wi-tabs" onKeyDown={move}>+ {tabButton(MAIN, agentName, turnDot(turn.status))}+ {helpers.map((entry) => tabButton(entry.id, entry.title, entry.waiting ? "waiting" : STATUS_DOT[entry.status], entry.depth, entry.agentType))}+ </div>;+}++function TracePanel({ turn, entry, prompt, onOpenHelper, label }: {+ turn: TurnItem; entry: SubagentEntry | null; prompt?: string; onOpenHelper: (id: string) => void;+ /** Whose trace this is, for the panel's accessible name. */+ label: string;+}) {+ const t = useT();+ const lang = t("trace_report.locale");+ const trace = useMemo(() => entry ? helperTrace(entry) : turn, [entry, turn]);+ // A helper's trace opens with the task it was given, the main one with the person's message.+ const rows = useMemo(() => inspectorRows(trace.blocks, { t, lang, status: trace.status, prompt: entry ? entry.prompt : prompt, promptLabel: entry ? "run_view.row.task" : undefined }),+ [trace, t, lang, entry, prompt]);+ const counts = rowCounts(rows);+ const [open, setOpen] = useState<Set<string>>(() => new Set());+ const allOpen = rows.length > 0 && rows.every((row) => open.has(row.id));+ const toggle = useCallback((id: string) => setOpen((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id); else next.add(id);+ return next;+ }), []);+ const { rootRef, contentRef, follow } = useStickToBottom();+ useEffect(follow, [follow, rows.length]);+ const lead = [+ counts.steps ? fill(t(`run_view.work.steps_${plural(lang, counts.steps)}`), { count: counts.steps }) : "",+ counts.thoughts ? fill(t(`run_view.inspector.thoughts_${plural(lang, counts.thoughts)}`), { count: counts.thoughts }) : "",+ counts.failed ? fill(t("run_view.inspector.failed"), { count: counts.failed }) : "",+ ].filter(Boolean).join(" · ");+ return <div className="wi-body" role="tabpanel" aria-label={label}>+ <div className="wi-toolbar">+ <span className="min-w-0 truncate">{lead}</span>+ {rows.length > 0 ? <button type="button" className="wi-text-btn" onClick={() => setOpen(allOpen ? new Set() : new Set(rows.map((row) => row.id)))}>+ {allOpen ? <ChevronsDownUp aria-hidden className="h-3.5 w-3.5" /> : <ChevronsUpDown aria-hidden className="h-3.5 w-3.5" />}+ {t(allOpen ? "run_view.inspector.collapse_all" : "run_view.inspector.expand_all")}+ </button> : null}+ </div>+ <div ref={rootRef} className="wi-scroll chat-scroller" data-testid="work-inspector-rows">+ <div ref={contentRef}>+ {rows.length === 0+ ? <p className="wi-empty">{t(trace.status === "running" ? "run_view.inspector.empty_live" : "run_view.inspector.empty")}</p>+ : <ol className="wi-rows">+ {rows.map((row) => <li key={row.id}>+ <TraceRow row={row} open={open.has(row.id)} onToggle={toggle} onOpenHelper={onOpenHelper} />+ </li>)}+ </ol>}+ </div>+ </div>+ </div>;+}++/**+ * A helper's own trace. A helper that streamed its steps but whose answer+ * arrived only in its final report still ends with that answer.+ */+function helperTrace(entry: SubagentEntry): TurnItem {+ const trace = subagentTurn(entry);+ const summary = entry.summary.trim();+ const last = [...trace.blocks].reverse().find((block) => block.kind === "text");+ if (!summary || (last && last.kind === "text" && last.text.trim() === summary)) return trace;+ return { ...trace, blocks: [...trace.blocks, { kind: "text", id: `summary:${entry.id}`, text: summary }] };+}++const KIND_ICON = {+ prompt: User,+ thought: Brain,+ reply: MessageSquareText,+ question: MessageCircleQuestion,+ approval: ShieldQuestion,+ credential: KeyRound,+ helper: Bot,+} as const;++function RowMark({ row }: { row: InspectorRow }) {+ if (row.status === "running") return <Loader2 aria-hidden className="wi-mark motion-safe:animate-spin" />;+ if (row.status === "failed") return <CircleX aria-hidden className="wi-mark" />;+ if (row.kind === "call" && row.call) return <span className="wi-mark-box"><CallMark call={row.call} /></span>;+ const Icon = row.kind === "call" ? ListTree : KIND_ICON[row.kind];+ return <Icon aria-hidden className="wi-mark" strokeWidth={1.75} />;+}++const TraceRow = memo(function TraceRow({ row, open, onToggle, onOpenHelper }: {+ row: InspectorRow; open: boolean; onToggle: (id: string) => void; onOpenHelper: (id: string) => void;+}) {+ const t = useT();+ const detailId = useId();+ return <div className="wi-row" data-kind={row.kind} data-status={row.status} data-testid="work-inspector-row">+ <button type="button" className="wi-row-btn" aria-expanded={open} aria-controls={detailId} onClick={() => onToggle(row.id)}>+ <RowMark row={row} />+ <span className={cn("wi-label", row.status === "running" && "wi-live")}>{row.label}</span>+ {row.preview ? <span className="wi-preview" title={row.preview}>{row.preview}</span> : <span className="flex-1" />}+ {row.added || row.removed ? <span className="wi-diffstat">+ {row.added ? <span className="run-diff-add">+{row.added}</span> : null}{row.added && row.removed ? " " : null}+ {row.removed ? <span className="run-diff-del">−{row.removed}</span> : null}+ </span> : null}+ {row.status === "waiting" || row.status === "declined" || row.status === "stopped"+ ? <span className="wi-state" data-state={row.status}>{t(`run_view.status.${row.status}`)}</span> : null}+ {row.durationMs && row.status !== "running" ? <span className="wi-time">{traceDuration(row.durationMs)}</span> : null}+ <ChevronRight aria-hidden className={cn("wi-chev", open && "is-open")} />+ </button>+ {open ? <div id={detailId} className="wi-detail"><RowDetail row={row} onOpenHelper={onOpenHelper} /></div> : null}+ </div>;+});++/** Very long values stay readable; the pane is not a log viewer. */+const DETAIL_CAP = 20_000;++function capped(text: string): string {+ return text.length > DETAIL_CAP ? `${text.slice(0, DETAIL_CAP)}\n…` : text;+}++function pretty(value: unknown): string {+ if (typeof value === "string") return value;+ try {+ return JSON.stringify(value, null, 2) ?? "";+ } catch {+ return String(value);+ }+}++function Section({ label, children }: { label: string; children: ReactNode }) {+ return <section className="wi-section">+ <h3 className="wi-section-label">{label}</h3>+ {children}+ </section>;+}++function Pre({ text }: { text: string }) {+ return <pre tabIndex={0} className="wi-pre">{capped(text)}</pre>;+}++function Prose({ text }: { text: string }) {+ return <div className="wi-prose prose prose-sm max-w-none dark:prose-invert [overflow-wrap:anywhere]"><ChatMarkdown text={text} /></div>;+}++function RowDetail({ row, onOpenHelper }: { row: InspectorRow; onOpenHelper: (id: string) => void }) {+ const t = useT();+ if (row.kind === "prompt" || row.kind === "reply") return <Prose text={row.text ?? ""} />;+ if (row.kind === "thought") return row.text ? <Prose text={row.text} /> : <p className="wi-note">{t("run_view.inspector.thought_private")}</p>;+ const block = row.block;+ if (!block) return <p className="wi-note">{t("run_view.inspector.no_details")}</p>;+ if (row.kind === "question") return <QuestionDetail block={block} />;+ if (row.kind === "credential") {+ const c = block.credential!;+ return <div className="wi-sections">+ <Section label={t("run_view.section.asked_for")}><p className="wi-text">{c.label || c.env}</p></Section>+ {c.description ? <p className="wi-note">{c.description}</p> : null}+ </div>;+ }+ if (row.kind === "approval") {+ return <div className="wi-sections">+ <Section label={t("run_view.section.request")}><p className="wi-text">{block.approval?.summary || block.name}</p></Section>+ <ToolSections block={block} />+ </div>;+ }+ if (row.kind === "helper") {+ const sub = block.subagent;+ const input = block.input && typeof block.input === "object" ? block.input as Record<string, unknown> : {};+ const task = sub?.prompt || (typeof input.prompt === "string" ? input.prompt : "");+ return <div className="wi-sections">+ {task ? <Section label={t("run_view.section.task")}><Prose text={task} /></Section> : null}+ {sub?.summary ? <Section label={t("run_view.section.answer")}><Prose text={sub.summary} /></Section> : null}+ <button type="button" className="wi-text-btn self-start" onClick={() => onOpenHelper(block.callId)}>+ <Bot aria-hidden className="h-3.5 w-3.5" />{t("run_view.inspector.open_helper")}+ </button>+ </div>;+ }+ return <div className="wi-sections"><ToolSections block={block} command={row.call?.kind === "command" ? row.call.text : undefined} /></div>;+}++function QuestionDetail({ block }: { block: ToolBlock }) {+ const t = useT();+ const q = block.question!;+ return <ol className="wi-qa">+ {q.questions.map((item, i) => {+ const answer = q.answers[i];+ return <li key={i}>+ <p className="wi-text">{item.question}</p>+ <p className="wi-answer">{answer ? answer.text || t("run_view.inspector.no_answer") : t("run_view.status.waiting")}</p>+ </li>;+ })}+ </ol>;+}++/** What a call ran, what it changed and what came back. */+function ToolSections({ block, command }: { block: ToolBlock; command?: string }) {+ const t = useT();+ const diff = useMemo(() => toolDiff(block.name, block.input, block.output), [block.name, block.input, block.output]);+ const output = block.output === null ? null : readableOutput(block);+ const input = block.input && typeof block.input === "object" ? block.input as Record<string, unknown> : null;+ const fullCommand = command !== undefined+ ? (typeof input?.command === "string" ? input.command : typeof input?.cmd === "string" ? input.cmd : command)+ : null;+ return <>+ <p className="wi-tool-name">{block.name}</p>+ {fullCommand !== null+ ? <Section label={t("run_view.section.command")}><Pre text={`$ ${fullCommand}`} /></Section>+ : block.input !== undefined && block.input !== null && pretty(block.input).trim() && pretty(block.input) !== "{}"+ ? <Section label={t("run_view.section.input")}><Pre text={pretty(block.input)} /></Section> : null}+ {diff ? <Section label={t("run_view.section.changes")}>+ <div className="wi-diff" tabIndex={0}>+ {diff.map((file, i) => <div key={i} className="wi-diff-file">+ <p className="wi-diff-path">+ <span className="min-w-0 truncate">{file.path}</span>+ <span className="wi-diffstat"><span className="run-diff-add">+{file.added}</span> <span className="run-diff-del">−{file.removed}</span></span>+ </p>+ {file.lines.map((line, n) => <div key={n} data-kind={line.kind}+ className={cn("wi-diff-line", line.kind === "add" && "diff-line-add", line.kind === "del" && "diff-line-del")}>+ {line.kind === "add" ? "+ " : line.kind === "del" ? "− " : line.kind === "gap" ? " ⋯ " : " "}{line.text}+ </div>)}+ {file.truncated > 0 ? <p className="wi-note">{fill(t("run_view.inspector.truncated"), { count: file.truncated })}</p> : null}+ </div>)}+ </div>+ </Section> : null}+ {output !== null+ ? <Section label={t(block.isError ? "run_view.section.error" : "run_view.section.output")}>+ {output.trim() ? <Pre text={output} /> : <p className="wi-note">{t("run_view.inspector.empty_output")}</p>}+ </Section>+ : null}+ {block.durationMs ? <p className="wi-note">{fill(t("run_view.inspector.took"), { duration: traceDuration(block.durationMs) })}</p> : null}+ </>;+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspector.css b/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspector.cssnew file mode 100644index 0000000000..ac282d232f--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspector.css@@ -0,0 +1,390 @@+/*+ * The work inspector pane. Neutral chrome from the theme ladder; the agent's+ * colour (--agent) marks only the selected tab and live rows.+ */++.work-inspector {+ --agent: hsl(var(--foreground));+ position: relative;+ display: flex;+ flex: none;+ flex-direction: column;+ min-height: 0;+ height: 100%;+ max-width: 100%;+ border-left: 1px solid hsl(var(--border));+ background: hsl(var(--card));+ color: hsl(var(--foreground));+ outline: none;+ animation: wi-in 220ms cubic-bezier(0.2, 0.8, 0.2, 1) both;+}+.work-inspector.is-floating {+ position: absolute;+ inset: 0 0 0 auto;+ z-index: 30;+ border-left-color: hsl(var(--border-strong));+ box-shadow: -16px 0 40px -12px rgb(var(--scrim-rgb) / 0.5), -1px 0 0 rgb(var(--scrim-rgb) / 0.08);+}+@keyframes wi-in {+ from { opacity: 0; transform: translateX(12px); }+ to { opacity: 1; transform: none; }+}++/* ---- resize edge ---------------------------------------------------------- */++.wi-edge {+ position: absolute;+ inset: 0 auto 0 -4px;+ z-index: 2;+ width: 8px;+ cursor: col-resize;+ touch-action: none;+}+.wi-edge::after {+ content: "";+ position: absolute;+ inset: 0 3px;+ border-radius: 2px;+ background: transparent;+ transition: background-color 150ms ease;+}+.wi-edge:hover::after,+.wi-edge:focus-visible::after {+ background: hsl(var(--border-strong));+}+.wi-edge:focus-visible { outline: none; }++/* ---- header --------------------------------------------------------------- */++.wi-head {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 12px 10px 10px 14px;+ border-bottom: 1px solid hsl(var(--border));+}+.wi-head-mark {+ display: inline-flex;+ flex: none;+ align-items: center;+ justify-content: center;+ width: 28px;+ height: 28px;+ color: hsl(var(--muted-foreground));+}+.wi-title {+ font-size: 13.5px;+ font-weight: 600;+ line-height: 18px;+}+.wi-meta {+ overflow: hidden;+ color: hsl(var(--muted-foreground));+ font-size: 12px;+ line-height: 16px;+ font-variant-numeric: tabular-nums;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.wi-icon-btn {+ display: inline-flex;+ flex: none;+ align-items: center;+ justify-content: center;+ width: 28px;+ height: 28px;+ border-radius: 8px;+ color: hsl(var(--muted-foreground));+ transition: background-color 150ms ease, color 150ms ease;+}+.wi-icon-btn:hover { background: hsl(var(--secondary)); color: hsl(var(--foreground)); }+.wi-icon-btn:focus-visible { outline: none; box-shadow: 0 0 0 2px hsl(var(--ring)); }++/* ---- tabs ----------------------------------------------------------------- */++.wi-tabs {+ display: flex;+ gap: 2px;+ overflow-x: auto;+ padding: 6px 8px 0;+ border-bottom: 1px solid hsl(var(--border));+ scrollbar-width: none;+}+.wi-tabs::-webkit-scrollbar { display: none; }+.wi-tab {+ position: relative;+ display: inline-flex;+ max-width: 220px;+ flex: none;+ align-items: center;+ gap: 6px;+ padding: 6px 10px 8px;+ border-radius: 6px 6px 0 0;+ color: hsl(var(--muted-foreground));+ font-size: 12.5px;+ line-height: 16px;+ transition: color 150ms ease, background-color 150ms ease;+}+.wi-tab[data-depth] { padding-left: 14px; }+.wi-tab:hover { color: hsl(var(--foreground)); background: hsl(var(--secondary)); }+.wi-tab:focus-visible { outline: none; box-shadow: inset 0 0 0 2px hsl(var(--ring)); }+.wi-tab[aria-selected="true"] { color: hsl(var(--foreground)); font-weight: 500; }+.wi-tab[aria-selected="true"]::after {+ content: "";+ position: absolute;+ inset: auto 8px -1px;+ height: 2px;+ border-radius: 2px;+ background: var(--agent);+}+.wi-tab-kind {+ flex: none;+ padding: 0 5px;+ border-radius: 6px;+ background: hsl(var(--secondary));+ color: hsl(var(--muted-foreground));+ font-size: 11px;+}+.wi-dot {+ flex: none;+ width: 7px;+ height: 7px;+ border-radius: 999px;+ background: hsl(var(--muted-foreground));+}+.wi-dot[data-state="running"] {+ background: var(--agent);+ box-shadow: 0 0 0 0 var(--agent);+ animation: wi-dot-pulse 1.6s ease-in-out infinite;+}+.wi-dot[data-state="done"] { background: hsl(var(--success)); }+.wi-dot[data-state="failed"] { background: hsl(var(--destructive)); }+.wi-dot[data-state="waiting"] { background: hsl(var(--warning)); }+.wi-dot[data-state="stopped"] { background: hsl(var(--border-strong)); }+@keyframes wi-dot-pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.45; }+}++/* ---- body ----------------------------------------------------------------- */++.wi-body {+ display: flex;+ flex: 1;+ flex-direction: column;+ min-height: 0;+}+.wi-toolbar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ min-height: 34px;+ padding: 6px 10px 4px 14px;+ color: hsl(var(--muted-foreground));+ font-size: 12px;+ line-height: 16px;+ font-variant-numeric: tabular-nums;+}+.wi-text-btn {+ display: inline-flex;+ flex: none;+ align-items: center;+ gap: 5px;+ padding: 3px 7px;+ border-radius: 6px;+ color: hsl(var(--muted-foreground));+ font-size: 12px;+ line-height: 16px;+ transition: background-color 150ms ease, color 150ms ease;+}+.wi-text-btn:hover { background: hsl(var(--secondary)); color: hsl(var(--foreground)); }+.wi-text-btn:focus-visible { outline: none; box-shadow: 0 0 0 2px hsl(var(--ring)); }+.wi-scroll {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ padding: 2px 6px 16px;+}+.wi-empty {+ padding: 28px 16px;+ color: hsl(var(--muted-foreground));+ font-size: 13px;+ line-height: 20px;+ text-align: center;+}+.wi-rows { display: flex; flex-direction: column; }+.wi-rows > li { content-visibility: auto; contain-intrinsic-size: auto 32px; }++/* ---- rows ----------------------------------------------------------------- */++.wi-row-btn {+ display: flex;+ width: 100%;+ min-width: 0;+ min-height: 32px;+ align-items: center;+ gap: 8px;+ padding: 6px 8px;+ border-radius: 8px;+ text-align: left;+ font-size: 13px;+ line-height: 18px;+ transition: background-color 100ms ease;+}+.wi-row-btn:hover { background: hsl(var(--secondary)); }+.wi-row-btn:focus-visible { outline: none; box-shadow: inset 0 0 0 2px hsl(var(--ring)); }+.wi-row-btn[aria-expanded="true"] { background: hsl(var(--secondary)); }+.wi-mark {+ width: 16px;+ height: 16px;+ flex: none;+ color: hsl(var(--muted-foreground));+}+.wi-mark-box { display: inline-flex; flex: none; color: hsl(var(--muted-foreground)); }+.wi-row[data-kind="thought"] .wi-mark { color: hsl(var(--viz-reasoning)); }+.wi-row[data-kind="question"] .wi-mark,+.wi-row[data-kind="approval"] .wi-mark,+.wi-row[data-kind="credential"] .wi-mark { color: hsl(var(--warning)); }+.wi-row[data-status="failed"] .wi-mark { color: hsl(var(--destructive)); }+.wi-row[data-status="running"] .wi-mark { color: var(--agent); }+.wi-label {+ flex: none;+ max-width: 60%;+ overflow: hidden;+ color: hsl(var(--foreground-secondary));+ text-overflow: ellipsis;+ white-space: nowrap;+}+.wi-row[data-kind="call"] .wi-label { font-family: inherit; }+.wi-live {+ background-image: linear-gradient(+ 90deg,+ hsl(var(--foreground-secondary)) 0%,+ hsl(var(--foreground-secondary)) 36%,+ hsl(var(--foreground-strong)) 50%,+ hsl(var(--foreground-secondary)) 64%,+ hsl(var(--foreground-secondary)) 100%+ );+ background-size: 250% 100%;+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ animation: wi-sweep 2.6s linear infinite;+}+.wi-preview {+ min-width: 0;+ flex: 1;+ overflow: hidden;+ color: hsl(var(--muted-foreground));+ text-overflow: ellipsis;+ white-space: nowrap;+}+.wi-diffstat,+.wi-time {+ flex: none;+ color: hsl(var(--muted-foreground));+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ font-size: 11.5px;+ font-variant-numeric: tabular-nums;+}+.wi-state {+ flex: none;+ padding: 0 6px;+ border-radius: 6px;+ background: hsl(var(--secondary));+ color: hsl(var(--muted-foreground));+ font-size: 11px;+ line-height: 16px;+}+.wi-state[data-state="waiting"] { color: hsl(var(--warning)); }+.wi-chev {+ width: 14px;+ height: 14px;+ flex: none;+ color: hsl(var(--muted-foreground));+ opacity: 0.5;+ transition: transform 150ms ease, opacity 150ms ease;+}+.wi-row-btn:hover .wi-chev { opacity: 0.9; }+.wi-chev.is-open { transform: rotate(90deg); opacity: 0.9; }++/* ---- detail --------------------------------------------------------------- */++.wi-detail {+ margin: 2px 0 8px 15px;+ padding: 6px 4px 4px 17px;+ border-left: 1px solid hsl(var(--border));+ animation: wi-detail-in 160ms ease-out both;+}+@keyframes wi-detail-in {+ from { opacity: 0; transform: translateY(-2px); }+ to { opacity: 1; transform: none; }+}+.wi-sections { display: flex; flex-direction: column; gap: 10px; }+.wi-section-label {+ margin-bottom: 4px;+ color: hsl(var(--muted-foreground));+ font-size: 11px;+ font-weight: 500;+ letter-spacing: 0.02em;+ line-height: 14px;+ text-transform: uppercase;+}+.wi-tool-name {+ color: hsl(var(--muted-foreground));+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ font-size: 11.5px;+ overflow-wrap: anywhere;+}+.wi-pre,+.wi-diff {+ max-height: 18rem;+ overflow: auto;+ padding: 8px 10px;+ border-radius: 10px;+ background: hsl(var(--surface-raised));+ color: hsl(var(--foreground-secondary));+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ font-size: 12px;+ line-height: 18px;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+}+.wi-pre:focus-visible,+.wi-diff:focus-visible { outline: none; box-shadow: 0 0 0 1px hsl(var(--ring)); }+.wi-diff-file + .wi-diff-file { margin-top: 10px; }+.wi-diff-path {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ margin-bottom: 4px;+ color: hsl(var(--foreground));+}+.wi-diff-line { white-space: pre-wrap; }+.wi-diff-line[data-kind="gap"] { color: hsl(var(--muted-foreground)); }+.wi-prose { font-size: 13px; line-height: 20px; }+.wi-prose > :first-child { margin-top: 0; }+.wi-prose > :last-child { margin-bottom: 0; }+.wi-text { font-size: 13px; line-height: 19px; overflow-wrap: anywhere; }+.wi-note { color: hsl(var(--muted-foreground)); font-size: 12px; line-height: 17px; }+.wi-qa { display: flex; flex-direction: column; gap: 8px; }+.wi-answer {+ margin-top: 2px;+ color: hsl(var(--muted-foreground));+ font-size: 12.5px;+ line-height: 18px;+}+.wi-answer::before { content: "→ "; }++@media (prefers-reduced-motion: reduce) {+ .work-inspector, .wi-detail { animation: none; }+ .wi-dot[data-state="running"] { animation: none; }+ .wi-live { animation: none; background-image: none; color: hsl(var(--foreground)); }+ .wi-chev, .wi-row-btn, .wi-edge::after { transition: none; }+}+@keyframes wi-sweep {+ from { background-position: 100% 0; }+ to { background-position: -150% 0; }+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspectorRows.ts b/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspectorRows.tsnew file mode 100644index 0000000000..c73e3753ea--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspectorRows.ts@@ -0,0 +1,174 @@+/**+ * The work inspector's rows: a turn's whole trace, one row per thing that+ * happened, in order. Where the conversation shows only messages and the+ * activity line, this is the full account: the request, every thought (with+ * its words when the provider shares them), every reply, every call with+ * what it ran and what came back, every card the agent showed the person,+ * and every helper it started (which opens that helper's own tab).+ *+ * Pure: blocks in, rows out. The same rows come from every runtime, because+ * every runtime writes the same event vocabulary. A runtime that streams+ * nothing (only finished blocks) simply has fewer, finished rows.+ */++import { isSubagentCall } from "@/components/agentic/threads/subagents";+import type { ReasoningBlock, TextBlock, ToolBlock, TurnBlock, TurnStatus } from "../reduce";+import { callOf, isPlumbing, readableOutput, type Call, type Translate } from "../traceEntries";++export type RowKind = "prompt" | "thought" | "reply" | "call" | "question" | "approval" | "credential" | "helper";+export type RowStatus = "running" | "done" | "failed" | "waiting" | "stopped" | "declined";++export interface InspectorRow {+ id: string;+ kind: RowKind;+ status: RowStatus;+ /** The row's words (translated or the call's own line). */+ label: string;+ /** A dimmed first line, at most PREVIEW_MAX characters. */+ preview: string;+ added: number;+ removed: number;+ durationMs: number | null;+ /** The call behind a call, card or helper row. */+ block?: ToolBlock;+ /** The trace model's view of a call row (its kind drives the mark). */+ call?: Call;+ /** The full text of a prompt, thought or reply. */+ text?: string;+}++export const PREVIEW_MAX = 80;++/** First meaningful line, markdown marks dropped, capped. */+export function previewOf(text: string, max = PREVIEW_MAX): string {+ const line = text+ .replace(/```[\s\S]*?```/g, " ")+ .split(/\r?\n/)+ .map((part) => part.replace(/^[#>*\-\s]+/, "").replace(/[`*_~]/g, "").trim())+ .find(Boolean) ?? "";+ const clean = line.replace(/\s+/g, " ");+ return clean.length > max ? `${clean.slice(0, max - 1).trimEnd()}…` : clean;+}++export interface RowOptions {+ t: Translate;+ lang: string;+ status: TurnStatus;+ /** The person's message that started the turn, shown first. */+ prompt?: string;+ /** The first row's label key, when the trace starts with something else (a helper's task). */+ promptLabel?: string;+}++function thoughtRow(block: ReasoningBlock, turn: TurnStatus, t: Translate): InspectorRow {+ const text = block.text.trim();+ const running = turn === "running" && block.live;+ return {+ id: block.id, kind: "thought", status: running ? "running" : "done",+ label: t(text ? "run_view.row.thought" : "run_view.row.thought_hidden"),+ preview: previewOf(text), added: 0, removed: 0, durationMs: block.durationMs, text,+ };+}++function replyRow(block: TextBlock, t: Translate): InspectorRow {+ return {+ id: block.id, kind: "reply", status: "done", label: t("run_view.row.reply"),+ preview: previewOf(block.text), added: 0, removed: 0, durationMs: null, text: block.text,+ };+}++function cardRow(block: ToolBlock, turn: TurnStatus, t: Translate): InspectorRow {+ const base = { id: block.callId, added: 0, removed: 0, durationMs: block.durationMs, block };+ if (block.question) {+ const q = block.question;+ const first = q.questions[0]?.question ?? "";+ return { ...base, kind: "question", status: q.closed ? "done" : turn === "running" || q.deferred ? "waiting" : "stopped",+ label: t("run_view.row.question"), preview: previewOf(first) };+ }+ if (block.credential) {+ const c = block.credential;+ const status: RowStatus = c.status === null ? "waiting" : c.status === "saved" ? "done" : "declined";+ return { ...base, kind: "credential", status, label: t("run_view.row.credential"), preview: previewOf(c.label || c.env) };+ }+ const decision = block.approval?.decision ?? null;+ const status: RowStatus = decision === null ? "waiting" : decision === "deny" || decision === "cancel" || decision === "expired" ? "declined" : "done";+ return { ...base, kind: "approval", status, label: t("run_view.row.approval"), preview: previewOf(block.approval?.summary || block.name) };+}++function helperRow(block: ToolBlock, turn: TurnStatus, t: Translate): InspectorRow {+ const sub = block.subagent;+ const input = block.input && typeof block.input === "object" ? block.input as Record<string, unknown> : {};+ const title = sub?.description || (typeof input.description === "string" ? input.description : "")+ || previewOf(sub?.prompt || (typeof input.prompt === "string" ? input.prompt : ""));+ const reported = sub?.status;+ const status: RowStatus = reported === "running" ? "running" : reported === "failed" ? "failed" : reported === "stopped" ? "stopped"+ : reported === "done" ? "done"+ : block.output === null ? (turn === "running" ? "running" : "stopped") : block.isError ? "failed" : "done";+ return {+ id: block.callId, kind: "helper", status, label: t("run_view.row.helper"), preview: previewOf(title),+ added: 0, removed: 0, durationMs: sub?.durationMs ?? block.durationMs, block,+ };+}++const CALL_STATUS: Record<Call["status"], RowStatus> = {+ running: "running", done: "done", failed: "failed", blocked: "failed", declined: "declined", interrupted: "stopped",+};++function callRow(block: ToolBlock, turn: TurnStatus, t: Translate, lang: string): InspectorRow {+ const call = callOf(block, turn, t, lang);+ const tail = call.detail || call.result || (call.status === "failed" || call.status === "blocked" ? call.reason : "");+ return {+ id: block.callId, kind: "call", status: CALL_STATUS[call.status], label: call.text,+ preview: previewOf(tail || (call.kind === "command" ? "" : readableOutput(block))),+ added: call.added, removed: call.removed, durationMs: block.durationMs, block, call,+ };+}++/** The rows of one trace (a turn's blocks, or a helper's). */+export function inspectorRows(blocks: readonly TurnBlock[], options: RowOptions): InspectorRow[] {+ const { t, lang, status, prompt, promptLabel = "run_view.row.prompt" } = options;+ const rows: InspectorRow[] = [];+ if (prompt && prompt.trim()) {+ rows.push({ id: "prompt", kind: "prompt", status: "done", label: t(promptLabel), preview: previewOf(prompt),+ added: 0, removed: 0, durationMs: null, text: prompt });+ }+ for (const block of blocks) {+ if (block.kind === "reasoning") {+ rows.push(thoughtRow(block, status, t));+ continue;+ }+ if (block.kind === "text") {+ if (block.text.trim()) rows.push(replyRow(block, t));+ continue;+ }+ if (isPlumbing(block)) continue;+ if (block.question || block.credential || block.approval) {+ // A decided approval reads as the call it guarded, with how it was decided.+ if (!block.question && !block.credential && block.approval && block.approval.decision !== null && block.output !== null) {+ rows.push(callRow(block, status, t, lang));+ continue;+ }+ rows.push(cardRow(block, status, t));+ continue;+ }+ if (isSubagentCall(block)) {+ rows.push(helperRow(block, status, t));+ continue;+ }+ rows.push(callRow(block, status, t, lang));+ }+ return rows;+}++/** Counts for the inspector's header line. */+export function rowCounts(rows: readonly InspectorRow[]): { steps: number; thoughts: number; failed: number } {+ let steps = 0;+ let thoughts = 0;+ let failed = 0;+ for (const row of rows) {+ if (row.kind === "thought") thoughts += 1;+ else if (row.kind !== "prompt" && row.kind !== "reply") steps += 1;+ if (row.status === "failed") failed += 1;+ }+ return { steps, thoughts, failed };+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspectorWidth.ts b/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspectorWidth.tsnew file mode 100644index 0000000000..8bed959d06--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspectorWidth.ts@@ -0,0 +1,36 @@+/** The work inspector's width: chosen by dragging its edge, kept per viewer. */++export const INSPECTOR_MIN = 320;+export const INSPECTOR_MAX = 760;+export const INSPECTOR_DEFAULT = 420;+/** The conversation keeps at least this much beside the open inspector, or the inspector floats over it. */+export const CHAT_KEEP = 440;++const KEY = "dodaios.runView.inspectorWidth";++export function clampWidth(width: number, room = Number.POSITIVE_INFINITY): number {+ const max = Math.max(INSPECTOR_MIN, Math.min(INSPECTOR_MAX, room));+ return Math.round(Math.min(max, Math.max(INSPECTOR_MIN, width)));+}++export function readInspectorWidth(): number {+ try {+ const raw = Number(window.localStorage.getItem(KEY));+ return Number.isFinite(raw) && raw > 0 ? clampWidth(raw) : INSPECTOR_DEFAULT;+ } catch {+ return INSPECTOR_DEFAULT;+ }+}++export function writeInspectorWidth(width: number): void {+ try {+ window.localStorage.setItem(KEY, String(clampWidth(width)));+ } catch {+ // Private windows and blocked storage keep the width for this session only.+ }+}++/** Side by side when the pane leaves the chat its room; otherwise it floats over the chat. */+export function inspectorDocked(containerWidth: number, width: number): boolean {+ return containerWidth - width >= CHAT_KEEP;+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/traceEntries.ts b/dodaios/ui/web/frontend/src/components/agentchat/traceEntries.tsindex 844547a103..1047f80dcf 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/traceEntries.ts+++ b/dodaios/ui/web/frontend/src/components/agentchat/traceEntries.ts@@ -146,7 +146,7 @@ export function shortPath(path: string): string {}/** Plumbing calls draw nothing: loading a tool's schema, polling a question card. */-function isPlumbing(block: ToolBlock): boolean {+export function isPlumbing(block: ToolBlock): boolean {if (isQuestionTool(block.name) && !block.question) return true;if (isCredentialTool(block.name) && !block.credential && !block.isError) return true;if (block.name.replace(/^mcp__[^_]+__/, "") === "ToolSearch") {@@ -318,7 +318,7 @@ export function ownServerTool(name: string): string | null {}/** One finished or running call as its line. */-function callOf(block: ToolBlock, turn: TurnStatus, t: Translate, lang: string): Call {+export function callOf(block: ToolBlock, turn: TurnStatus, t: Translate, lang: string): Call {const view = traceToolIdentity(block);const record = inputRecord(block);const { status, reason } = statusOf(block, turn, t);diff --git a/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsxindex d9fc7987a8..3e9a2e19af 100644--- a/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx+++ b/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx@@ -65,7 +65,6 @@ import { AwaitingTurn, MessengerTurn, type MemoryLink } from "@/components/agentimport { VoiceStage } from "@/components/home/VoiceStage";import { ProviderLogo } from "@/components/providers/ProviderLogo";import { fill, useT } from "@/i18n";-import { useRunLocale } from "@/components/runs/format";import { cn } from "@/lib/utils";import { societyDisplayName } from "@/lib/societyDisplayName";import { createAgentChatStore, useAgentChatStore, type AgentChatStoreHook } from "@/store/agentChat";@@ -96,9 +95,18 @@ import {mentionsInText,type MentionItem,} from "./mentionItems";--/** A gap this long between messages earns a fresh time stamp. */-const STAMP_GAP_MS = 30 * 60_000;+import { stampPlan, type StampEntry } from "@/components/agentchat/activity/transcriptTime";+import { CatchUpPill, RunAnnouncer, SettleBox, TranscriptStamp, useFarFromEnd, useUnseen } from "@/components/agentchat/activity/TranscriptAids";+import { WorkInspector } from "@/components/agentchat/inspector/WorkInspector";+import { inspectorDocked, readInspectorWidth, writeInspectorWidth } from "@/components/agentchat/inspector/inspectorWidth";++/** Who spoke an item, for time stamps that never split one speaker's run. */+function stampEntry(item: TimelineItem): StampEntry {+ const ts = item.type === "turn" ? item.startedMs : item.tsMs;+ const author = item.type === "turn" ? "agent" : item.type === "user" ? "person" : item.type;+ const end = item.type === "turn" && item.durationMs ? item.startedMs + item.durationMs : undefined;+ return { id: item.id, ts, end, author };+}/*** Messages use the full conversation lane; each bubble limits its own prose@@ -711,6 +719,61 @@ export function Transcript({// watches the content's own size too, so growth follows; scrolled up, the// reader keeps their place and gets a button back.const { rootRef, contentRef, atEnd, jumpToEnd, follow } = useStickToBottom();+ // The scroller itself too: past 80 px from the end it offers the way back.+ const [scroller, setScroller] = useState<HTMLElement | null>(null);+ const setRoot = useCallback((node: HTMLDivElement | null) => {+ rootRef(node);+ setScroller(node);+ }, [rootRef]);+ const far = useFarFromEnd(scroller);+ const unseen = useUnseen(items, atEnd);+ // A stamp marks a pause of 15 minutes or a new day, before a speaker's run.+ const stamps = useMemo(() => stampPlan(items.map(stampEntry)), [items]);+ const assistantName = useEventStore((state) => state.assistantName);+ // "Writing to Scout": a teammate by the name and face a person knows.+ const memberOf = useCallback((value: string) => {+ const key = value.trim().toLowerCase();+ return roster.find((a) => a.agentId === value || a.name.toLowerCase() === key);+ }, [roster]);+ const nameOf = useCallback((value: string) => {+ const member = memberOf(value);+ return member ? societyDisplayName(member, assistantName) : value;+ }, [memberOf, assistantName]);+ const peerFace = useCallback((value: string) => {+ const member = memberOf(value);+ return member ? <AgentSwatch agent={{ ...member, state: undefined }} size={16} /> : null;+ }, [memberOf]);+ // The work inspector: one turn's whole trace beside the conversation.+ const [inspecting, setInspecting] = useState<string | null>(null);+ const inspectedAt = inspecting ? items.findIndex((item) => item.type === "turn" && item.id === inspecting) : -1;+ const inspected = inspectedAt >= 0 ? items[inspectedAt] as TurnItem : null;+ const inspectedPrompt = useMemo(() => {+ for (let i = inspectedAt - 1; i >= 0; i--) {+ const item = items[i];+ if (item.type === "user") return visibleUserText(item.text);+ if (item.type === "turn") break;+ }+ return undefined;+ }, [items, inspectedAt]);+ const [inspectorWidth, setInspectorWidth] = useState(readInspectorWidth);+ const onInspectorWidth = useCallback((width: number) => {+ setInspectorWidth(width);+ writeInspectorWidth(width);+ }, []);+ const closeInspector = useCallback(() => setInspecting(null), []);+ const [frame, setFrame] = useState<HTMLDivElement | null>(null);+ const [frameWidth, setFrameWidth] = useState(0);+ // Measured only while the inspector is open: a closed one costs nothing.+ const inspectorOpen = inspected !== null;+ useEffect(() => {+ if (!frame || !inspectorOpen) return;+ setFrameWidth(frame.clientWidth);+ if (typeof ResizeObserver === "undefined") return;+ const ro = new ResizeObserver(() => setFrameWidth(frame.clientWidth));+ ro.observe(frame);+ return () => ro.disconnect();+ }, [frame, inspectorOpen]);+ const docked = frameWidth > 0 && inspectorDocked(frameWidth, inspectorWidth);// The person's bubbles wear the colour of the agent they talk to.const tint = useMemo(() => bubbleTint(agentColor(agent)), [agent]);// `items` itself, not its length: a reasoning trace or tool row grows@@ -732,59 +795,63 @@ export function Transcript({);}- let lastStamp = 0;+ const displayName = societyDisplayName(agent, assistantName);return (- <div className="relative flex min-h-0 flex-1 flex-col">- <div ref={rootRef} className="chat-scroller min-h-0 flex-1 overflow-y-auto px-4 py-5 sm:px-6" data-testid="society-transcript">- <div ref={contentRef} className={cn(CHAT_MEASURE, "flex flex-col gap-3")}>- {items.map((item) => {- const ts = item.type === "turn" ? item.startedMs : item.tsMs;- const stamp = ts && ts - lastStamp > STAMP_GAP_MS ? ts : 0;- if (stamp) lastStamp = ts;- return (- <div key={item.id} data-chat-item={item.id} className="flex flex-col gap-2">- {stamp ? <TimeStamp ms={stamp} /> : null}- {item.type === "internal" ? (- <AgentMessageActivity item={item} roster={roster} />- ) : item.type === "user" && assignmentOf(item.text) ? (- <DelegationActivity {...assignmentOf(item.text)!} roster={roster} />- ) : item.type === "user" && item.teamEvent ? (- <TeamEventLine event={item.teamEvent} text={item.text} />- ) : item.type === "user" ? (- <UserBubble item={item} agentId={agent.agentId} sessionId={sessionId ?? agent.chatSessionId ?? undefined} tint={tint} />- ) : item.type === "turn" ? (- <TurnBubble item={item} agent={agent} memory={memoryByTurn.get(item.id)} onDecide={onDecide} />- ) : item.type === "notice" ? (- item.kind === "proposal" ? (- <ProposalCard item={item} />- ) : (- <NoticeLine item={item} />- )+ <div ref={setFrame} className="relative flex min-h-0 flex-1">+ <div className="relative flex min-h-0 min-w-0 flex-1 flex-col">+ <div ref={setRoot} className="chat-scroller min-h-0 flex-1 overflow-y-auto px-4 py-5 sm:px-6" data-testid="society-transcript">+ <div ref={contentRef} className={cn(CHAT_MEASURE, "flex flex-col gap-3")}>+ {items.map((item, index) => {+ const stamp = stamps.has(item.id) ? (item.type === "turn" ? item.startedMs : item.tsMs) : 0;+ // The live turn glides to its new height as it grows.+ const live = index === items.length - 1 && item.type === "turn" && item.status === "running";+ const body = item.type === "internal" ? (+ <AgentMessageActivity item={item} roster={roster} />+ ) : item.type === "user" && assignmentOf(item.text) ? (+ <DelegationActivity {...assignmentOf(item.text)!} roster={roster} />+ ) : item.type === "user" && item.teamEvent ? (+ <TeamEventLine event={item.teamEvent} text={item.text} />+ ) : item.type === "user" ? (+ <UserBubble item={item} agentId={agent.agentId} sessionId={sessionId ?? agent.chatSessionId ?? undefined} tint={tint} />+ ) : item.type === "turn" ? (+ <TurnBubble item={item} agent={agent} memory={memoryByTurn.get(item.id)} onDecide={onDecide}+ nameOf={nameOf} peerFace={peerFace} workOpen={inspecting === item.id} onShowWork={setInspecting} />+ ) : item.type === "notice" ? (+ item.kind === "proposal" ? (+ <ProposalCard item={item} />) : (- <p className="self-start rounded-2xl bg-destructive/10 px-3 py-2 text-xs text-destructive">{item.text}</p>- )}- </div>- );- })}- {awaiting ? <AwaitingTurn since={awaiting.tsMs} seed={awaiting.id}- avatar={<AgentSwatch agent={{ ...agent, state: undefined }} size={28} expressive />} color={agentColor(agent)} /> : null}+ <NoticeLine item={item} />+ )+ ) : (+ <p className="self-start rounded-2xl bg-destructive/10 px-3 py-2 text-xs text-destructive">{item.text}</p>+ );+ return (+ <div key={item.id} data-chat-item={item.id} className="flex flex-col gap-2">+ {stamp ? <TranscriptStamp ms={stamp} /> : null}+ {/* A turn always sits in its settle box, so finishing (or a+ notice arriving after it) never remounts it mid-flight. */}+ {item.type === "turn" ? <SettleBox active={live}>{body}</SettleBox> : body}+ </div>+ );+ })}+ {awaiting ? <AwaitingTurn since={awaiting.tsMs} seed={awaiting.id}+ avatar={<AgentSwatch agent={{ ...agent, state: undefined }} size={28} expressive />} color={agentColor(agent)} /> : null}+ </div></div>+ {/* Scrolled up: what arrived meanwhile, else simply the way back. */}+ {!atEnd && unseen.count > 0+ ? <CatchUpPill count={unseen.count} onJump={jumpToEnd} onDismiss={unseen.dismiss} />+ : !atEnd && far ? <ScrollToEndButton onClick={jumpToEnd} testId="society-scroll-end" className="top-auto bottom-3" /> : null}+ <RunAnnouncer items={items} agentName={displayName} /></div>- {!atEnd && <ScrollToEndButton onClick={jumpToEnd} testId="society-scroll-end" className="top-auto bottom-3" />}+ {inspected ? <WorkInspector turn={inspected} prompt={inspectedPrompt} agentName={displayName}+ color={agentColor(agent)} avatar={<AgentSwatch agent={{ ...agent, state: undefined }} size={24} />}+ width={docked || frameWidth === 0 ? inspectorWidth : Math.min(inspectorWidth, Math.max(280, frameWidth - 24))}+ onWidth={onInspectorWidth} floating={!docked} onClose={closeInspector} /> : null}</div>);}-function TimeStamp({ ms }: { ms: number }) {- const t = useT();- const locale = useRunLocale();- const date = new Date(ms);- const today = new Date().toDateString() === date.toDateString();- const time = date.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit" });- const day = today ? t("society.chat.today") : date.toLocaleDateString(locale, { day: "2-digit", month: "short" });- return <p className="my-4 text-center text-[11px] text-muted-foreground">{`${day} ${time}`}</p>;-}-/*** A delegated task coming back: the agent's name as the headline, its* summary underneath, muted — it is the society reporting, not Jarvis@@ -1074,11 +1141,20 @@ function TurnBubble({agent,memory,onDecide,+ nameOf,+ peerFace,+ workOpen,+ onShowWork,}: {item: TurnItem;agent: SocietyAgent;memory?: NoticeItem[];onDecide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;+ nameOf?: (idOrName: string) => string;+ peerFace?: (peer: string) => ReactNode;+ workOpen?: boolean;+ /** Opens the work inspector on a turn (by its id). */+ onShowWork?: (turnId: string) => void;}) {const t = useT();const [openId, setOpenId] = useState<string | null>(null);@@ -1090,12 +1166,15 @@ function TurnBubble({[memory, t],);const opened = openId ? memory?.find((notice) => notice.id === openId) : undefined;+ const face = useMemo(() => <AgentSwatch agent={{ ...agent, state: undefined }} size={28} expressive />, [agent]);+ const showWork = useMemo(() => onShowWork ? () => onShowWork(item.id) : undefined, [onShowWork, item.id]);// An agent's turn reads like a messenger: its messages, what it changed,// and while it works its face with a word for what it is doing.// The face stays a face: the effect beside it says what it is doing, so// the swatch's own "working" dots would only repeat it.return <>- <MessengerTurn turn={item} avatar={<AgentSwatch agent={{ ...agent, state: undefined }} size={28} expressive />} color={agentColor(agent)} onDecide={onDecide} memoryLinks={memoryLinks} />+ <MessengerTurn turn={item} avatar={face} color={agentColor(agent)} onDecide={onDecide} memoryLinks={memoryLinks}+ nameOf={nameOf} peerFace={peerFace} onShowWork={showWork} workOpen={workOpen} />{opened && <MemoryNoticeViewer item={opened} onClose={() => setOpenId(null)} />}</>;}diff --git a/dodaios/ui/web/frontend/src/components/society/chat/TranscriptRunView.test.tsx b/dodaios/ui/web/frontend/src/components/society/chat/TranscriptRunView.test.tsxnew file mode 100644index 0000000000..04b8fcd1da--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/chat/TranscriptRunView.test.tsx@@ -0,0 +1,142 @@+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { Transcript } from "@/components/society/chat/AgentChatPanel";+import { EMPTY_TIMELINE, reduceEvents } from "@/components/agentchat/reduce";+import type { AgentChatEvent } from "@/lib/agentChatApi";+import type { SocietyAgent } from "@/components/society/data";++/**+ * The society transcript's run view: time stamps that mark a pause, a+ * "N new" pill for a reader who scrolled up, and the work inspector one+ * click from each turn.+ */++const agent = { agentId: "a1", name: "Scout", tier: "worker" } as unknown as SocietyAgent;+const MIN = 60_000;+const BASE = new Date(2026, 9, 26, 9, 0).getTime();++let seq = 0;+function ev(kind: string, payload: Record<string, unknown>, ts: number): AgentChatEvent {+ seq += 1;+ return { seq, ts_ms: ts, kind, payload } as AgentChatEvent;+}++function exchange(n: number, at: number): AgentChatEvent[] {+ const id = `t${n}`;+ return [+ ev("user_message", { text: `question ${n}` }, at),+ ev("turn_started", { turn_id: id, provider: "openai", runner: "brain" }, at + 1_000),+ ev("tool_call", { turn_id: id, call_id: `c${n}`, name: "Read", input: { file_path: `f${n}.ts` } }, at + 2_000),+ ev("tool_result", { turn_id: id, call_id: `c${n}`, output: "ok", is_error: false }, at + 3_000),+ ev("assistant_text", { turn_id: id, message_id: `m${n}`, text: `answer ${n}` }, at + 4_000),+ ev("turn_finished", { turn_id: id, status: "done", duration_ms: 3_000 }, at + 5_000),+ ];+}++function draw(events: AgentChatEvent[]) {+ const { items } = reduceEvents(EMPTY_TIMELINE, events);+ return render(<Transcript items={items} agent={agent} roster={[]} onDecide={async () => {}} />);+}++function measure(el: HTMLElement, scrollTop: number, scrollHeight: number, clientHeight: number) {+ Object.defineProperty(el, "scrollHeight", { value: scrollHeight, configurable: true });+ Object.defineProperty(el, "clientHeight", { value: clientHeight, configurable: true });+ el.scrollTop = scrollTop;+}++afterEach(() => {+ cleanup();+ seq = 0;+ vi.useRealTimers();+});++describe("transcript time stamps", () => {+ it("stamps the start and every pause of 15 minutes, never inside a reply", () => {+ draw([...exchange(1, BASE), ...exchange(2, BASE + 5 * MIN), ...exchange(3, BASE + 30 * MIN)]);+ const stamps = screen.getAllByTestId("transcript-stamp");+ expect(stamps).toHaveLength(2);+ expect(stamps[0].querySelector("time")?.getAttribute("datetime")).toBe(new Date(BASE).toISOString());+ });+});++describe("catch-up pill", () => {+ it("counts what arrived while the reader was scrolled up, and dismisses", () => {+ const first = exchange(1, BASE);+ const { rerender } = draw(first);+ const el = screen.getByTestId("society-transcript");+ measure(el, 100, 2_000, 400);+ act(() => { fireEvent.scroll(el); });+ // Away from the end with nothing new: just the way back.+ expect(screen.getByTestId("society-scroll-end")).toBeTruthy();+ const more = reduceEvents(EMPTY_TIMELINE, [...first, ...exchange(2, BASE + MIN)]).items;+ rerender(<Transcript items={more} agent={agent} roster={[]} onDecide={async () => {}} />);+ const pill = screen.getByTestId("transcript-new-pill");+ expect(pill.textContent).toContain("2 new messages");+ expect(screen.queryByTestId("society-scroll-end")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));+ expect(screen.queryByTestId("transcript-new-pill")).toBeNull();+ expect(screen.getByTestId("society-scroll-end")).toBeTruthy();+ });++ it("offers no way back within 80 px of the end", () => {+ draw(exchange(1, BASE));+ const el = screen.getByTestId("society-transcript");+ measure(el, 1_525, 2_000, 400);+ act(() => { fireEvent.scroll(el); });+ expect(screen.queryByTestId("society-scroll-end")).toBeNull();+ });+});++describe("work inspector from the chat", () => {+ it("opens a turn's work beside the conversation and closes again", () => {+ draw(exchange(1, BASE));+ expect(screen.queryByTestId("work-inspector")).toBeNull();+ fireEvent.click(screen.getByTestId("work-disclosure"));+ const pane = screen.getByTestId("work-inspector");+ expect(pane.dataset.turn).toBe("t1");+ // The request that started the turn leads its trace.+ expect(screen.getAllByTestId("work-inspector-row")[0].dataset.kind).toBe("prompt");+ fireEvent.click(screen.getByTestId("work-inspector-close"));+ expect(screen.queryByTestId("work-inspector")).toBeNull();+ });+});++describe("announcer", () => {+ it("says when the agent replies, not what was already there", () => {+ const start = [+ ev("user_message", { text: "hi" }, BASE),+ ev("turn_started", { turn_id: "t1", provider: "openai" }, BASE + 1),+ ];+ const { rerender } = draw(start);+ expect(screen.getByTestId("run-announcer").textContent).toBe("");+ const done = reduceEvents(EMPTY_TIMELINE, [+ ...start,+ ev("assistant_text", { turn_id: "t1", message_id: "m1", text: "Hello!" }, BASE + 2),+ ev("turn_finished", { turn_id: "t1", status: "done", duration_ms: 10 }, BASE + 3),+ ]).items;+ rerender(<Transcript items={done} agent={agent} roster={[]} onDecide={async () => {}} />);+ expect(screen.getByTestId("run-announcer").textContent).toBe("Scout replied.");+ });+});++describe("live turn", () => {+ it("keeps the same turn mounted when it finishes, so the done flourish can play", () => {+ const start = [+ ev("user_message", { text: "hi" }, BASE),+ ev("turn_started", { turn_id: "t1", provider: "openai" }, BASE + 1),+ ev("assistant_text", { turn_id: "t1", message_id: "m1", text: "Hello!" }, BASE + 2),+ ];+ const { rerender } = draw(start);+ const running = screen.getByTestId("messenger-turn");+ expect(running.dataset.status).toBe("running");+ const done = reduceEvents(EMPTY_TIMELINE, [+ ...start,+ ev("turn_finished", { turn_id: "t1", status: "done", duration_ms: 10 }, BASE + 3),+ ]).items;+ rerender(<Transcript items={done} agent={agent} roster={[]} onDecide={async () => {}} />);+ const finished = screen.getByTestId("messenger-turn");+ expect(finished).toBe(running);+ expect(finished.dataset.status).toBe("done");+ });+});diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.jsonindex 7ac20b0b87..f0d62581f2 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json@@ -10226,5 +10226,130 @@"label": "Gebaut von {name}","title": "{name} hat das von sich aus gebaut. Zum Bau öffnen.","trial": "auf Probe"+ },+ "run_view": {+ "phrase": {+ "thinking_0": "Denkt nach",+ "thinking_1": "Plant den nächsten Schritt",+ "thinking_2": "Wägt ab",+ "thinking_3": "Fügt die Teile zusammen",+ "composing": "Schreibt zurück",+ "search_web": "Sucht im Netz",+ "search_web_for": "Sucht nach „{target}“",+ "search_files": "Durchsucht das Projekt",+ "search_for": "Sucht nach „{target}“",+ "read_page": "Liest eine Seite auf {target}",+ "read_any": "Öffnet eine Datei",+ "read_file": "Öffnet {target}",+ "view_image": "Sieht sich ein Bild an",+ "list_folder": "Sieht {target} durch",+ "edit_file": "Bearbeitet {target}",+ "write_file": "Schreibt {target}",+ "write_any": "Schreibt eine Datei",+ "run_cmd": "Führt {target} aus",+ "run_any": "Arbeitet im Terminal",+ "browse_site": "Auf {target}",+ "browse_any": "Im Browser",+ "recall": "Schaut in die eigenen Notizen",+ "note": "Macht sich eine Notiz",+ "message": "Schreibt an {target}",+ "message_any": "Schreibt einem Teammitglied",+ "delegate": "Weist einen Helfer ein: {target}",+ "delegate_any": "Ein Helfer ist dran",+ "delegate_many": "{target} Helfer arbeiten",+ "connect": "Arbeitet in {target}",+ "setup": "Richtet etwas ein",+ "waiting": "Braucht deine Antwort",+ "waiting_approval": "Braucht dein OK",+ "working_0": "Ist dran",+ "working_1": "Kommt voran",+ "working_2": "Arbeitet es durch"+ },+ "timer": {+ "min": "{count} Min.",+ "hour": "{hours} Std. {minutes} Min."+ },+ "work": {+ "working": "Arbeitet",+ "worked_for": "Hat {duration} gearbeitet",+ "stopped_after": "Nach {duration} gestoppt",+ "failed_after": "Nach {duration} mit einem Fehler beendet",+ "steps_one": "{count} Schritt",+ "steps_other": "{count} Schritte",+ "files_one": "{count} Datei",+ "files_other": "{count} Dateien",+ "helpers_one": "{count} Helfer",+ "helpers_other": "{count} Helfer",+ "open": "Arbeit anzeigen"+ },+ "inspector": {+ "title": "Arbeitsverlauf",+ "close": "Arbeitsverlauf schließen",+ "resize": "Breite des Arbeitsverlaufs ändern",+ "tabs": "Wer daran gearbeitet hat",+ "tokens": "{count} Tokens",+ "thoughts_one": "{count} Gedanke",+ "thoughts_other": "{count} Gedanken",+ "failed": "{count} fehlgeschlagen",+ "expand_all": "Alle öffnen",+ "collapse_all": "Alle schließen",+ "empty": "Für diesen Durchgang wurde nichts aufgezeichnet.",+ "empty_live": "Schritte erscheinen hier, sobald der Agent sie macht.",+ "thought_private": "Der Anbieter hält den Wortlaut dieses Gedankens privat.",+ "no_details": "Es wurden keine Details aufgezeichnet.",+ "open_helper": "Verlauf des Helfers öffnen",+ "no_answer": "Keine Antwort",+ "truncated": "{count} weitere Zeilen nicht angezeigt",+ "empty_output": "Es kam nichts zurück.",+ "took": "Dauerte {duration}"+ },+ "row": {+ "prompt": "Deine Nachricht",+ "task": "Aufgabe",+ "thought": "Gedanke",+ "thought_hidden": "Gedanke (privat)",+ "reply": "Antwort",+ "question": "Hat dich gefragt",+ "credential": "Hat nach Zugangsdaten gefragt",+ "approval": "Hat um dein OK gebeten",+ "helper": "Helfer"+ },+ "status": {+ "running": "Läuft",+ "done": "Fertig",+ "failed": "Fehlgeschlagen",+ "stopped": "Gestoppt",+ "waiting": "Wartet auf dich",+ "declined": "Abgelehnt"+ },+ "section": {+ "asked_for": "Gefragt nach",+ "request": "Anfrage",+ "task": "Aufgabe",+ "answer": "Antwort",+ "command": "Befehl",+ "input": "Eingabe",+ "changes": "Änderungen",+ "output": "Ausgabe",+ "error": "Fehler"+ },+ "announce": {+ "started": "{agent} hat angefangen zu arbeiten.",+ "replied": "{agent} hat geantwortet.",+ "finished": "{agent} ist fertig.",+ "stopped": "{agent} hat gestoppt.",+ "failed": "{agent} ist auf ein Problem gestoßen.",+ "asked": "{agent} fragt: {question}",+ "needs_ok": "{agent} braucht dein OK."+ },+ "time": {+ "today": "Heute {time}",+ "yesterday": "Gestern {time}"+ },+ "pill": {+ "new_one": "{count} neue Nachricht",+ "new_other": "{count} neue Nachrichten",+ "dismiss": "Ausblenden"+ }}}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.jsonindex 4b2865ac66..39890201ab 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json@@ -10226,5 +10226,130 @@"label": "Built by {name}","title": "{name} built this on its own. Open its build.","trial": "on trial"+ },+ "run_view": {+ "phrase": {+ "thinking_0": "Thinking",+ "thinking_1": "Planning the next step",+ "thinking_2": "Weighing it up",+ "thinking_3": "Connecting the dots",+ "composing": "Writing back",+ "search_web": "Looking it up online",+ "search_web_for": "Looking up “{target}”",+ "search_files": "Searching the project",+ "search_for": "Searching for “{target}”",+ "read_page": "Reading a page on {target}",+ "read_any": "Opening a file",+ "read_file": "Opening {target}",+ "view_image": "Looking at an image",+ "list_folder": "Looking through {target}",+ "edit_file": "Editing {target}",+ "write_file": "Writing {target}",+ "write_any": "Writing a file",+ "run_cmd": "Running {target}",+ "run_any": "At the terminal",+ "browse_site": "On {target}",+ "browse_any": "In the browser",+ "recall": "Checking its notes",+ "note": "Making a note",+ "message": "Writing to {target}",+ "message_any": "Writing to a teammate",+ "delegate": "Briefing a helper: {target}",+ "delegate_any": "A helper is on it",+ "delegate_many": "{target} helpers at work",+ "connect": "Working in {target}",+ "setup": "Setting things up",+ "waiting": "Needs your answer",+ "waiting_approval": "Needs your OK",+ "working_0": "On it",+ "working_1": "Making progress",+ "working_2": "Working through it"+ },+ "timer": {+ "min": "{count} min",+ "hour": "{hours} h {minutes} min"+ },+ "work": {+ "working": "Working",+ "worked_for": "Worked for {duration}",+ "stopped_after": "Stopped after {duration}",+ "failed_after": "Ended with an error after {duration}",+ "steps_one": "{count} step",+ "steps_other": "{count} steps",+ "files_one": "{count} file",+ "files_other": "{count} files",+ "helpers_one": "{count} helper",+ "helpers_other": "{count} helpers",+ "open": "Show the work"+ },+ "inspector": {+ "title": "Work trace",+ "close": "Close the work trace",+ "resize": "Resize the work trace",+ "tabs": "Who worked on this",+ "tokens": "{count} tokens",+ "thoughts_one": "{count} thought",+ "thoughts_other": "{count} thoughts",+ "failed": "{count} failed",+ "expand_all": "Open all",+ "collapse_all": "Close all",+ "empty": "Nothing was recorded for this turn.",+ "empty_live": "Steps show up here as soon as the agent takes them.",+ "thought_private": "The provider keeps the words of this thought private.",+ "no_details": "No details were recorded.",+ "open_helper": "Open the helper's trace",+ "no_answer": "No answer",+ "truncated": "{count} more lines not shown",+ "empty_output": "It returned nothing.",+ "took": "Took {duration}"+ },+ "row": {+ "prompt": "Your message",+ "task": "Task",+ "thought": "Thought",+ "thought_hidden": "Thought (private)",+ "reply": "Reply",+ "question": "Asked you",+ "credential": "Asked for a credential",+ "approval": "Asked for your OK",+ "helper": "Helper"+ },+ "status": {+ "running": "Running",+ "done": "Done",+ "failed": "Failed",+ "stopped": "Stopped",+ "waiting": "Waiting for you",+ "declined": "Declined"+ },+ "section": {+ "asked_for": "Asked for",+ "request": "Request",+ "task": "Task",+ "answer": "Answer",+ "command": "Command",+ "input": "Input",+ "changes": "Changes",+ "output": "Output",+ "error": "Error"+ },+ "announce": {+ "started": "{agent} started working.",+ "replied": "{agent} replied.",+ "finished": "{agent} finished.",+ "stopped": "{agent} stopped.",+ "failed": "{agent} ran into a problem.",+ "asked": "{agent} asks: {question}",+ "needs_ok": "{agent} needs your OK."+ },+ "time": {+ "today": "Today {time}",+ "yesterday": "Yesterday {time}"+ },+ "pill": {+ "new_one": "{count} new message",+ "new_other": "{count} new messages",+ "dismiss": "Dismiss"+ }}}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.jsonindex a5ae28e838..12e39e1ef4 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json@@ -10226,5 +10226,130 @@"label": "Hecho por {name}","title": "{name} lo construyó por su cuenta. Abrir su construcción.","trial": "en prueba"+ },+ "run_view": {+ "phrase": {+ "thinking_0": "Pensando",+ "thinking_1": "Planeando el siguiente paso",+ "thinking_2": "Sopesándolo",+ "thinking_3": "Atando cabos",+ "composing": "Respondiendo",+ "search_web": "Buscando en internet",+ "search_web_for": "Buscando «{target}»",+ "search_files": "Buscando en el proyecto",+ "search_for": "Buscando «{target}»",+ "read_page": "Leyendo una página de {target}",+ "read_any": "Abriendo un archivo",+ "read_file": "Abriendo {target}",+ "view_image": "Mirando una imagen",+ "list_folder": "Revisando {target}",+ "edit_file": "Editando {target}",+ "write_file": "Escribiendo {target}",+ "write_any": "Escribiendo un archivo",+ "run_cmd": "Ejecutando {target}",+ "run_any": "En la terminal",+ "browse_site": "En {target}",+ "browse_any": "En el navegador",+ "recall": "Revisando sus notas",+ "note": "Tomando una nota",+ "message": "Escribiendo a {target}",+ "message_any": "Escribiendo a un compañero",+ "delegate": "Preparando a un ayudante: {target}",+ "delegate_any": "Un ayudante se encarga",+ "delegate_many": "{target} ayudantes trabajando",+ "connect": "Trabajando en {target}",+ "setup": "Preparando todo",+ "waiting": "Necesita tu respuesta",+ "waiting_approval": "Necesita tu visto bueno",+ "working_0": "En ello",+ "working_1": "Avanzando",+ "working_2": "Resolviéndolo"+ },+ "timer": {+ "min": "{count} min",+ "hour": "{hours} h {minutes} min"+ },+ "work": {+ "working": "Trabajando",+ "worked_for": "Trabajó {duration}",+ "stopped_after": "Detenido tras {duration}",+ "failed_after": "Terminó con un error tras {duration}",+ "steps_one": "{count} paso",+ "steps_other": "{count} pasos",+ "files_one": "{count} archivo",+ "files_other": "{count} archivos",+ "helpers_one": "{count} ayudante",+ "helpers_other": "{count} ayudantes",+ "open": "Ver el trabajo"+ },+ "inspector": {+ "title": "Registro de trabajo",+ "close": "Cerrar el registro de trabajo",+ "resize": "Cambiar el ancho del registro de trabajo",+ "tabs": "Quién trabajó en esto",+ "tokens": "{count} tokens",+ "thoughts_one": "{count} pensamiento",+ "thoughts_other": "{count} pensamientos",+ "failed": "{count} fallidos",+ "expand_all": "Abrir todo",+ "collapse_all": "Cerrar todo",+ "empty": "No se registró nada en este turno.",+ "empty_live": "Los pasos aparecen aquí en cuanto el agente los da.",+ "thought_private": "El proveedor mantiene en privado el texto de este pensamiento.",+ "no_details": "No se registraron detalles.",+ "open_helper": "Abrir el registro del ayudante",+ "no_answer": "Sin respuesta",+ "truncated": "{count} líneas más sin mostrar",+ "empty_output": "No devolvió nada.",+ "took": "Tardó {duration}"+ },+ "row": {+ "prompt": "Tu mensaje",+ "task": "Tarea",+ "thought": "Pensamiento",+ "thought_hidden": "Pensamiento (privado)",+ "reply": "Respuesta",+ "question": "Te preguntó",+ "credential": "Pidió una credencial",+ "approval": "Pidió tu visto bueno",+ "helper": "Ayudante"+ },+ "status": {+ "running": "En curso",+ "done": "Hecho",+ "failed": "Falló",+ "stopped": "Detenido",+ "waiting": "Te espera",+ "declined": "Rechazado"+ },+ "section": {+ "asked_for": "Pidió",+ "request": "Solicitud",+ "task": "Tarea",+ "answer": "Respuesta",+ "command": "Comando",+ "input": "Entrada",+ "changes": "Cambios",+ "output": "Salida",+ "error": "Error"+ },+ "announce": {+ "started": "{agent} empezó a trabajar.",+ "replied": "{agent} respondió.",+ "finished": "{agent} terminó.",+ "stopped": "{agent} se detuvo.",+ "failed": "{agent} tuvo un problema.",+ "asked": "{agent} pregunta: {question}",+ "needs_ok": "{agent} necesita tu visto bueno."+ },+ "time": {+ "today": "Hoy {time}",+ "yesterday": "Ayer {time}"+ },+ "pill": {+ "new_one": "{count} mensaje nuevo",+ "new_other": "{count} mensajes nuevos",+ "dismiss": "Descartar"+ }}}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.jsonindex ee91adbcc0..089f67ed80 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json@@ -10226,5 +10226,130 @@"label": "Feito por {name}","title": "{name} construiu isto por iniciativa própria. Abrir a construção.","trial": "em ensaio"+ },+ "run_view": {+ "phrase": {+ "thinking_0": "Pensando",+ "thinking_1": "Planejando o próximo passo",+ "thinking_2": "Pesando as opções",+ "thinking_3": "Ligando os pontos",+ "composing": "Respondendo",+ "search_web": "Pesquisando na internet",+ "search_web_for": "Pesquisando “{target}”",+ "search_files": "Procurando no projeto",+ "search_for": "Procurando “{target}”",+ "read_page": "Lendo uma página em {target}",+ "read_any": "Abrindo um arquivo",+ "read_file": "Abrindo {target}",+ "view_image": "Olhando uma imagem",+ "list_folder": "Revendo {target}",+ "edit_file": "Editando {target}",+ "write_file": "Escrevendo {target}",+ "write_any": "Escrevendo um arquivo",+ "run_cmd": "Executando {target}",+ "run_any": "No terminal",+ "browse_site": "Em {target}",+ "browse_any": "No navegador",+ "recall": "Consultando as próprias notas",+ "note": "Fazendo uma anotação",+ "message": "Escrevendo para {target}",+ "message_any": "Escrevendo para um colega",+ "delegate": "Orientando um ajudante: {target}",+ "delegate_any": "Um ajudante está cuidando disso",+ "delegate_many": "{target} ajudantes trabalhando",+ "connect": "Trabalhando com {target}",+ "setup": "Preparando tudo",+ "waiting": "Precisa da sua resposta",+ "waiting_approval": "Precisa do seu OK",+ "working_0": "Cuidando disso",+ "working_1": "Avançando",+ "working_2": "Resolvendo"+ },+ "timer": {+ "min": "{count} min",+ "hour": "{hours} h {minutes} min"+ },+ "work": {+ "working": "Trabalhando",+ "worked_for": "Trabalhou por {duration}",+ "stopped_after": "Parou após {duration}",+ "failed_after": "Terminou com um erro após {duration}",+ "steps_one": "{count} passo",+ "steps_other": "{count} passos",+ "files_one": "{count} arquivo",+ "files_other": "{count} arquivos",+ "helpers_one": "{count} ajudante",+ "helpers_other": "{count} ajudantes",+ "open": "Ver o trabalho"+ },+ "inspector": {+ "title": "Registro de trabalho",+ "close": "Fechar o registro de trabalho",+ "resize": "Mudar a largura do registro de trabalho",+ "tabs": "Quem trabalhou nisso",+ "tokens": "{count} tokens",+ "thoughts_one": "{count} pensamento",+ "thoughts_other": "{count} pensamentos",+ "failed": "{count} com falha",+ "expand_all": "Abrir tudo",+ "collapse_all": "Fechar tudo",+ "empty": "Nada foi registrado neste turno.",+ "empty_live": "Os passos aparecem aqui assim que o agente os dá.",+ "thought_private": "O provedor mantém o texto deste pensamento privado.",+ "no_details": "Nenhum detalhe foi registrado.",+ "open_helper": "Abrir o registro do ajudante",+ "no_answer": "Sem resposta",+ "truncated": "Mais {count} linhas não exibidas",+ "empty_output": "Não retornou nada.",+ "took": "Levou {duration}"+ },+ "row": {+ "prompt": "Sua mensagem",+ "task": "Tarefa",+ "thought": "Pensamento",+ "thought_hidden": "Pensamento (privado)",+ "reply": "Resposta",+ "question": "Perguntou a você",+ "credential": "Pediu uma credencial",+ "approval": "Pediu seu OK",+ "helper": "Ajudante"+ },+ "status": {+ "running": "Em andamento",+ "done": "Concluído",+ "failed": "Falhou",+ "stopped": "Parado",+ "waiting": "Aguardando você",+ "declined": "Recusado"+ },+ "section": {+ "asked_for": "Pediu",+ "request": "Pedido",+ "task": "Tarefa",+ "answer": "Resposta",+ "command": "Comando",+ "input": "Entrada",+ "changes": "Alterações",+ "output": "Saída",+ "error": "Erro"+ },+ "announce": {+ "started": "{agent} começou a trabalhar.",+ "replied": "{agent} respondeu.",+ "finished": "{agent} terminou.",+ "stopped": "{agent} parou.",+ "failed": "{agent} encontrou um problema.",+ "asked": "{agent} pergunta: {question}",+ "needs_ok": "{agent} precisa do seu OK."+ },+ "time": {+ "today": "Hoje {time}",+ "yesterday": "Ontem {time}"+ },+ "pill": {+ "new_one": "{count} nova mensagem",+ "new_other": "{count} novas mensagens",+ "dismiss": "Dispensar"+ }}}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.jsonindex 2001abd86f..89c2d221d6 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json@@ -10226,5 +10226,130 @@"label": "由 {name} 构建","title": "{name} 主动构建了它。打开它的构建记录。","trial": "试用中"+ },+ "run_view": {+ "phrase": {+ "thinking_0": "正在思考",+ "thinking_1": "正在规划下一步",+ "thinking_2": "正在权衡",+ "thinking_3": "正在理清头绪",+ "composing": "正在回复",+ "search_web": "正在网上查找",+ "search_web_for": "正在查找“{target}”",+ "search_files": "正在搜索项目",+ "search_for": "正在搜索“{target}”",+ "read_page": "正在阅读 {target} 上的页面",+ "read_any": "正在打开文件",+ "read_file": "正在打开 {target}",+ "view_image": "正在查看图片",+ "list_folder": "正在浏览 {target}",+ "edit_file": "正在编辑 {target}",+ "write_file": "正在写入 {target}",+ "write_any": "正在写入文件",+ "run_cmd": "正在运行 {target}",+ "run_any": "正在使用终端",+ "browse_site": "正在访问 {target}",+ "browse_any": "正在使用浏览器",+ "recall": "正在翻看自己的笔记",+ "note": "正在记笔记",+ "message": "正在给 {target} 写消息",+ "message_any": "正在给队友写消息",+ "delegate": "正在安排助手:{target}",+ "delegate_any": "助手正在处理",+ "delegate_many": "{target} 个助手在工作",+ "connect": "正在使用 {target}",+ "setup": "正在进行设置",+ "waiting": "需要你的回答",+ "waiting_approval": "需要你的同意",+ "working_0": "正在处理",+ "working_1": "正在推进",+ "working_2": "正在逐步完成"+ },+ "timer": {+ "min": "{count} 分钟",+ "hour": "{hours} 小时 {minutes} 分钟"+ },+ "work": {+ "working": "工作中",+ "worked_for": "工作了 {duration}",+ "stopped_after": "{duration} 后停止",+ "failed_after": "{duration} 后因错误结束",+ "steps_one": "{count} 个步骤",+ "steps_other": "{count} 个步骤",+ "files_one": "{count} 个文件",+ "files_other": "{count} 个文件",+ "helpers_one": "{count} 个助手",+ "helpers_other": "{count} 个助手",+ "open": "查看工作过程"+ },+ "inspector": {+ "title": "工作记录",+ "close": "关闭工作记录",+ "resize": "调整工作记录宽度",+ "tabs": "参与这项工作的成员",+ "tokens": "{count} 个 token",+ "thoughts_one": "{count} 次思考",+ "thoughts_other": "{count} 次思考",+ "failed": "{count} 个失败",+ "expand_all": "全部展开",+ "collapse_all": "全部收起",+ "empty": "这一轮没有记录任何内容。",+ "empty_live": "智能体一开始行动,步骤就会显示在这里。",+ "thought_private": "提供方不公开这次思考的具体内容。",+ "no_details": "没有记录详细信息。",+ "open_helper": "打开助手的工作记录",+ "no_answer": "没有回答",+ "truncated": "还有 {count} 行未显示",+ "empty_output": "没有返回任何内容。",+ "took": "耗时 {duration}"+ },+ "row": {+ "prompt": "你的消息",+ "task": "任务",+ "thought": "思考",+ "thought_hidden": "思考(未公开)",+ "reply": "回复",+ "question": "向你提问",+ "credential": "请求凭据",+ "approval": "请求你的同意",+ "helper": "助手"+ },+ "status": {+ "running": "进行中",+ "done": "完成",+ "failed": "失败",+ "stopped": "已停止",+ "waiting": "等待你",+ "declined": "已拒绝"+ },+ "section": {+ "asked_for": "请求内容",+ "request": "请求",+ "task": "任务",+ "answer": "回答",+ "command": "命令",+ "input": "输入",+ "changes": "改动",+ "output": "输出",+ "error": "错误"+ },+ "announce": {+ "started": "{agent} 开始工作了。",+ "replied": "{agent} 已回复。",+ "finished": "{agent} 已完成。",+ "stopped": "{agent} 已停止。",+ "failed": "{agent} 遇到了问题。",+ "asked": "{agent} 提问:{question}",+ "needs_ok": "{agent} 需要你的同意。"+ },+ "time": {+ "today": "今天 {time}",+ "yesterday": "昨天 {time}"+ },+ "pill": {+ "new_one": "{count} 条新消息",+ "new_other": "{count} 条新消息",+ "dismiss": "关闭"+ }}}diff --git a/dodaios/ui/web/frontend/src/i18n/run-view-i18n-parity.test.ts b/dodaios/ui/web/frontend/src/i18n/run-view-i18n-parity.test.tsnew file mode 100644index 0000000000..8d0ef96a09--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/run-view-i18n-parity.test.ts@@ -0,0 +1,73 @@+/**+ * The run view (activity line, work inspector, transcript aids) speaks from+ * one `run_view.*` block. Every key its sources ask for must exist in en, and+ * every locale must carry exactly en's keys with the same placeholders, so a+ * phrase added without its translations fails here, not in front of a person.+ */+import { readFileSync, readdirSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import en from "./locales/en.json";+import de from "./locales/de.json";+import es from "./locales/es.json";+import pt from "./locales/pt.json";+import zh from "./locales/zh.json";+import { VARIANTS } from "@/components/agentchat/activity/activityModel";++type Tree = Record<string, unknown>;++function flatten(obj: Tree, prefix = ""): Map<string, string> {+ const out = new Map<string, string>();+ for (const [k, v] of Object.entries(obj)) {+ const key = prefix ? `${prefix}.${k}` : k;+ if (v && typeof v === "object" && !Array.isArray(v)) for (const [kk, vv] of flatten(v as Tree, key)) out.set(kk, vv);+ else out.set(key, String(v));+ }+ return out;+}++const block = (loc: Tree) => flatten((loc.run_view ?? {}) as Tree, "run_view");+const placeholders = (text: string) => [...text.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort();++const SRC = join(__dirname, "..");+const DIRS = [+ join(SRC, "components", "agentchat", "activity"),+ join(SRC, "components", "agentchat", "inspector"),+];+const FILES = [+ ...DIRS.flatMap((dir) => readdirSync(dir).filter((f) => /\.tsx?$/.test(f) && !/\.test\./.test(f)).map((f) => join(dir, f))),+ join(SRC, "components", "society", "chat", "AgentChatPanel.tsx"),+];++describe("run_view i18n", () => {+ const base = block(en as Tree);++ it("has every literal key the sources use", () => {+ const missing: string[] = [];+ for (const file of FILES) {+ for (const m of readFileSync(file, "utf8").matchAll(/"(run_view\.[a-z0-9_.]+)"/g)) {+ if (!base.has(m[1])) missing.push(`${m[1]} (${file})`);+ }+ }+ expect(missing).toEqual([]);+ });++ it("has every phrasing variant of the generic families", () => {+ for (const [phrase, count] of Object.entries(VARIANTS)) {+ for (let i = 0; i < (count ?? 0); i++) expect(base.has(`run_view.phrase.${phrase}_${i}`)).toBe(true);+ }+ });++ it.each([["de", de], ["es", es], ["pt", pt], ["zh", zh]] as const)("%s carries exactly en's keys and placeholders", (_lang, loc) => {+ const other = block(loc as Tree);+ expect([...other.keys()].sort()).toEqual([...base.keys()].sort());+ for (const [key, text] of base) expect(placeholders(other.get(key) ?? "")).toEqual(placeholders(text));+ });++ it("never uses the assistant-name token and German keeps its umlauts", () => {+ for (const text of base.values()) expect(text).not.toContain("{name}");+ const german = [...block(de as Tree).values()].join(" ");+ expect(german).not.toMatch(/\b(fuer|ueber|schliessen|Aenderungen|naechsten)\b/);+ expect(german).toMatch(/[äöüß]/);+ });+});