Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(deck): a log terminal and a response instrument replace the trace and the screen mirror; captures fade

Haraldffc4a08a724f
diff --git a/jarvis/screen_context/service.py b/jarvis/screen_context/service.py
index 976216053f..484acc705e 100644
--- a/jarvis/screen_context/service.py
+++ b/jarvis/screen_context/service.py
@@ -617,8 +617,13 @@ class ScreenContextService:
"image was discarded. Ask again to use the new settings."
),
)
- await self._publish_completed(context, trace_id=event_trace_id)
+ # Mirror BEFORE the receipt goes out: the deck fetches the picture
+ # the moment ``ScreenCaptureCompleted`` reaches it, and the bus
+ # awaits that WebSocket send — mirroring afterwards let the deck
+ # find no frame (or the previous one) for the capture it was just
+ # told about.
self._mirror_for_deck(context, trace_id=event_trace_id)
+ await self._publish_completed(context, trace_id=event_trace_id)
log.info("screen_context: %s", context.describe())
return CaptureOutcome(
status="captured",
diff --git a/jarvis/ui/web/frontend/src/components/deck/DeckActivityCards.tsx b/jarvis/ui/web/frontend/src/components/deck/DeckActivityCards.tsx
index 9c81fb32e2..a81f9c1fbe 100644
--- a/jarvis/ui/web/frontend/src/components/deck/DeckActivityCards.tsx
+++ b/jarvis/ui/web/frontend/src/components/deck/DeckActivityCards.tsx
@@ -1,7 +1,6 @@
import { useEffect, useMemo, useRef } from "react";
import { useQuery } from "@tanstack/react-query";
import {
- Activity,
FolderOpen,
Gauge,
MessagesSquare,
@@ -13,7 +12,6 @@ import { useRuns } from "@/hooks/useRuns";
import { useOutputsList, type OutputSummary } from "@/hooks/useOutputs";
import { fetchIdeState, fetchTerminalActivity, type IdeState, type ActivityResponse } from "@/lib/agenticIdeApi";
import { useCommandActivityStore } from "@/store/commandActivity";
-import type { ThinkingStep } from "@/lib/thinkingSteps";
import type { RunListItem } from "@/components/runs/types";
import { DeckCard } from "@/components/deck/DeckCard";
import { cn } from "@/lib/utils";
@@ -25,88 +23,6 @@ import { useT } from "@/i18n";
* nothing to show says so in one line rather than inventing a placeholder.
*/
-// ----------------------------------------------------------------------
-// Ablauf — what the assistant is doing right now (the reasoning trace)
-// ----------------------------------------------------------------------
-
-const STEP_BADGE: Record<string, string> = {
- brain: "bg-primary text-primary-foreground",
- tool: "bg-sky-400 text-black",
- computer: "bg-violet-400 text-black",
- worker: "bg-emerald-400 text-black",
- note: "bg-muted text-muted-foreground",
-};
-
-export function FlowCard({ steps, className }: { steps: ThinkingStep[]; className?: string }) {
- const t = useT();
- const setActiveSection = useEventStore((s) => s.setActiveSection);
- const active = steps.filter((s) => s.status === "active").length;
- const shown = [...steps].reverse();
-
- return (
- <DeckCard
- icon={Activity}
- title={t("deck.card_flow")}
- meta={active > 0 ? active : undefined}
- live={active > 0}
- variant="rail"
- onOpen={() => setActiveSection("run_inspector")}
- openLabel={t("deck.open_section")}
- className={className}
- bodyClassName="overflow-y-auto"
- >
- {shown.length === 0 ? (
- <p className="text-[11px] text-muted-foreground">{t("deck.running_empty")}</p>
- ) : (
- <ul className="space-y-1">
- {shown.slice(0, 14).map((step) => (
- <li
- key={step.id}
- className={cn(
- "border-l px-2 py-0.5",
- step.status === "active"
- ? "border-primary"
- : step.status === "error"
- ? "border-destructive"
- : "border-border",
- )}
- >
- <div className="flex items-center gap-1.5">
- <span
- className={cn(
- "shrink-0 px-1 py-px font-mono text-[9px] uppercase tracking-wider",
- STEP_BADGE[step.kind] ?? STEP_BADGE.note,
- )}
- >
- {step.kind}
- </span>
- <span
- className={cn(
- "flex-1 truncate text-[11px]",
- step.status === "active" ? "text-foreground" : "text-muted-foreground",
- )}
- >
- {t(step.labelKey)}
- </span>
- {step.durationMs !== undefined && (
- <span className="shrink-0 font-mono text-[9px] tabular-nums text-muted-foreground">
- {(step.durationMs / 1000).toFixed(1)}s
- </span>
- )}
- </div>
- {step.detail && (
- <div className="truncate pl-1 font-mono text-[10px] text-muted-foreground">
- {step.detail}
- </div>
- )}
- </li>
- ))}
- </ul>
- )}
- </DeckCard>
- );
-}
-
// ----------------------------------------------------------------------
// Runs — the run inspector's list, newest first
// ----------------------------------------------------------------------
diff --git a/jarvis/ui/web/frontend/src/components/deck/DeckLogAndTurn.test.tsx b/jarvis/ui/web/frontend/src/components/deck/DeckLogAndTurn.test.tsx
new file mode 100644
index 0000000000..3b440088aa
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/deck/DeckLogAndTurn.test.tsx
@@ -0,0 +1,150 @@
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import { LogCard } from "@/components/deck/DeckLogCard";
+import { TurnCard } from "@/components/deck/DeckTurnCard";
+import { CaptureCard, CAPTURE_AFTERGLOW_MS } from "@/components/deck/DeckSignalCards";
+import { emptyDeckState, reduceDeck, type DeckState } from "@/lib/deckState";
+import { useDeckStore } from "@/store/deck";
+import { useEventStore } from "@/store/events";
+
+/**
+ * The three cards that replaced the "right now" trace, the live screen
+ * mirror and the lingering capture on the front page (2026-08-18). Rendered
+ * against a store fed with the same events the reducer tests use, so what
+ * is asserted here is what a person sees for a real turn.
+ */
+
+function feed(events: Array<[string, unknown]>, start: DeckState = emptyDeckState(), from = 10_000): DeckState {
+ let s = start;
+ let ts = from;
+ for (const [name, payload] of events) s = reduceDeck(s, name, payload, (ts += 250));
+ return s;
+}
+
+const VOICE_TURN: Array<[string, unknown]> = [
+ ["WakeWordDetected", { keyword: "nova", confidence: 0.91 }],
+ ["TranscriptFinal", { transcript: { text: "wie spät ist es" } }],
+ ["LatencySpan", { phase: "stt_finalize", duration_ms: 380 }],
+ ["BrainTurnStarted", { provider: "openrouter", model: "claude-sonnet-5" }],
+ ["LatencySpan", { phase: "brain_first_token", duration_ms: 1300 }],
+ ["ActionProposed", { tool_name: "get_time" }],
+ ["ActionExecuted", { tool_name: "get_time", success: true, duration_ms: 84 }],
+ ["BrainTurnCompleted", { tokens_in: 1200, tokens_out: 88, cost_usd: 0.0031 }],
+ ["SpeechSpoken", { text: "Es ist 14:47.", spoken_kind: "reply" }],
+ ["LatencySpan", { phase: "turn_to_first_audio", duration_ms: 1900 }],
+];
+
+describe("LogCard", () => {
+ beforeEach(() => {
+ useDeckStore.getState().resetDeck();
+ useEventStore.setState({ connected: true, voiceReady: true, wsWarming: false, voiceState: "idle" });
+ });
+ afterEach(() => cleanup());
+
+ test("shows the cursor line even before anything happened", () => {
+ render(<LogCard />);
+ expect(screen.getByText("listening for the wake word")).toBeTruthy();
+ });
+
+ test("prints one line per thing heard, thought, done and said, with durations", () => {
+ useDeckStore.setState(feed(VOICE_TURN));
+ render(<LogCard />);
+ expect(screen.getByText("wake word")).toBeTruthy();
+ expect(screen.getByText("“wie spät ist es”")).toBeTruthy();
+ expect(screen.getByText("openrouter · claude-sonnet-5")).toBeTruthy();
+ expect(screen.getByText("get_time")).toBeTruthy();
+ expect(screen.getByText(/84 ms/)).toBeTruthy();
+ expect(screen.getByText("1.20k in · 88 out · $0.0031")).toBeTruthy();
+ expect(screen.getByText("“Es ist 14:47.”")).toBeTruthy();
+ expect(screen.getByText("first audio")).toBeTruthy();
+ expect(screen.getByText(/1\.9 s/)).toBeTruthy();
+ // The turn is over (speech spoken, brain done): the cursor is quiet again
+ // — but the card is still on, with a lit "say" tag among the rows.
+ expect(screen.getAllByText("say").length).toBeGreaterThan(0);
+ });
+
+ test("the title opens the sessions section", () => {
+ render(<LogCard />);
+ fireEvent.click(screen.getByText("Log"));
+ expect(useEventStore.getState().activeSection).toBe("sessions");
+ });
+});
+
+describe("TurnCard", () => {
+ beforeEach(() => useDeckStore.getState().resetDeck());
+ afterEach(() => cleanup());
+
+ test("says so before the first turn", () => {
+ render(<TurnCard />);
+ expect(screen.getByText("No response yet. Say your wake word.")).toBeTruthy();
+ });
+
+ test("shows the phases, the marks and the model of the last turn", () => {
+ const s = feed(VOICE_TURN);
+ useDeckStore.setState(feed([["SystemStateChanged", { new_state: "LISTENING", previous: "SPEAKING" }]], s, 20_000));
+ render(<TurnCard />);
+ expect(screen.getByText("#1 · last")).toBeTruthy();
+ for (const ph of ["hear", "think", "act", "speak"]) expect(screen.getByText(ph)).toBeTruthy();
+ expect(screen.getByText("380 ms")).toBeTruthy(); // transcript
+ expect(screen.getByText("1.3 s")).toBeTruthy(); // first token
+ expect(screen.getByText("1.9 s")).toBeTruthy(); // first audio
+ expect(screen.getByText(/claude-sonnet-5/)).toBeTruthy();
+ expect(screen.getByText(/1 tools/)).toBeTruthy();
+ expect(screen.getByText(/4 words/)).toBeTruthy();
+ });
+
+ test("runs live while a turn is open", () => {
+ // Fed at the real clock: a turn nobody touched for 90 s counts as quiet.
+ useDeckStore.setState(
+ feed(
+ [
+ ["TranscriptFinal", { transcript: { text: "hallo" } }],
+ ["BrainTurnStarted", { provider: "openrouter", model: "m" }],
+ ],
+ emptyDeckState(),
+ Date.now() - 1_000,
+ ),
+ );
+ render(<TurnCard />);
+ expect(screen.getByText("#1 · live")).toBeTruthy();
+ expect(screen.getByText("after you finished speaking")).toBeTruthy();
+ });
+});
+
+describe("CaptureCard", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ useDeckStore.getState().resetDeck();
+ });
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ });
+
+ test("shows a fresh capture with a fading rail, then only the ledger", () => {
+ useDeckStore.setState(
+ feed([["ScreenCaptureCompleted", { target_label: "Chrome", width: 1920, height: 1080, redaction_count: 2 }]]),
+ );
+ render(<CaptureCard />);
+ // Up: the picture, its label, what was redacted, and the countdown.
+ expect(document.querySelector("img")).toBeTruthy();
+ expect(screen.getByText("Chrome")).toBeTruthy();
+ expect(screen.getByText("2 redacted")).toBeTruthy();
+ expect(screen.getByText(/fades in/)).toBeTruthy();
+
+ act(() => {
+ vi.advanceTimersByTime(CAPTURE_AFTERGLOW_MS + 500);
+ });
+ // Gone: no picture lingers, the ledger remembers the look in words.
+ expect(document.querySelector("img")).toBeNull();
+ expect(screen.getByText("Earlier this session")).toBeTruthy();
+ expect(screen.getByText("Chrome")).toBeTruthy();
+ expect(screen.getByText("1920×1080")).toBeTruthy();
+ });
+
+ test("says so when nothing was captured", () => {
+ render(<CaptureCard />);
+ expect(screen.getByText("No capture right now.")).toBeTruthy();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/deck/DeckLogCard.tsx b/jarvis/ui/web/frontend/src/components/deck/DeckLogCard.tsx
new file mode 100644
index 0000000000..2bcd898f95
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/deck/DeckLogCard.tsx
@@ -0,0 +1,225 @@
+import { useEffect, useRef, useState } from "react";
+import { ScrollText } from "lucide-react";
+import { useEventStore } from "@/store/events";
+import { useDeckStore } from "@/store/deck";
+import type { JournalKind, JournalLine, TurnPhase } from "@/lib/deckState";
+import { useVoiceReadiness } from "@/hooks/useVoiceReadiness";
+import { DeckCard } from "@/components/deck/DeckCard";
+import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
+
+/**
+ * The deck's terminal — the session log.
+ *
+ * One line per thing the assistant heard, thought, did or said, with the
+ * clock time in front and the measured duration at the end: the reasoning
+ * made visible as it happens, and kept afterwards so the last minutes can be
+ * read back (maintainer decision 2026-08-18: "a display that always shows
+ * something, like a terminal, showing the reasoning and how long it takes").
+ *
+ * The lines come from `deckState.reduceJournal`, folded from the same bus
+ * events every other card reads — nothing here is invented. The last row is
+ * the cursor: what the assistant is doing this very second, and how long it
+ * has been quiet, so the terminal is never blank even on a fresh start.
+ */
+
+/** How many lines the terminal paints — the store keeps more, the eye needs fewer. */
+const SHOWN_LINES = 60;
+
+const TAG_TONE: Record<JournalKind, string> = {
+ boot: "text-muted-foreground",
+ wake: "text-primary",
+ hear: "text-sky-400",
+ think: "text-primary",
+ done: "text-primary",
+ tool: "text-emerald-400",
+ say: "text-amber-300",
+ worker: "text-emerald-400",
+ control: "text-violet-400",
+ look: "text-violet-400",
+ memory: "text-sky-400",
+ error: "text-destructive",
+ note: "text-muted-foreground",
+};
+
+/** Lines whose text is something a person said or heard — shown as speech. */
+const SPEECH: ReadonlySet<JournalKind> = new Set(["hear", "say"]);
+
+export function fmtMs(ms: number): string {
+ if (ms < 1000) return `${Math.round(ms)} ms`;
+ if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`;
+ const minutes = Math.floor(ms / 60_000);
+ const seconds = Math.floor((ms % 60_000) / 1000);
+ return `${minutes}:${String(seconds).padStart(2, "0")} min`;
+}
+
+function fmtClock(ms: number): string {
+ return new Date(ms).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit", second: "2-digit" });
+}
+
+/** "quiet for 3 min" — coarse on purpose; a second-by-second count would fidget. */
+function fmtQuiet(ms: number): string {
+ if (ms < 60_000) return `${Math.max(1, Math.floor(ms / 1000))} s`;
+ if (ms < 3_600_000) return `${Math.floor(ms / 60_000)} min`;
+ return `${Math.floor(ms / 3_600_000)} h`;
+}
+
+function fill(template: string, args?: Record<string, string>): string {
+ if (!args) return template;
+ return template.replace(/\{(\w+)\}/g, (m, k: string) => (k in args ? args[k] : m));
+}
+
+const NOW_KEY: Record<TurnPhase, string> = {
+ idle: "deck.log_now_idle",
+ hear: "deck.log_now_hear",
+ think: "deck.log_now_think",
+ act: "deck.log_now_act",
+ speak: "deck.log_now_speak",
+};
+
+export function LogCard({ className }: { className?: string }) {
+ const t = useT();
+ const setActiveSection = useEventStore((s) => s.setActiveSection);
+ const journal = useDeckStore((s) => s.journal);
+ const turn = useDeckStore((s) => s.turn);
+ const { connected, warming } = useVoiceReadiness();
+ const voiceState = useEventStore((s) => s.voiceState);
+
+ // The cursor line ticks once a second: "quiet for 3 min" has to move
+ // without an event arriving, that is its whole point.
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ const id = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(id);
+ }, []);
+
+ // Stick to the bottom like a terminal — unless the reader scrolled up to
+ // read something, in which case new lines must not yank them back down.
+ const bodyRef = useRef<HTMLDivElement | null>(null);
+ const stickRef = useRef(true);
+ const onScroll = () => {
+ const el = bodyRef.current;
+ if (!el) return;
+ stickRef.current = el.scrollTop + el.clientHeight >= el.scrollHeight - 24;
+ };
+ useEffect(() => {
+ const el = bodyRef.current;
+ if (el && stickRef.current) el.scrollTop = el.scrollHeight;
+ }, [journal.length, turn.phase]);
+
+ const shown = journal.length > SHOWN_LINES ? journal.slice(journal.length - SHOWN_LINES) : journal;
+ const live = turn.phase !== "idle";
+ const lastTs = journal.length > 0 ? journal[journal.length - 1].ts : null;
+
+ // What the cursor says: the link first, then the voice, then the turn — and
+ // the supervisor's own state when it is ahead of the turn (listening
+ // before a transcript exists).
+ const nowKey = !connected
+ ? "deck.log_now_offline"
+ : warming
+ ? "deck.log_now_warming"
+ : live
+ ? NOW_KEY[turn.phase]
+ : voiceState === "listening"
+ ? "deck.log_now_hear"
+ : voiceState === "speaking"
+ ? "deck.log_now_speak"
+ : "deck.log_now_idle";
+ const quiet = !live && lastTs !== null ? now - lastTs : null;
+
+ return (
+ <DeckCard
+ icon={ScrollText}
+ title={t("deck.card_log")}
+ meta={journal.length > 0 ? journal.length : undefined}
+ live={live}
+ variant="rail"
+ onOpen={() => setActiveSection("sessions")}
+ openLabel={t("deck.log_open_section")}
+ className={className}
+ bodyClassName="p-0"
+ >
+ <div
+ ref={bodyRef}
+ onScroll={onScroll}
+ className="h-full overflow-y-auto px-2.5 pb-2 font-mono text-[10.5px] leading-[1.5]"
+ >
+ {shown.map((line) => (
+ <LogRow key={line.id} line={line} t={t} />
+ ))}
+ {/* The cursor: never empty. Wraps rather than truncates — this is the
+ one line that must always be readable whole. */}
+ <div className="mt-1 flex items-baseline gap-2 text-[10.5px]">
+ <span className="shrink-0 tabular-nums text-muted-foreground/70">{fmtClock(now)}</span>
+ <span
+ className={cn(
+ "inline-block h-[1.1em] w-[0.55em] shrink-0 self-center",
+ live ? "bg-primary" : "bg-foreground/60 motion-safe:animate-pulse",
+ )}
+ aria-hidden
+ />
+ <span className="min-w-0 flex-1 whitespace-normal break-words">
+ <span className={live ? "text-primary" : "text-foreground/80"}>{t(nowKey)}</span>
+ {quiet !== null && quiet > 5_000 && (
+ <span className="text-muted-foreground/70">
+ {" · "}
+ {t("deck.log_quiet_for").replace("{0}", fmtQuiet(quiet))}
+ </span>
+ )}
+ </span>
+ </div>
+ </div>
+ </DeckCard>
+ );
+}
+
+function LogRow({ line, t }: { line: JournalLine; t: (key: string) => string }) {
+ const label = line.labelKey ? fill(t(line.labelKey), line.args) : "";
+ const failed = line.ok === false;
+ const speech = SPEECH.has(line.kind) && Boolean(line.text);
+ return (
+ <div
+ className={cn(
+ "flex items-baseline gap-2",
+ failed && "text-destructive",
+ // A sub-note (first token, first audio) hangs under its parent line.
+ line.kind === "note" && !line.text && line.ms !== undefined && "opacity-80",
+ )}
+ >
+ <span className="shrink-0 tabular-nums text-muted-foreground/70">{fmtClock(line.ts)}</span>
+ <span
+ className={cn(
+ "w-[6ch] shrink-0 uppercase tracking-wider",
+ failed ? "text-destructive" : TAG_TONE[line.kind],
+ line.open && "motion-safe:animate-pulse",
+ )}
+ >
+ {t(`deck.log_kind_${line.kind}`)}
+ </span>
+ {/* Wraps like a terminal does — a transcript cut to "wie spät…" would
+ hide the one thing the line is for. Long lines cost height, and the
+ card has that. */}
+ <span className="min-w-0 flex-1 whitespace-normal break-words [overflow-wrap:anywhere]">
+ {label && <span className={cn(line.text ? "text-muted-foreground" : "text-foreground/90")}>{label}</span>}
+ {label && line.text && " "}
+ {line.text && (
+ <span className={cn(speech ? "text-foreground" : "text-foreground/90")}>
+ {speech ? `“${line.text}”` : line.text}
+ </span>
+ )}
+ {line.open ? (
+ <span className="text-primary" aria-hidden>
+ {" …"}
+ </span>
+ ) : (
+ line.ms !== undefined && (
+ <span className={cn("tabular-nums", failed ? "text-destructive" : "text-muted-foreground")}>
+ {" · "}
+ {fmtMs(line.ms)}
+ </span>
+ )
+ )}
+ </span>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/deck/DeckSignalCards.tsx b/jarvis/ui/web/frontend/src/components/deck/DeckSignalCards.tsx
index aee471a4d2..9f95c6e04e 100644
--- a/jarvis/ui/web/frontend/src/components/deck/DeckSignalCards.tsx
+++ b/jarvis/ui/web/frontend/src/components/deck/DeckSignalCards.tsx
@@ -1,186 +1,128 @@
import { useEffect, useMemo, useState } from "react";
-import { Camera, Coins, MousePointer2 } from "lucide-react";
+import { Camera, Coins } from "lucide-react";
import { useEventStore } from "@/store/events";
import { useDeckStore } from "@/store/deck";
-import { countWords } from "@/lib/deckState";
+import { countWords, type CaptureState } from "@/lib/deckState";
import { DeckCard } from "@/components/deck/DeckCard";
import { HudGauge, HudLamp } from "@/components/deck/HudFrame";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
/**
- * The deck's signal cards — the pictures and the numbers.
+ * The deck's signal cards — the picture and the numbers.
*
- * Both picture cards read the images through the deck routes added for them
- * (`/api/deck/frame`, `/api/deck/cu-frame/{sha}`) and nothing else. The
- * numbers are the ones the bus actually publishes: `BrainTurnCompleted`
- * carries tokens and cost, `TranscriptFinal` the words. No estimate anywhere.
+ * The capture card reads its image through the deck route added for it
+ * (`/api/deck/frame`) and nothing else. The numbers are the ones the bus
+ * actually publishes: `BrainTurnCompleted` carries tokens and cost,
+ * `TranscriptFinal` the words. No estimate anywhere.
*/
// ----------------------------------------------------------------------
-// Computer Use — what the assistant is doing on the screen
+// Capture — the picture Screen Context just took, briefly, then the ledger
// ----------------------------------------------------------------------
-const CU_PHASES = ["observe", "uia", "plan", "think", "act", "verify"] as const;
-
-export function ComputerUseCard({ className }: { className?: string }) {
- const t = useT();
- const cu = useDeckStore((s) => s.cu);
- const setActiveSection = useEventStore((s) => s.setActiveSection);
- const src = cu.lastFrameSha ? `/api/deck/cu-frame/${cu.lastFrameSha}` : null;
- const [broken, setBroken] = useState(false);
- useEffect(() => setBroken(false), [src]);
+/**
+ * How long a new capture stays on the front page before it fades. Long
+ * enough to see what was looked at, short enough that a picture of the
+ * screen never sits there as furniture (maintainer complaint 2026-08-18: the
+ * shot used to stay until the next one replaced it). The backend keeps the
+ * bytes for its own budget (`deck_preview_s`); this is only how long the
+ * deck SHOWS them.
+ */
+export const CAPTURE_AFTERGLOW_MS = 20_000;
- return (
- <DeckCard
- icon={MousePointer2}
- title={t("deck.card_cu")}
- meta={cu.active ? `#${cu.stepIdx}` : cu.frames > 0 ? t("deck.cu_done") : undefined}
- live={cu.active}
- variant="bracket"
- onOpen={() => setActiveSection("run_inspector")}
- openLabel={t("deck.open_section")}
- className={className}
- bodyClassName="p-0"
- >
- <div className="relative flex h-full min-h-[6rem] flex-col">
- {/* The frame the harness last looked at. Object-contain: the whole
- screen matters, not a crop of it. */}
- <div className="relative min-h-0 flex-1 overflow-hidden bg-black/20">
- {src && !broken ? (
- <img
- src={src}
- alt=""
- onError={() => setBroken(true)}
- className={cn("h-full w-full object-contain", !cu.active && "opacity-70")}
- />
- ) : (
- <div className="flex h-full items-center justify-center px-3 text-center text-[11px] text-muted-foreground">
- {cu.active ? t("deck.cu_waiting_frame") : t("deck.cu_idle")}
- </div>
- )}
- {cu.active && (
- <span className="absolute left-2 top-2 flex items-center gap-1 rounded-sm bg-background/80 px-1.5 py-0.5 font-mono text-[9px] uppercase tracking-wider text-primary">
- <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-primary" aria-hidden />
- live
- </span>
- )}
- </div>
+/**
+ * The receipt event and the mirrored bytes are two different messages, and a
+ * fetch that lands between them gets a 404. The service now mirrors first,
+ * but a picture must not depend on that ordering forever: retry briefly.
+ */
+const FRAME_RETRIES = 3;
+const FRAME_RETRY_MS = 400;
- {/* Phase strip: observe → plan → act → verify. */}
- <div className="flex items-stretch gap-px border-t border-border/60 px-2 py-1">
- {CU_PHASES.map((ph, i) => {
- const on = cu.active && cu.phase === ph;
- const passed = cu.active && (CU_PHASES as readonly string[]).indexOf(cu.phase) > i;
- return (
- <span
- key={ph}
- className={cn(
- "flex flex-1 flex-col items-center gap-0.5 font-mono text-[8px] uppercase tracking-wider",
- on ? "text-primary" : "text-muted-foreground/70",
- )}
- >
- <span
- className={cn(
- "h-1 w-full",
- on ? "bg-primary shadow-[0_0_6px_hsl(var(--primary)/0.7)]" : passed ? "bg-primary/40" : "bg-border",
- )}
- style={{ clipPath: "polygon(0 0, calc(100% - 3px) 0, 100% 100%, 3px 100%)" }}
- aria-hidden
- />
- <span className="truncate">{ph}</span>
- </span>
- );
- })}
- </div>
- {(cu.lastActionKind || cu.windowTitle) && (
- <div className="flex items-center gap-2 border-t border-border/60 px-2 py-1 font-mono text-[10px]">
- {cu.lastActionKind && (
- <span
- className={cn(
- "shrink-0 rounded-sm px-1 py-px uppercase",
- cu.lastActionOk === false
- ? "bg-destructive text-white"
- : "bg-primary text-primary-foreground",
- )}
- >
- {cu.lastActionKind}
- </span>
- )}
- <span className="min-w-0 flex-1 truncate text-muted-foreground">
- {cu.lastTargetHint || cu.windowTitle}
- </span>
- </div>
- )}
- </div>
- </DeckCard>
- );
+function fmtClock(ms: number): string {
+ return new Date(ms).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });
}
-// ----------------------------------------------------------------------
-// App-Shot — the picture Screen Context just took
-// ----------------------------------------------------------------------
-
-/**
- * Shows the last one-shot capture for as long as the backend keeps it — the
- * mirror has a TTL, and when the image 404s the card goes quiet again. The
- * URL carries the sequence so a NEW capture is a new request; the browser
- * would otherwise happily show the previous picture from memory.
- */
-export function AppShotCard({ className }: { className?: string }) {
+export function CaptureCard({ className }: { className?: string }) {
const t = useT();
const capture = useDeckStore((s) => s.capture);
- const [gone, setGone] = useState(false);
- const src = capture ? `/api/deck/frame?s=${capture.seq}` : null;
+ const captures = useDeckStore((s) => s.captures);
+ // The afterglow: a fresh capture is shown, a rail drains, then it is gone.
+ // `remaining` is only ever read while a picture is up, so the interval runs
+ // only then.
+ const [remaining, setRemaining] = useState(0);
+ const [attempt, setAttempt] = useState(0);
+ const [gone, setGone] = useState(false);
useEffect(() => {
- setGone(false);
if (!capture) return;
- // Re-check well within the default 120 s budget so an expired preview
- // does not linger as a stale <img>.
- const id = window.setInterval(async () => {
- try {
- const res = await fetch("/api/deck/frame/meta", { cache: "no-store" });
- const meta = (await res.json()) as { available?: boolean };
- if (!meta.available) setGone(true);
- } catch {
- /* the deck must not care */
- }
- }, 15_000);
+ setGone(false);
+ setAttempt(0);
+ setRemaining(CAPTURE_AFTERGLOW_MS);
+ const started = Date.now();
+ const id = window.setInterval(() => {
+ const left = CAPTURE_AFTERGLOW_MS - (Date.now() - started);
+ setRemaining(Math.max(0, left));
+ if (left <= 0) window.clearInterval(id);
+ }, 250);
return () => window.clearInterval(id);
}, [capture]);
- const fresh = capture && !gone;
+ const showing = Boolean(capture) && !gone && remaining > 0;
+ const src = capture ? `/api/deck/frame?s=${capture.seq}&r=${attempt}` : null;
+
+ const onError = () => {
+ if (attempt < FRAME_RETRIES) {
+ window.setTimeout(() => setAttempt((n) => n + 1), FRAME_RETRY_MS);
+ } else {
+ setGone(true);
+ }
+ };
return (
<DeckCard
icon={Camera}
title={t("deck.card_shot")}
- meta={fresh && capture ? `${capture.width}×${capture.height}` : undefined}
- live={Boolean(fresh)}
+ meta={showing && capture ? `${capture.width}×${capture.height}` : captures.length > 0 ? captures.length : undefined}
+ live={showing}
variant="bracket"
className={className}
bodyClassName="p-0"
>
<div className="relative h-full min-h-[5rem] overflow-hidden bg-black/20">
- {fresh && src ? (
+ {showing && src ? (
<>
<img
key={src}
src={src}
alt=""
- onError={() => setGone(true)}
+ onError={onError}
className="h-full w-full object-contain"
/>
- <div className="absolute bottom-0 left-0 right-0 flex items-center gap-2 bg-background/75 px-2 py-0.5 font-mono text-[9px] text-muted-foreground">
- <span className="min-w-0 flex-1 truncate">{capture?.targetLabel || capture?.targetKind}</span>
- {capture && capture.redactions > 0 && (
- <span className="shrink-0 text-primary">
- {t("deck.shot_redacted").replace("{0}", String(capture.redactions))}
+ <div className="absolute bottom-0 left-0 right-0 flex flex-col bg-background/75">
+ <div className="flex items-center gap-2 px-2 py-0.5 font-mono text-[9px] text-muted-foreground">
+ <span className="min-w-0 flex-1 truncate">{capture?.targetLabel || capture?.targetKind}</span>
+ {capture && capture.redactions > 0 && (
+ <span className="shrink-0 text-primary">
+ {t("deck.shot_redacted").replace("{0}", String(capture.redactions))}
+ </span>
+ )}
+ <span className="shrink-0 tabular-nums">
+ {t("deck.shot_fades").replace("{0}", `${Math.ceil(remaining / 1000)} s`)}
</span>
- )}
+ </div>
+ {/* The draining rail: the picture's remaining time, visible. */}
+ <div className="h-px w-full bg-border/60">
+ <div
+ className="h-px bg-primary transition-[width] duration-200 ease-linear"
+ style={{ width: `${(remaining / CAPTURE_AFTERGLOW_MS) * 100}%` }}
+ aria-hidden
+ />
+ </div>
</div>
</>
+ ) : captures.length > 0 ? (
+ <CaptureLedger captures={captures} t={t} />
) : (
<div className="flex h-full items-center justify-center px-3 text-center text-[11px] text-muted-foreground">
{t("deck.shot_empty")}
@@ -191,6 +133,40 @@ export function AppShotCard({ className }: { className?: string }) {
);
}
+/**
+ * What was looked at this session — time, target, size, what was redacted.
+ * Words only, never pixels: the mirror holds one frame and no history, and
+ * the ledger keeps that promise (the labels are the service's own scrubbed
+ * ones, the same the receipt event carries).
+ */
+function CaptureLedger({ captures, t }: { captures: CaptureState[]; t: (key: string) => string }) {
+ return (
+ <div className="flex h-full flex-col px-2.5 py-1.5">
+ <span className="font-mono text-[9px] uppercase tracking-[0.16em] text-muted-foreground">
+ {t("deck.shot_earlier")}
+ </span>
+ <ul className="mt-1 min-h-0 flex-1 space-y-0.5 overflow-y-auto">
+ {captures.map((c) => (
+ <li key={c.seq} className="flex items-center gap-2 font-mono text-[10px]">
+ <span className="shrink-0 tabular-nums text-muted-foreground">{fmtClock(c.ts)}</span>
+ <span className="min-w-0 flex-1 truncate text-foreground">{c.targetLabel || c.targetKind || "—"}</span>
+ {c.width > 0 && c.height > 0 && (
+ <span className="shrink-0 tabular-nums text-muted-foreground">
+ {c.width}×{c.height}
+ </span>
+ )}
+ {c.redactions > 0 && (
+ <span className="shrink-0 text-primary">
+ {t("deck.shot_redacted").replace("{0}", String(c.redactions))}
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
+
// ----------------------------------------------------------------------
// API stats — what this session cost
// ----------------------------------------------------------------------
diff --git a/jarvis/ui/web/frontend/src/components/deck/DeckTurnCard.tsx b/jarvis/ui/web/frontend/src/components/deck/DeckTurnCard.tsx
new file mode 100644
index 0000000000..cf9b9b8aad
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/deck/DeckTurnCard.tsx
@@ -0,0 +1,173 @@
+import { useEffect, useState } from "react";
+import { Timer } from "lucide-react";
+import { useEventStore } from "@/store/events";
+import { useDeckStore } from "@/store/deck";
+import type { TurnPhase } from "@/lib/deckState";
+import { DeckCard } from "@/components/deck/DeckCard";
+import { HudLamp } from "@/components/deck/HudFrame";
+import { fmtMs } from "@/components/deck/DeckLogCard";
+import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
+
+/**
+ * The response instrument — how the answer is coming about, and how long
+ * each stage takes.
+ *
+ * Replaces the live screen mirror on the front page (maintainer decision
+ * 2026-08-18: not a live feed, a display that shows the process and its
+ * timing). Four phases — hear, think, act, speak — light up as the turn moves
+ * through them; the big figure is the clock since the request was complete,
+ * running while the turn is open and frozen when it ends. Next to it the
+ * marks that matter for a voice assistant, all measured from the same
+ * anchor: when the transcript was final, when the brain's first token came,
+ * when the first audio was audible. Between turns the card keeps the LAST
+ * turn's figures, so after the first answer it always has something real.
+ *
+ * Every number is the backend's own (`deckState.reduceTurn`): latency marks
+ * from the latency tracker, tokens from `BrainTurnCompleted`. Nothing here is
+ * estimated for show.
+ */
+
+const PHASES: readonly TurnPhase[] = ["hear", "think", "act", "speak"];
+
+/** A turn nobody has touched for this long is over in every way but the event. */
+const QUIET_AFTER_MS = 90_000;
+
+export function TurnCard({ className }: { className?: string }) {
+ const t = useT();
+ const turn = useDeckStore((s) => s.turn);
+ const cuActive = useDeckStore((s) => s.cu.active);
+ const setActiveSection = useEventStore((s) => s.setActiveSection);
+
+ const live = turn.phase !== "idle";
+ // The stopwatch ticks only while a turn is open — ten times a second, which
+ // is what a person reads as "running" without the digits blurring.
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (!live) return;
+ setNow(Date.now());
+ const id = window.setInterval(() => setNow(Date.now()), 100);
+ return () => window.clearInterval(id);
+ }, [live]);
+
+ const quiet = live && turn.lastEventTs !== null && now - turn.lastEventTs > QUIET_AFTER_MS;
+ const clockEnd = live ? (quiet ? (turn.lastEventTs ?? now) : now) : (turn.endedTs ?? turn.lastEventTs ?? 0);
+ const elapsed = turn.anchorTs !== null ? Math.max(0, clockEnd - turn.anchorTs) : null;
+ const phaseIdx = PHASES.indexOf(turn.phase);
+
+ return (
+ <DeckCard
+ icon={Timer}
+ title={t("deck.card_turn")}
+ meta={
+ turn.index > 0
+ ? `#${turn.index} · ${live ? (quiet ? t("deck.turn_quiet") : t("deck.turn_live")) : t("deck.turn_last")}`
+ : undefined
+ }
+ live={live && !quiet}
+ variant="chamfer"
+ onOpen={() => setActiveSection("run_inspector")}
+ openLabel={t("deck.open_section")}
+ className={className}
+ bodyClassName="p-0"
+ >
+ {turn.index === 0 ? (
+ <p className="px-2.5 py-1 text-[11px] text-muted-foreground">{t("deck.turn_empty")}</p>
+ ) : (
+ <div className={cn("flex h-full min-h-0 flex-col", quiet && "opacity-60")}>
+ {/* Phase strip: hear → think → act → speak. */}
+ <div className="flex items-stretch gap-px px-2.5 pt-0.5">
+ {PHASES.map((ph, i) => {
+ const on = live && turn.phase === ph;
+ const passed = live ? phaseIdx > i : true;
+ return (
+ <span
+ key={ph}
+ className={cn(
+ "flex flex-1 flex-col items-center gap-0.5 font-mono text-[8px] uppercase tracking-wider",
+ on ? "text-primary" : "text-muted-foreground/70",
+ )}
+ >
+ <span
+ className={cn(
+ "h-1 w-full",
+ on
+ ? "bg-primary shadow-[0_0_6px_hsl(var(--primary)/0.7)]"
+ : passed
+ ? "bg-primary/40"
+ : "bg-border",
+ )}
+ style={{ clipPath: "polygon(0 0, calc(100% - 3px) 0, 100% 100%, 3px 100%)" }}
+ aria-hidden
+ />
+ <span className="truncate">{t(`deck.turn_phase_${ph}`)}</span>
+ </span>
+ );
+ })}
+ </div>
+
+ {/* The clock and the marks. */}
+ <div className="flex min-h-0 flex-1 items-center gap-3 px-2.5 py-1">
+ <div className="flex shrink-0 flex-col">
+ <span
+ className={cn(
+ "font-mono text-2xl font-semibold tabular-nums leading-none",
+ live && !quiet ? "text-primary" : "text-foreground",
+ )}
+ >
+ {elapsed === null ? "—" : fmtMs(elapsed)}
+ </span>
+ <span className="mt-1 max-w-[12ch] truncate font-mono text-[8px] uppercase leading-tight tracking-[0.14em] text-muted-foreground">
+ {turn.anchorTs === null ? t("deck.turn_phase_hear") : t("deck.turn_since_anchor")}
+ </span>
+ </div>
+ <ul className="flex min-w-0 flex-1 flex-col gap-px font-mono text-[9.5px]">
+ <Mark label={t("deck.turn_stt")} ms={turn.sttMs} />
+ {turn.ackMs !== null && <Mark label={t("deck.turn_ack")} ms={turn.ackMs} hot />}
+ <Mark label={t("deck.turn_first_token")} ms={turn.ttftMs} />
+ <Mark label={t("deck.turn_first_audio")} ms={turn.firstAudioMs} hot />
+ </ul>
+ </div>
+
+ {/* The bottom line: who answered, and with what. */}
+ <div className="flex items-center gap-2 overflow-hidden border-t border-border/60 px-2.5 py-1 font-mono text-[9.5px] text-muted-foreground">
+ <HudLamp on={live && !quiet} />
+ <span className="min-w-0 flex-1 truncate">
+ {[
+ turn.model || turn.provider,
+ turn.attempts > 1 ? `${turn.attempts} ${t("deck.turn_attempts")}` : "",
+ turn.tools > 0
+ ? `${turn.tools}${turn.toolsFailed > 0 ? `(${turn.toolsFailed}✕)` : ""} ${t("deck.turn_tools")}`
+ : "",
+ turn.cu || cuActive ? t("deck.turn_screen") : "",
+ turn.words > 0 ? `${turn.words} ${t("deck.turn_words")}` : "",
+ turn.brainMs !== null ? `${t("deck.turn_brain")} ${fmtMs(turn.brainMs)}` : "",
+ ]
+ .filter(Boolean)
+ .join(" · ")}
+ </span>
+ {turn.cacheHit && (
+ <span className="shrink-0 uppercase tracking-wider text-emerald-400">{t("deck.api_cache_hit")}</span>
+ )}
+ </div>
+ </div>
+ )}
+ </DeckCard>
+ );
+}
+
+function Mark({ label, ms, hot }: { label: string; ms: number | null; hot?: boolean }) {
+ return (
+ <li className="flex items-baseline gap-2">
+ <span className="min-w-0 flex-1 truncate uppercase tracking-wider text-muted-foreground/80">{label}</span>
+ <span
+ className={cn(
+ "shrink-0 tabular-nums",
+ ms === null ? "text-muted-foreground/50" : hot ? "text-primary" : "text-foreground",
+ )}
+ >
+ {ms === null ? "—" : fmtMs(ms)}
+ </span>
+ </li>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 8185d52348..7c11850eab 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -4331,7 +4331,6 @@
"deck": {
"sections": "Sektionen",
"running": "Läuft gerade",
- "running_empty": "Nichts läuft. Sag dein Wake-Word.",
"thinking_now": "Denkt gerade",
"thinking_starting": "Startet…",
"idle_headline": "Bereit. Sag dein Wake-Word.",
@@ -4348,7 +4347,6 @@
"switch_to_deck": "Deck",
"open_section": "Sektion öffnen",
"unavailable": "Gerade nicht verfügbar",
- "card_flow": "Gerade jetzt",
"card_runs": "Läufe",
"runs_empty": "Noch keine Läufe.",
"card_outputs": "Ergebnisse",
@@ -4358,10 +4356,6 @@
"card_terminals": "Terminals",
"terminals_empty": "Noch keine Befehle.",
"card_wiki": "Wiki",
- "card_cu": "Computer-Steuerung",
- "cu_idle": "Steuert den Bildschirm gerade nicht.",
- "cu_waiting_frame": "Schaut zum ersten Mal hin…",
- "cu_done": "fertig",
"card_shot": "Bildschirmfoto",
"shot_empty": "Gerade keine Aufnahme.",
"shot_redacted": "{0} geschwärzt",
@@ -4388,6 +4382,70 @@
"lamp_brain": "Hirn",
"lamp_cu": "Steuerung",
"orb_steps": "Schritte",
- "orb_words": "Wörter"
+ "orb_words": "Wörter",
+ "card_log": "Logbuch",
+ "log_kind_boot": "start",
+ "log_kind_wake": "wach",
+ "log_kind_hear": "hört",
+ "log_kind_think": "denkt",
+ "log_kind_done": "fertig",
+ "log_kind_tool": "tool",
+ "log_kind_say": "sagt",
+ "log_kind_worker": "agent",
+ "log_kind_control": "schirm",
+ "log_kind_look": "blick",
+ "log_kind_memory": "merkt",
+ "log_kind_error": "fehler",
+ "log_kind_note": "notiz",
+ "log_voice_ready": "Stimme bereit",
+ "log_brain_switched": "Hirn gewechselt",
+ "log_wake": "Wake-Word",
+ "log_hotkey": "Tastenkürzel",
+ "log_session_ended": "Sitzung zu Ende · {turns} Antworten",
+ "log_hear_more": "…und",
+ "log_typed": "getippt",
+ "log_first_token": "erstes Token",
+ "log_done": "{in} rein · {out} raus · {cost}",
+ "log_denied": "abgelehnt",
+ "log_ack": "Kurzantwort",
+ "log_first_audio": "erster Ton",
+ "log_ack_audio": "Kurzantwort hörbar",
+ "log_progress": "Zwischenstand",
+ "log_worker": "Hintergrund-Agent",
+ "log_control": "hat den Bildschirm übernommen",
+ "log_control_ended": "hat den Bildschirm zurückgegeben",
+ "log_look": "hat auf den Bildschirm geschaut",
+ "log_look_redacted": "hat auf den Bildschirm geschaut · {n} geschwärzt",
+ "log_memory": "hat sich etwas gemerkt",
+ "log_now_offline": "keine Verbindung zum Assistenten",
+ "log_now_warming": "Stimme startet gerade",
+ "log_now_idle": "wartet auf das Wake-Word",
+ "log_now_hear": "hört zu",
+ "log_now_think": "denkt nach",
+ "log_now_act": "handelt",
+ "log_now_speak": "spricht",
+ "log_quiet_for": "seit {0} still",
+ "log_open_section": "Sitzungen öffnen",
+ "card_turn": "Antwort",
+ "turn_empty": "Noch keine Antwort. Sag dein Wake-Word.",
+ "turn_phase_hear": "hören",
+ "turn_phase_think": "denken",
+ "turn_phase_act": "handeln",
+ "turn_phase_speak": "sprechen",
+ "turn_stt": "Transkript",
+ "turn_ack": "Kurzantwort",
+ "turn_first_token": "erstes Token",
+ "turn_first_audio": "erster Ton",
+ "turn_brain": "Hirn",
+ "turn_tools": "Tools",
+ "turn_words": "Wörter",
+ "turn_attempts": "Anläufe",
+ "turn_screen": "Bildschirm",
+ "turn_last": "zuletzt",
+ "turn_live": "live",
+ "turn_quiet": "still",
+ "turn_since_anchor": "nachdem du fertig gesprochen hast",
+ "shot_earlier": "Vorhin in dieser Sitzung",
+ "shot_fades": "verblasst in {0}"
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 10f5a52a8d..7fb974c535 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -4331,7 +4331,6 @@
"deck": {
"sections": "Sections",
"running": "Running now",
- "running_empty": "Nothing running. Say your wake word.",
"thinking_now": "Thinking",
"thinking_starting": "Starting…",
"idle_headline": "Ready. Say your wake word.",
@@ -4348,7 +4347,6 @@
"switch_to_deck": "Deck",
"open_section": "Open section",
"unavailable": "Not available right now",
- "card_flow": "Right now",
"card_runs": "Runs",
"runs_empty": "No runs yet.",
"card_outputs": "Outputs",
@@ -4358,10 +4356,6 @@
"card_terminals": "Terminals",
"terminals_empty": "No commands yet.",
"card_wiki": "Wiki",
- "card_cu": "Computer use",
- "cu_idle": "Not controlling the screen.",
- "cu_waiting_frame": "Taking the first look…",
- "cu_done": "done",
"card_shot": "Screen capture",
"shot_empty": "No capture right now.",
"shot_redacted": "{0} redacted",
@@ -4388,6 +4382,70 @@
"lamp_brain": "brain",
"lamp_cu": "control",
"orb_steps": "steps",
- "orb_words": "words"
+ "orb_words": "words",
+ "card_log": "Log",
+ "log_kind_boot": "boot",
+ "log_kind_wake": "wake",
+ "log_kind_hear": "hear",
+ "log_kind_think": "think",
+ "log_kind_done": "done",
+ "log_kind_tool": "tool",
+ "log_kind_say": "say",
+ "log_kind_worker": "agent",
+ "log_kind_control": "screen",
+ "log_kind_look": "look",
+ "log_kind_memory": "memory",
+ "log_kind_error": "error",
+ "log_kind_note": "note",
+ "log_voice_ready": "voice ready",
+ "log_brain_switched": "brain switched",
+ "log_wake": "wake word",
+ "log_hotkey": "hotkey",
+ "log_session_ended": "session over · {turns} turns",
+ "log_hear_more": "…and",
+ "log_typed": "typed",
+ "log_first_token": "first token",
+ "log_done": "{in} in · {out} out · {cost}",
+ "log_denied": "denied",
+ "log_ack": "quick reply",
+ "log_first_audio": "first audio",
+ "log_ack_audio": "quick reply audible",
+ "log_progress": "update",
+ "log_worker": "background agent",
+ "log_control": "took the screen",
+ "log_control_ended": "gave the screen back",
+ "log_look": "looked at the screen",
+ "log_look_redacted": "looked at the screen · {n} redacted",
+ "log_memory": "wrote memory",
+ "log_now_offline": "no link to the assistant",
+ "log_now_warming": "voice is starting up",
+ "log_now_idle": "listening for the wake word",
+ "log_now_hear": "listening",
+ "log_now_think": "thinking",
+ "log_now_act": "acting",
+ "log_now_speak": "speaking",
+ "log_quiet_for": "quiet for {0}",
+ "log_open_section": "Open sessions",
+ "card_turn": "Response",
+ "turn_empty": "No response yet. Say your wake word.",
+ "turn_phase_hear": "hear",
+ "turn_phase_think": "think",
+ "turn_phase_act": "act",
+ "turn_phase_speak": "speak",
+ "turn_stt": "transcript",
+ "turn_ack": "quick reply",
+ "turn_first_token": "first token",
+ "turn_first_audio": "first audio",
+ "turn_brain": "brain",
+ "turn_tools": "tools",
+ "turn_words": "words",
+ "turn_attempts": "attempts",
+ "turn_screen": "screen",
+ "turn_last": "last",
+ "turn_live": "live",
+ "turn_quiet": "quiet",
+ "turn_since_anchor": "after you finished speaking",
+ "shot_earlier": "Earlier this session",
+ "shot_fades": "fades in {0}"
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 7f8211aed1..a6b10ce40c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -4331,7 +4331,6 @@
"deck": {
"sections": "Secciones",
"running": "En marcha",
- "running_empty": "Nada en marcha. Di tu palabra de activación.",
"thinking_now": "Pensando",
"thinking_starting": "Empezando…",
"idle_headline": "Listo. Di tu palabra de activación.",
@@ -4348,7 +4347,6 @@
"switch_to_deck": "Panel",
"open_section": "Abrir sección",
"unavailable": "No disponible ahora",
- "card_flow": "Ahora mismo",
"card_runs": "Ejecuciones",
"runs_empty": "Aún no hay ejecuciones.",
"card_outputs": "Resultados",
@@ -4358,10 +4356,6 @@
"card_terminals": "Terminales",
"terminals_empty": "Aún no hay comandos.",
"card_wiki": "Wiki",
- "card_cu": "Control del equipo",
- "cu_idle": "No está controlando la pantalla.",
- "cu_waiting_frame": "Mirando por primera vez…",
- "cu_done": "listo",
"card_shot": "Captura de pantalla",
"shot_empty": "Sin captura ahora.",
"shot_redacted": "{0} ocultos",
@@ -4388,6 +4382,70 @@
"lamp_brain": "cerebro",
"lamp_cu": "control",
"orb_steps": "pasos",
- "orb_words": "palabras"
+ "orb_words": "palabras",
+ "card_log": "Bitácora",
+ "log_kind_boot": "inicio",
+ "log_kind_wake": "aviso",
+ "log_kind_hear": "oye",
+ "log_kind_think": "piensa",
+ "log_kind_done": "listo",
+ "log_kind_tool": "tool",
+ "log_kind_say": "dice",
+ "log_kind_worker": "agente",
+ "log_kind_control": "pantalla",
+ "log_kind_look": "mira",
+ "log_kind_memory": "memoria",
+ "log_kind_error": "error",
+ "log_kind_note": "nota",
+ "log_voice_ready": "voz lista",
+ "log_brain_switched": "cerebro cambiado",
+ "log_wake": "palabra de activación",
+ "log_hotkey": "atajo",
+ "log_session_ended": "sesión terminada · {turns} respuestas",
+ "log_hear_more": "…y",
+ "log_typed": "escrito",
+ "log_first_token": "primer token",
+ "log_done": "{in} entrada · {out} salida · {cost}",
+ "log_denied": "denegado",
+ "log_ack": "respuesta rápida",
+ "log_first_audio": "primer audio",
+ "log_ack_audio": "respuesta rápida audible",
+ "log_progress": "avance",
+ "log_worker": "agente en segundo plano",
+ "log_control": "tomó la pantalla",
+ "log_control_ended": "devolvió la pantalla",
+ "log_look": "miró la pantalla",
+ "log_look_redacted": "miró la pantalla · {n} ocultos",
+ "log_memory": "guardó en la memoria",
+ "log_now_offline": "sin conexión con el asistente",
+ "log_now_warming": "la voz está arrancando",
+ "log_now_idle": "esperando la palabra de activación",
+ "log_now_hear": "escuchando",
+ "log_now_think": "pensando",
+ "log_now_act": "actuando",
+ "log_now_speak": "hablando",
+ "log_quiet_for": "en silencio desde hace {0}",
+ "log_open_section": "Abrir sesiones",
+ "card_turn": "Respuesta",
+ "turn_empty": "Aún no hay respuesta. Di tu palabra de activación.",
+ "turn_phase_hear": "oír",
+ "turn_phase_think": "pensar",
+ "turn_phase_act": "actuar",
+ "turn_phase_speak": "hablar",
+ "turn_stt": "transcripción",
+ "turn_ack": "respuesta rápida",
+ "turn_first_token": "primer token",
+ "turn_first_audio": "primer audio",
+ "turn_brain": "cerebro",
+ "turn_tools": "tools",
+ "turn_words": "palabras",
+ "turn_attempts": "intentos",
+ "turn_screen": "pantalla",
+ "turn_last": "última",
+ "turn_live": "en vivo",
+ "turn_quiet": "en silencio",
+ "turn_since_anchor": "después de que terminaste de hablar",
+ "shot_earlier": "Antes en esta sesión",
+ "shot_fades": "se desvanece en {0}"
}
}
diff --git a/jarvis/ui/web/frontend/src/lib/deckState.test.ts b/jarvis/ui/web/frontend/src/lib/deckState.test.ts
index df7b88a3dc..2502f4e610 100644
--- a/jarvis/ui/web/frontend/src/lib/deckState.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/deckState.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it } from "vitest";
import {
+ MAX_CAPTURES,
+ MAX_JOURNAL_LINES,
MAX_TERM_LINES,
countWords,
emptyDeckState,
@@ -15,11 +17,14 @@ import {
* a sequence, terminal noise is stripped, and unrelated events change nothing.
*/
+// One clock for the whole file, so a state folded in two steps still sees
+// time moving forward between them (durations are wall-clock deltas).
+let clock = 1_000;
+
function fold(events: Array<[string, unknown]>, start: DeckState = emptyDeckState()): DeckState {
let s = start;
- let ts = 1_000;
for (const [name, payload] of events) {
- s = reduceDeck(s, name, payload, (ts += 100));
+ s = reduceDeck(s, name, payload, (clock += 100));
}
return s;
}
@@ -27,7 +32,7 @@ function fold(events: Array<[string, unknown]>, start: DeckState = emptyDeckStat
describe("reduceDeck", () => {
it("returns the same object for events it does not read", () => {
const start = emptyDeckState();
- expect(reduceDeck(start, "HotkeyPressed", {}, 1)).toBe(start);
+ expect(reduceDeck(start, "TerminalSpawned", {}, 1)).toBe(start);
expect(reduceDeck(start, "SomethingNew", { x: 1 }, 1)).toBe(start);
});
@@ -174,3 +179,285 @@ describe("splitTerminalData", () => {
expect(splitTerminalData("10%\r20%\r30%\r\n\n")).toEqual(["10%", "20%", "30%"]);
});
});
+
+/**
+ * The session log and the turn are what the front page shows INSTEAD of a
+ * live screen feed (maintainer decision 2026-08-18): a terminal that always
+ * has something to say, and an instrument that reads how the last answer came
+ * about. Both are folded from the same events, so both are pinned here.
+ */
+describe("the session log", () => {
+ it("writes one line per thing heard, thought, done and said — with durations", () => {
+ const s = fold([
+ ["WakeWordDetected", { keyword: "nova", confidence: 0.92 }],
+ ["TranscriptFinal", { transcript: { text: "wie spät ist es" } }],
+ ["BrainTurnStarted", { provider: "openrouter", model: "claude-sonnet-5" }],
+ ["BrainTTFT", { cache_hit: true, model: "claude-sonnet-5" }],
+ ["ActionProposed", { tool_name: "get_time" }],
+ ["ActionExecuted", { tool_name: "get_time", success: true, duration_ms: 84 }],
+ ["BrainTurnCompleted", { tokens_in: 1200, tokens_out: 88, cost_usd: 0.0031 }],
+ ["SpeechSpoken", { text: "Es ist 14:47.", spoken_kind: "reply" }],
+ ["LatencySpan", { phase: "turn_to_first_audio", duration_ms: 1900 }],
+ ]);
+ const lines = s.journal.map((l) => [l.kind, l.labelKey ?? "", l.text ?? "", l.ms ?? null, l.ok ?? null, l.open ?? false]);
+ expect(lines).toEqual([
+ ["wake", "deck.log_wake", "nova · 0.92", null, null, false],
+ ["hear", "", "wie spät ist es", null, null, false],
+ // The brain line was opened, then closed in place when the turn completed.
+ ["think", "", "openrouter · claude-sonnet-5", 400, true, false],
+ ["note", "deck.log_first_token", "cache", 100, null, false],
+ ["tool", "", "get_time", 84, true, false],
+ ["done", "deck.log_done", "", 400, null, false],
+ ["say", "", "Es ist 14:47.", null, null, false],
+ ["note", "deck.log_first_audio", "", 1900, null, false],
+ ]);
+ const done = s.journal.find((l) => l.kind === "done")!;
+ expect(done.args).toEqual({ in: "1.20k", out: "88", cost: "$0.0031" });
+ });
+
+ it("does not write the same reply twice when it arrives spoken AND as a message", () => {
+ const s = fold([
+ ["SpeechSpoken", { text: "Erledigt.", spoken_kind: "reply" }],
+ ["MessageSent", { role: "assistant", text: "Erledigt." }],
+ ["MessageSent", { role: "assistant", text: "Something else." }],
+ ]);
+ expect(s.journal.map((l) => l.text)).toEqual(["Erledigt.", "Something else."]);
+ });
+
+ it("logs a typed message once, not once per channel, and never the voice transcript again", () => {
+ const s = fold([
+ ["TranscriptFinal", { transcript: { text: "mach das licht an" } }],
+ ["MessageSent", { role: "user", text: "mach das licht an" }],
+ ["MessageSent", { role: "user", text: "typed instead" }],
+ ]);
+ expect(s.journal.map((l) => [l.labelKey ?? "", l.text])).toEqual([
+ ["", "mach das licht an"],
+ ["deck.log_typed", "typed instead"],
+ ]);
+ });
+
+ it("marks a denied tool and a failed worker as not ok", () => {
+ const s = fold([
+ ["ActionProposed", { tool_name: "run_shell" }],
+ ["ActionDenied", { tool_name: "run_shell" }],
+ ["JarvisAgentTaskStarted", { utterance: "sort my invoices" }],
+ ["JarvisAgentTaskCompleted", { success: false, duration_s: 12.5 }],
+ ]);
+ const tool = s.journal.find((l) => l.kind === "tool")!;
+ expect(tool.ok).toBe(false);
+ expect(tool.labelKey).toBe("deck.log_denied");
+ const worker = s.journal.find((l) => l.kind === "worker")!;
+ expect(worker.ok).toBe(false);
+ expect(worker.ms).toBe(12_500);
+ expect(worker.open).toBe(false);
+ });
+
+ it("closes a brain attempt when the fallback chain starts the next one", () => {
+ const s = fold([
+ ["BrainTurnStarted", { provider: "anthropic", model: "opus" }],
+ ["BrainTurnStarted", { provider: "openrouter", model: "sonnet" }],
+ ["BrainTurnCompleted", { tokens_in: 1, tokens_out: 1 }],
+ ]);
+ const thinks = s.journal.filter((l) => l.kind === "think");
+ // Both closed, both with a duration; only the DONE line says which one answered.
+ expect(thinks.map((l) => [l.text, l.open, l.ms])).toEqual([
+ ["anthropic · opus", false, 100],
+ ["openrouter · sonnet", false, 100],
+ ]);
+ expect(s.journal.at(-1)?.kind).toBe("done");
+ });
+
+ it("notes captures, memory writes, control sessions and errors", () => {
+ const s = fold([
+ ["ScreenCaptureCompleted", { target_label: "Chrome", width: 1920, height: 1080, redaction_count: 2 }],
+ ["WikiPageChanged", { slug: "projects/nova", kind: "updated" }],
+ ["CUControlStarted", { mission_id: "m1" }],
+ ["CUControlEnded", { reason: "finished" }],
+ ["ErrorOccurred", { layer: "brain", message: "rate limited" }],
+ ]);
+ expect(s.journal.map((l) => [l.kind, l.labelKey ?? "", l.text ?? "", l.ok ?? null])).toEqual([
+ ["look", "deck.log_look_redacted", "Chrome · 1920×1080", null],
+ ["memory", "deck.log_memory", "projects/nova · updated", null],
+ ["control", "deck.log_control", "finished", true],
+ ["error", "", "brain: rate limited", false],
+ ]);
+ expect(s.journal[0].args).toEqual({ n: "2" });
+ });
+
+ it("says the voice is ready once, not on every heartbeat", () => {
+ const s = fold([
+ ["VoiceBootStatus", { ready: false }],
+ ["VoiceBootStatus", { ready: true }],
+ ["VoiceBootStatus", { ready: true }],
+ ]);
+ expect(s.journal).toHaveLength(1);
+ expect(s.journal[0].labelKey).toBe("deck.log_voice_ready");
+ });
+
+ it("caps the log", () => {
+ let s = emptyDeckState();
+ for (let i = 0; i < MAX_JOURNAL_LINES + 30; i++) {
+ s = reduceDeck(s, "SpeechSpoken", { text: `line ${i}` }, i);
+ }
+ expect(s.journal).toHaveLength(MAX_JOURNAL_LINES);
+ expect(s.journal[0].text).toBe("line 30");
+ });
+});
+
+describe("the turn", () => {
+ it("follows a voice turn from wake word to the mic reopening, keeping every mark", () => {
+ let s = fold([["WakeWordDetected", { keyword: "nova" }]]);
+ expect(s.turn.index).toBe(1);
+ expect(s.turn.phase).toBe("hear");
+ expect(s.turn.voice).toBe(true);
+ expect(s.turn.anchorTs).toBeNull();
+
+ // LISTENING after the wake word is the hear phase, not the end.
+ s = fold([["SystemStateChanged", { new_state: "LISTENING", previous: "IDLE" }]], s);
+ expect(s.turn.phase).toBe("hear");
+ expect(s.turn.index).toBe(1);
+
+ s = fold(
+ [
+ ["TranscriptFinal", { transcript: { text: "wie spät ist es" } }],
+ ["LatencySpan", { phase: "stt_finalize", duration_ms: 380 }],
+ ["SystemStateChanged", { new_state: "THINKING", previous: "LISTENING" }],
+ ["BrainTurnStarted", { provider: "openrouter", model: "sonnet" }],
+ ["LatencySpan", { phase: "ack_first_audio", duration_ms: 900 }],
+ ["BrainTTFT", { cache_hit: false }],
+ ["LatencySpan", { phase: "brain_first_token", duration_ms: 1300 }],
+ ["ActionProposed", { tool_name: "get_time" }],
+ ],
+ s,
+ );
+ expect(s.turn.index).toBe(1);
+ expect(s.turn.anchorTs).not.toBeNull();
+ expect(s.turn.words).toBe(4);
+ expect(s.turn.sttMs).toBe(380);
+ expect(s.turn.ackMs).toBe(900);
+ expect(s.turn.ttftMs).toBe(1300);
+ expect(s.turn.provider).toBe("openrouter");
+ expect(s.turn.phase).toBe("act");
+ expect(s.turn.tools).toBe(1);
+
+ s = fold(
+ [
+ ["ActionExecuted", { tool_name: "get_time", success: true, duration_ms: 84 }],
+ ["BrainTurnCompleted", { tokens_in: 1200, tokens_out: 88, cost_usd: 0.003, provider: "openrouter", model: "sonnet" }],
+ ["SystemStateChanged", { new_state: "SPEAKING", previous: "THINKING" }],
+ ["LatencySpan", { phase: "turn_to_first_audio", duration_ms: 1900 }],
+ ],
+ s,
+ );
+ expect(s.turn.phase).toBe("speak");
+ expect(s.turn.tokensIn).toBe(1200);
+ expect(s.turn.brainMs).toBeGreaterThan(0);
+ expect(s.turn.firstAudioMs).toBe(1900);
+ expect(s.turn.endedTs).toBeNull();
+
+ s = fold([["SystemStateChanged", { new_state: "LISTENING", previous: "SPEAKING" }]], s);
+ expect(s.turn.phase).toBe("idle");
+ expect(s.turn.endedTs).not.toBeNull();
+ // The figures stay for the card to show as the LAST turn.
+ expect(s.turn.index).toBe(1);
+ expect(s.turn.firstAudioMs).toBe(1900);
+ });
+
+ it("does not count a turn twice when the reply's message lands after the turn closed", () => {
+ let s = fold([
+ ["TranscriptFinal", { transcript: { text: "hallo" } }],
+ ["BrainTurnStarted", { provider: "p", model: "m" }],
+ ["BrainTurnCompleted", {}],
+ ["SystemStateChanged", { new_state: "SPEAKING" }],
+ ["SystemStateChanged", { new_state: "LISTENING" }],
+ ]);
+ expect(s.turn.index).toBe(1);
+ expect(s.turn.phase).toBe("idle");
+ // A late soft signal within the grace period re-opens the same turn…
+ s = fold([["SystemStateChanged", { new_state: "SPEAKING" }]], s);
+ expect(s.turn.index).toBe(1);
+ expect(s.turn.phase).toBe("speak");
+ // …and a follow-up transcript starts turn two.
+ s = fold([["TranscriptFinal", { transcript: { text: "und jetzt" } }]], s);
+ expect(s.turn.index).toBe(2);
+ expect(s.turn.phase).toBe("think");
+ });
+
+ it("ends a typed turn when the reply arrives, and a background brain turn when the brain is done", () => {
+ let s = fold([
+ ["MessageSent", { role: "user", text: "what is the time" }],
+ ["BrainTurnStarted", { provider: "p", model: "m" }],
+ ]);
+ expect(s.turn.voice).toBe(false);
+ expect(s.turn.words).toBe(4);
+ expect(s.turn.phase).toBe("think");
+ s = fold([["BrainTurnCompleted", { tokens_in: 10 }]], s);
+ expect(s.turn.phase).toBe("idle");
+ expect(s.turn.tokensIn).toBe(10);
+
+ // Nobody asked: the brain ran on its own (a summary, a wiki extraction).
+ // It shows as a turn while it runs and is over when it completes.
+ s = reduceDeck(s, "BrainTurnStarted", { provider: "vertex", model: "flash" }, 60_000);
+ expect(s.turn.index).toBe(2);
+ expect(s.turn.phase).toBe("think");
+ s = reduceDeck(s, "BrainTurnCompleted", { tokens_in: 5 }, 61_000);
+ expect(s.turn.phase).toBe("idle");
+ expect(s.turn.brainMs).toBe(1000);
+ });
+
+ it("goes back to thinking when the last tool returns, unless computer use has the screen", () => {
+ let s = fold([
+ ["TranscriptFinal", { transcript: { text: "click save" } }],
+ ["BrainTurnStarted", {}],
+ ["ActionProposed", { tool_name: "a" }],
+ ["ActionProposed", { tool_name: "b" }],
+ ["ActionExecuted", { tool_name: "a", success: true }],
+ ]);
+ expect(s.turn.phase).toBe("act");
+ s = fold([["ActionExecuted", { tool_name: "b", success: false }]], s);
+ expect(s.turn.phase).toBe("think");
+ expect(s.turn.toolsFailed).toBe(1);
+
+ s = fold([["CUControlStarted", { mission_id: "m" }], ["ActionProposed", { tool_name: "click" }], ["ActionExecuted", { tool_name: "click", success: true }]], s);
+ expect(s.turn.cu).toBe(true);
+ expect(s.turn.phase).toBe("act");
+ s = fold([["CUControlEnded", { reason: "finished" }]], s);
+ expect(s.turn.phase).toBe("think");
+ });
+
+ it("fills missing marks from the end-of-turn snapshot and closes on a realtime completion", () => {
+ let s = fold([
+ ["VoiceTurnStarted", { turn_id: "t1" }],
+ ["TranscriptFinal", { transcript: { text: "hey" } }],
+ ["LatencyTurnComplete", { stages_ms: { stt_finalize: 210, brain_first_token: 800, turn_to_first_audio: 1500 } }],
+ ]);
+ expect(s.turn.sttMs).toBe(210);
+ expect(s.turn.ttftMs).toBe(800);
+ expect(s.turn.firstAudioMs).toBe(1500);
+ s = fold([["VoiceTurnCompleted", { provider: "openai", model: "rt", tokens_in: 3, tokens_out: 4, cost_usd: 0.01, tool_calls: ["a", "b"] }]], s);
+ expect(s.turn.phase).toBe("idle");
+ expect(s.turn.provider).toBe("openai");
+ expect(s.turn.tokensIn).toBe(3);
+ expect(s.turn.tools).toBe(2);
+ });
+
+ it("ends the thinking when the brain fails", () => {
+ const s = fold([
+ ["TranscriptFinal", { transcript: { text: "hallo" } }],
+ ["BrainTurnStarted", {}],
+ ["ErrorOccurred", { layer: "brain", message: "boom" }],
+ ]);
+ expect(s.turn.phase).toBe("idle");
+ expect(s.turn.errors).toBe(1);
+ });
+
+ it("keeps a ledger of this session's captures, newest first", () => {
+ let s = emptyDeckState();
+ for (let i = 0; i < MAX_CAPTURES + 2; i++) {
+ s = reduceDeck(s, "ScreenCaptureCompleted", { target_label: `w${i}`, width: 10, height: 10 }, i);
+ }
+ expect(s.captures).toHaveLength(MAX_CAPTURES);
+ expect(s.captures[0].targetLabel).toBe(`w${MAX_CAPTURES + 1}`);
+ expect(s.capture?.seq).toBe(MAX_CAPTURES + 2);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/deckState.ts b/jarvis/ui/web/frontend/src/lib/deckState.ts
index 48a6448882..d9c8ec0ca3 100644
--- a/jarvis/ui/web/frontend/src/lib/deckState.ts
+++ b/jarvis/ui/web/frontend/src/lib/deckState.ts
@@ -5,8 +5,11 @@
* The backend forwards EVERY EventBus event over the WebSocket. This module
* folds the handful the deck cares about into a small, plain state object:
* what the brain has cost this session, what Computer-Use is doing right now,
- * whether a screen capture just happened, the last shell/CLI lines, recent
- * wiki changes, and how many words were spoken.
+ * whether a screen capture just happened (and the ones before it), the last
+ * shell/CLI lines, recent wiki changes, how many words were spoken — and two
+ * things built for the front page alone: the session LOG (one line per thing
+ * the assistant heard, thought, did or said, with timings) and the current
+ * TURN (which phase it is in and how long each stage took).
*
* Every figure here is REAL and sourced from a payload the backend already
* publishes. Nothing is estimated: `BrainTurnCompleted` carries token counts
@@ -87,12 +90,119 @@ export interface WikiChange {
ts: number;
}
+/**
+ * One line of the session log — the deck's terminal.
+ *
+ * `kind` is the tag at the front of the line; `labelKey` the standing phrase
+ * (an i18n key under "deck.log_*", resolved at render time so a language
+ * switch re-labels the past too); `text` the raw runtime detail — a
+ * transcript, a tool name, a model id — which is never translated. `ms` is a
+ * measured duration and `ok === false` marks a failure. `open` is true while
+ * the span the line stands for (a tool call, a brain turn, a worker) is still
+ * running; the same line is closed in place when it finishes.
+ */
+export type JournalKind =
+ | "boot"
+ | "wake"
+ | "hear"
+ | "think"
+ | "done"
+ | "tool"
+ | "say"
+ | "worker"
+ | "control"
+ | "look"
+ | "memory"
+ | "error"
+ | "note";
+
+export interface JournalLine {
+ id: string;
+ ts: number;
+ kind: JournalKind;
+ labelKey?: string;
+ /** Placeholders for `labelKey` ("{in}", "{out}", …), raw runtime values. */
+ args?: Record<string, string>;
+ text?: string;
+ ms?: number;
+ ok?: boolean;
+ open?: boolean;
+}
+
+/**
+ * The turn the assistant is in — or the last one it finished.
+ *
+ * Phases follow the voice loop: `hear` (mic open, transcript pending),
+ * `think` (a brain turn is running), `act` (a tool, a worker or Computer-Use
+ * is doing something on the brain's behalf), `speak` (the answer is being
+ * said). `idle` means no turn is open; the figures then describe the LAST
+ * turn, so the card always has something real to show after the first one.
+ *
+ * Every millisecond figure is measured from `anchorTs`, the moment the
+ * request was complete (the utterance ended / the message was sent) — the
+ * same anchor the backend's latency tracker uses, so "first audio 1.9 s"
+ * here is the number the latency report would print.
+ */
+export type TurnPhase = "idle" | "hear" | "think" | "act" | "speak";
+
+export interface TurnState {
+ /** Turns opened this session; 0 before the first. */
+ index: number;
+ phase: TurnPhase;
+ /** Opened by the voice loop (wake word, mic, transcript) — not typed. */
+ voice: boolean;
+ /** The last event that touched this turn — the card dims a turn gone quiet. */
+ lastEventTs: number | null;
+ /** When the turn became visible (wake word, mic opened, first event). */
+ openedTs: number | null;
+ /** When the request was complete — the clock and every offset run from here. */
+ anchorTs: number | null;
+ /** When the turn closed; null while it is open. */
+ endedTs: number | null;
+ provider: string;
+ model: string;
+ /** Words heard (final transcripts of this turn). */
+ words: number;
+ /** ms from anchor: the recogniser's final transcript. */
+ sttMs: number | null;
+ /** ms from anchor: the instant acknowledgment became audible. */
+ ackMs: number | null;
+ /** ms from anchor: the brain's first token. */
+ ttftMs: number | null;
+ /** ms from anchor: the answer's first audible audio. */
+ firstAudioMs: number | null;
+ /** How long the (last) brain attempt took, start to completed. */
+ brainMs: number | null;
+ /** Wall-clock start of the running brain attempt (internal). */
+ brainStartedTs: number | null;
+ /** BrainTurnStarted count — more than one means the fallback chain ran. */
+ attempts: number;
+ tools: number;
+ toolsFailed: number;
+ toolsOpen: number;
+ workers: number;
+ /** Computer-Use took the screen during this turn. */
+ cu: boolean;
+ tokensIn: number;
+ tokensOut: number;
+ costUsd: number;
+ errors: number;
+ /** True when the last brain attempt was answered from a prompt cache. */
+ cacheHit: boolean;
+}
+
export interface DeckState {
usage: BrainUsage;
cu: CuState;
+ /** The newest capture — what the picture card shows. */
capture: CaptureState | null;
+ /** The captures of this session, newest first — the card's ledger. */
+ captures: CaptureState[];
termLines: TermLine[];
wikiChanges: WikiChange[];
+ /** The session log, oldest first. */
+ journal: JournalLine[];
+ turn: TurnState;
/** Words in every final transcript this session. */
wordsSession: number;
/** Words in the most recent final transcript. */
@@ -104,6 +214,19 @@ export interface DeckState {
/** Hard caps — a long session must not grow any list unbounded. */
export const MAX_TERM_LINES = 80;
export const MAX_WIKI_CHANGES = 12;
+export const MAX_JOURNAL_LINES = 160;
+export const MAX_CAPTURES = 8;
+
+/**
+ * A soft signal (a brain start, a state change, a latency mark) arriving this
+ * soon after a turn closed re-opens THAT turn rather than starting another:
+ * the reply's speech and its chat message do not arrive in a fixed order, and
+ * a turn must not be counted twice for that.
+ */
+export const TURN_REOPEN_GRACE_MS = 5_000;
+
+/** How much of a transcript or reply the log keeps on one line. */
+const LOG_TEXT_MAX = 120;
const CU_PHASES: readonly CuPhase[] = ["observe", "uia", "plan", "think", "act", "verify"];
@@ -135,14 +258,49 @@ export function emptyDeckState(): DeckState {
endedReason: "",
},
capture: null,
+ captures: [],
termLines: [],
wikiChanges: [],
+ journal: [],
+ turn: emptyTurn(),
wordsSession: 0,
wordsLast: 0,
utterances: 0,
};
}
+export function emptyTurn(): TurnState {
+ return {
+ index: 0,
+ phase: "idle",
+ voice: false,
+ lastEventTs: null,
+ openedTs: null,
+ anchorTs: null,
+ endedTs: null,
+ provider: "",
+ model: "",
+ words: 0,
+ sttMs: null,
+ ackMs: null,
+ ttftMs: null,
+ firstAudioMs: null,
+ brainMs: null,
+ brainStartedTs: null,
+ attempts: 0,
+ tools: 0,
+ toolsFailed: 0,
+ toolsOpen: 0,
+ workers: 0,
+ cu: false,
+ tokensIn: 0,
+ tokensOut: 0,
+ costUsd: 0,
+ errors: 0,
+ cacheHit: false,
+ };
+}
+
let seq = 0;
function nextId(): string {
seq += 1;
@@ -199,7 +357,9 @@ function pushLines(lines: TermLine[], added: TermLine[]): TermLine[] {
*
* Returns the SAME object when the event is not one the deck reads, so a
* store can bail out without a re-render — the wildcard forwarder delivers
- * every event, and most of them are not for the deck.
+ * every event, and most of them are not for the deck. Three folds in a row,
+ * each pure and each returning its input untouched when the event is not
+ * for it: the cards' figures, the session log, the turn.
*/
export function reduceDeck(
state: DeckState,
@@ -208,7 +368,18 @@ export function reduceDeck(
tsMs: number,
): DeckState {
const p = obj(payload);
+ let next = reduceCards(state, name, p, tsMs);
+ next = reduceJournal(next, name, p, tsMs);
+ next = reduceTurn(next, name, p, tsMs);
+ return next;
+}
+function reduceCards(
+ state: DeckState,
+ name: string,
+ p: Record<string, unknown>,
+ tsMs: number,
+): DeckState {
switch (name) {
// ---- brain: what this session has cost ------------------------------
case "BrainTurnCompleted": {
@@ -327,19 +498,22 @@ export function reduceDeck(
}
// ---- screen capture: the one-shot look --------------------------------
- case "ScreenCaptureCompleted":
+ case "ScreenCaptureCompleted": {
+ const capture: CaptureState = {
+ seq: (state.capture?.seq ?? 0) + 1,
+ ts: tsMs,
+ targetKind: str(p.target_kind),
+ targetLabel: str(p.target_label),
+ width: num(p.width),
+ height: num(p.height),
+ redactions: num(p.redaction_count),
+ };
return {
...state,
- capture: {
- seq: (state.capture?.seq ?? 0) + 1,
- ts: tsMs,
- targetKind: str(p.target_kind),
- targetLabel: str(p.target_label),
- width: num(p.width),
- height: num(p.height),
- redactions: num(p.redaction_count),
- },
+ capture,
+ captures: [capture, ...state.captures].slice(0, MAX_CAPTURES),
};
+ }
// ---- terminals: shell + CLI ---------------------------------------------
case "TerminalCommandExecuted": {
@@ -416,3 +590,624 @@ export function reduceDeck(
return state;
}
}
+
+// ----------------------------------------------------------------------
+// The session log — one line per thing heard, thought, done or said
+// ----------------------------------------------------------------------
+
+function clip(text: string, max = LOG_TEXT_MAX): string {
+ const clean = text.replace(/\s+/g, " ").trim();
+ return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
+}
+
+function fmtTokens(n: number): string {
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2)}M`;
+ if (n >= 10_000) return `${(n / 1_000).toFixed(1)}k`;
+ if (n >= 1_000) return `${(n / 1_000).toFixed(2)}k`;
+ return String(n);
+}
+
+function fmtUsd(n: number): string {
+ if (n === 0) return "$0";
+ if (n < 0.01) return `$${n.toFixed(4)}`;
+ return `$${n.toFixed(2)}`;
+}
+
+function appendLine(journal: JournalLine[], line: Omit<JournalLine, "id">): JournalLine[] {
+ const next = journal.concat({ id: nextId(), ...line });
+ return next.length > MAX_JOURNAL_LINES ? next.slice(next.length - MAX_JOURNAL_LINES) : next;
+}
+
+/**
+ * Index of the newest OPEN line of `kind` — preferring one that carries this
+ * exact `text` (tool calls interleave), else the newest open one of the kind.
+ */
+function findOpen(journal: JournalLine[], kind: JournalKind, text?: string): number {
+ let fallback = -1;
+ for (let i = journal.length - 1; i >= 0; i--) {
+ const line = journal[i];
+ if (line.kind !== kind || !line.open) continue;
+ if (text && line.text === text) return i;
+ if (fallback === -1) fallback = i;
+ }
+ return fallback;
+}
+
+/** Close an open line in place: duration, outcome, optionally a new label. */
+function closeLine(
+ journal: JournalLine[],
+ index: number,
+ tsMs: number,
+ patch: Partial<Pick<JournalLine, "ms" | "ok" | "labelKey" | "text">>,
+): JournalLine[] {
+ const line = journal[index];
+ const next = [...journal];
+ next[index] = {
+ ...line,
+ open: false,
+ ms: patch.ms ?? Math.max(0, tsMs - line.ts),
+ ok: patch.ok ?? true,
+ ...(patch.labelKey ? { labelKey: patch.labelKey } : {}),
+ ...(patch.text !== undefined ? { text: patch.text } : {}),
+ };
+ return next;
+}
+
+/** True when one of the last few lines already says this (a reply arrives on two channels). */
+function recentlySaid(journal: JournalLine[], kind: JournalKind, text: string, within = 8): boolean {
+ for (let i = journal.length - 1; i >= 0 && i >= journal.length - within; i--) {
+ const line = journal[i];
+ if (line.kind === kind && line.text === text) return true;
+ }
+ return false;
+}
+
+function withJournal(state: DeckState, journal: JournalLine[]): DeckState {
+ return journal === state.journal ? state : { ...state, journal };
+}
+
+function reduceJournal(
+ state: DeckState,
+ name: string,
+ p: Record<string, unknown>,
+ tsMs: number,
+): DeckState {
+ const journal = state.journal;
+
+ switch (name) {
+ // ---- boot ---------------------------------------------------------------
+ case "VoiceBootStatus": {
+ if (p.ready !== true) return state;
+ const last = [...journal].reverse().find((l) => l.kind === "boot");
+ if (last && last.labelKey === "deck.log_voice_ready") return state;
+ return withJournal(state, appendLine(journal, { ts: tsMs, kind: "boot", labelKey: "deck.log_voice_ready" }));
+ }
+ case "BrainProviderSwitched": {
+ const provider = str(p.provider) || str(p.new_provider);
+ return withJournal(
+ state,
+ appendLine(journal, { ts: tsMs, kind: "boot", labelKey: "deck.log_brain_switched", text: provider || undefined }),
+ );
+ }
+
+ // ---- wake ---------------------------------------------------------------
+ case "WakeWordDetected": {
+ const keyword = str(p.keyword);
+ const confidence = num(p.confidence);
+ const text = [keyword, confidence > 0 ? confidence.toFixed(2) : ""].filter(Boolean).join(" · ");
+ return withJournal(state, appendLine(journal, { ts: tsMs, kind: "wake", labelKey: "deck.log_wake", text: text || undefined }));
+ }
+ case "HotkeyPressed":
+ return withJournal(
+ state,
+ appendLine(journal, { ts: tsMs, kind: "wake", labelKey: "deck.log_hotkey", text: str(p.combo) || undefined }),
+ );
+ case "VoiceSessionEnded": {
+ const turns = num(p.turn_count);
+ const reason = str(p.hangup_reason);
+ return withJournal(
+ state,
+ appendLine(journal, {
+ ts: tsMs,
+ kind: "note",
+ labelKey: "deck.log_session_ended",
+ args: { turns: String(turns) },
+ text: reason || undefined,
+ ms: num(p.duration_s) * 1000 || undefined,
+ }),
+ );
+ }
+
+ // ---- hear ---------------------------------------------------------------
+ case "TranscriptFinal": {
+ const text = clip(str(obj(p.transcript).text));
+ if (!text) return state;
+ return withJournal(
+ state,
+ appendLine(journal, {
+ ts: tsMs,
+ kind: "hear",
+ labelKey: p.continues_previous === true ? "deck.log_hear_more" : undefined,
+ text,
+ }),
+ );
+ }
+
+ // ---- think --------------------------------------------------------------
+ case "BrainTurnStarted": {
+ const text = [str(p.provider), str(p.model)].filter(Boolean).join(" · ");
+ // A new attempt closes the one before it — the fallback chain moved
+ // on, or a second brain call started alongside. Neither is a failure
+ // this reducer can vouch for, so the line closes with its duration and
+ // no verdict; a real error arrives as ErrorOccurred and gets its line.
+ const idx = findOpen(journal, "think");
+ const closed = idx === -1 ? journal : closeLine(journal, idx, tsMs, {});
+ return withJournal(state, appendLine(closed, { ts: tsMs, kind: "think", text: text || undefined, open: true }));
+ }
+ case "BrainTTFT": {
+ const idx = findOpen(journal, "think");
+ return withJournal(
+ state,
+ appendLine(journal, {
+ ts: tsMs,
+ kind: "note",
+ labelKey: "deck.log_first_token",
+ ms: idx === -1 ? undefined : Math.max(0, tsMs - journal[idx].ts),
+ text: p.cache_hit === true ? "cache" : undefined,
+ }),
+ );
+ }
+ case "BrainTurnCompleted": {
+ const idx = findOpen(journal, "think");
+ const closed = idx === -1 ? journal : closeLine(journal, idx, tsMs, {});
+ return withJournal(
+ state,
+ appendLine(closed, {
+ ts: tsMs,
+ kind: "done",
+ labelKey: "deck.log_done",
+ args: {
+ in: fmtTokens(num(p.tokens_in)),
+ out: fmtTokens(num(p.tokens_out)),
+ cost: fmtUsd(num(p.cost_usd)),
+ },
+ ms: idx === -1 ? undefined : Math.max(0, tsMs - journal[idx].ts),
+ }),
+ );
+ }
+
+ // ---- tools --------------------------------------------------------------
+ case "ToolCallStarted":
+ case "ActionProposed": {
+ const tool = str(p.tool_name);
+ if (!tool) return state;
+ // The same call may be announced by both event families.
+ const dup = findOpen(journal, "tool", tool);
+ if (dup !== -1 && journal[dup].text === tool) return state;
+ return withJournal(state, appendLine(journal, { ts: tsMs, kind: "tool", text: tool, open: true }));
+ }
+ case "ToolCallCompleted":
+ case "ActionExecuted": {
+ const tool = str(p.tool_name);
+ const ok = p.success !== false;
+ const ms = num(p.duration_ms) || undefined;
+ const idx = findOpen(journal, "tool", tool);
+ if (idx !== -1) return withJournal(state, closeLine(journal, idx, tsMs, { ms, ok }));
+ if (name === "ActionExecuted" && tool) {
+ return withJournal(state, appendLine(journal, { ts: tsMs, kind: "tool", text: tool, ms, ok }));
+ }
+ return state;
+ }
+ case "ActionDenied": {
+ const idx = findOpen(journal, "tool", str(p.tool_name));
+ if (idx === -1) return state;
+ return withJournal(state, closeLine(journal, idx, tsMs, { ok: false, labelKey: "deck.log_denied" }));
+ }
+
+ // ---- say ----------------------------------------------------------------
+ case "SpeechSpoken": {
+ const text = clip(str(p.text));
+ if (!text || recentlySaid(journal, "say", text)) return state;
+ const kind = str(p.spoken_kind);
+ return withJournal(
+ state,
+ appendLine(journal, {
+ ts: tsMs,
+ kind: "say",
+ labelKey: kind === "preamble" ? "deck.log_ack" : undefined,
+ text,
+ }),
+ );
+ }
+ case "MessageSent": {
+ const role = str(p.role);
+ const text = clip(str(p.text));
+ if (!text) return state;
+ if (role === "user") {
+ // A voice turn's transcript reaches the log through TranscriptFinal;
+ // this only adds a TYPED message.
+ if (recentlySaid(journal, "hear", text)) return state;
+ return withJournal(state, appendLine(journal, { ts: tsMs, kind: "hear", labelKey: "deck.log_typed", text }));
+ }
+ if (role === "assistant" || role === "preamble") {
+ if (recentlySaid(journal, "say", text)) return state;
+ return withJournal(
+ state,
+ appendLine(journal, {
+ ts: tsMs,
+ kind: "say",
+ labelKey: role === "preamble" ? "deck.log_ack" : undefined,
+ text,
+ }),
+ );
+ }
+ if (role === "system") {
+ return withJournal(state, appendLine(journal, { ts: tsMs, kind: "note", text }));
+ }
+ return state;
+ }
+ case "LatencySpan": {
+ const phase = str(p.phase);
+ const ms = num(p.duration_ms);
+ if (phase === "turn_to_first_audio" || phase === "realtime_first_audio") {
+ return withJournal(state, appendLine(journal, { ts: tsMs, kind: "note", labelKey: "deck.log_first_audio", ms }));
+ }
+ if (phase === "ack_first_audio") {
+ return withJournal(state, appendLine(journal, { ts: tsMs, kind: "note", labelKey: "deck.log_ack_audio", ms }));
+ }
+ return state;
+ }
+ case "AnnouncementRequested": {
+ if (str(p.kind) !== "progress") return state;
+ const text = clip(str(p.text), 80);
+ if (!text) return state;
+ return withJournal(state, appendLine(journal, { ts: tsMs, kind: "note", labelKey: "deck.log_progress", text }));
+ }
+
+ // ---- workers, control, look, memory ---------------------------------------
+ case "JarvisAgentTaskStarted":
+ return withJournal(
+ state,
+ appendLine(journal, {
+ ts: tsMs,
+ kind: "worker",
+ labelKey: "deck.log_worker",
+ text: clip(str(p.utterance), 80) || undefined,
+ open: true,
+ }),
+ );
+ case "JarvisAgentTaskCompleted": {
+ const idx = findOpen(journal, "worker");
+ if (idx === -1) return state;
+ return withJournal(
+ state,
+ closeLine(journal, idx, tsMs, { ms: num(p.duration_s) * 1000 || undefined, ok: p.success !== false }),
+ );
+ }
+ case "CUControlStarted":
+ return withJournal(
+ state,
+ appendLine(journal, {
+ ts: tsMs,
+ kind: "control",
+ labelKey: "deck.log_control",
+ text: str(p.mission_id) || undefined,
+ open: true,
+ }),
+ );
+ case "CUControlEnded": {
+ const idx = findOpen(journal, "control");
+ const reason = str(p.reason);
+ const ok = reason !== "error" && reason !== "failed";
+ if (idx === -1) {
+ return withJournal(
+ state,
+ appendLine(journal, { ts: tsMs, kind: "control", labelKey: "deck.log_control_ended", text: reason || undefined, ok }),
+ );
+ }
+ return withJournal(state, closeLine(journal, idx, tsMs, { text: reason || journal[idx].text, ok }));
+ }
+ case "ScreenCaptureCompleted": {
+ const size = num(p.width) && num(p.height) ? `${num(p.width)}×${num(p.height)}` : "";
+ const text = [str(p.target_label), size].filter(Boolean).join(" · ");
+ const redactions = num(p.redaction_count);
+ return withJournal(
+ state,
+ appendLine(journal, {
+ ts: tsMs,
+ kind: "look",
+ labelKey: redactions > 0 ? "deck.log_look_redacted" : "deck.log_look",
+ args: redactions > 0 ? { n: String(redactions) } : undefined,
+ text: text || undefined,
+ }),
+ );
+ }
+ case "WikiPageChanged": {
+ const slug = str(p.slug);
+ if (!slug) return state;
+ const kind = str(p.kind);
+ return withJournal(
+ state,
+ appendLine(journal, { ts: tsMs, kind: "memory", labelKey: "deck.log_memory", text: kind ? `${slug} · ${kind}` : slug }),
+ );
+ }
+ case "ErrorOccurred": {
+ const layer = str(p.layer) || str(p.source_layer);
+ const message = clip(str(p.message), 100);
+ const text = [layer, message].filter(Boolean).join(": ");
+ if (!text) return state;
+ return withJournal(state, appendLine(journal, { ts: tsMs, kind: "error", text, ok: false }));
+ }
+ default:
+ return state;
+ }
+}
+
+// ----------------------------------------------------------------------
+// The turn — which phase, and how long each stage took
+// ----------------------------------------------------------------------
+
+function withTurn(state: DeckState, turn: TurnState): DeckState {
+ return turn === state.turn ? state : { ...state, turn };
+}
+
+/** A fresh turn, closing whatever was open. */
+function openTurn(state: DeckState, tsMs: number, init: Partial<TurnState>): TurnState {
+ return {
+ ...emptyTurn(),
+ index: state.turn.index + 1,
+ openedTs: tsMs,
+ lastEventTs: tsMs,
+ ...init,
+ };
+}
+
+/** A turn that closed this recently is re-opened by a soft signal, not doubled. */
+function justClosed(turn: TurnState, tsMs: number): boolean {
+ return turn.phase === "idle" && turn.endedTs !== null && tsMs - turn.endedTs <= TURN_REOPEN_GRACE_MS;
+}
+
+/**
+ * The turn a soft signal belongs to: the open one, the one that closed a
+ * moment ago (re-opened), or — when neither — a new one anchored now.
+ */
+function joinTurn(state: DeckState, tsMs: number, phase: TurnPhase): TurnState {
+ const turn = state.turn;
+ if (turn.phase !== "idle") return { ...turn, phase, lastEventTs: tsMs };
+ if (justClosed(turn, tsMs)) return { ...turn, phase, endedTs: null, lastEventTs: tsMs };
+ return openTurn(state, tsMs, { phase, anchorTs: tsMs });
+}
+
+function endTurn(turn: TurnState, tsMs: number): TurnState {
+ if (turn.phase === "idle") return turn;
+ return { ...turn, phase: "idle", endedTs: tsMs, lastEventTs: tsMs, toolsOpen: 0 };
+}
+
+/** ms from the turn's anchor to now, or null before the request was complete. */
+function sinceAnchor(turn: TurnState, tsMs: number): number | null {
+ return turn.anchorTs === null ? null : Math.max(0, tsMs - turn.anchorTs);
+}
+
+function reduceTurn(
+ state: DeckState,
+ name: string,
+ p: Record<string, unknown>,
+ tsMs: number,
+): DeckState {
+ const turn = state.turn;
+
+ switch (name) {
+ // ---- hard starters: a person began a turn ------------------------------
+ case "WakeWordDetected":
+ case "HotkeyPressed":
+ case "VoiceTurnStarted":
+ return withTurn(state, openTurn(state, tsMs, { phase: "hear", voice: true }));
+
+ case "TranscriptFinal": {
+ const words = countWords(str(obj(p.transcript).text));
+ if (words === 0) return state;
+ if (p.continues_previous === true && turn.phase !== "idle") {
+ return withTurn(state, { ...turn, words: turn.words + words, lastEventTs: tsMs });
+ }
+ // The mic was opened for this utterance (wake word / follow-up): the
+ // transcript completes THAT turn's request rather than opening another.
+ if (turn.phase === "hear" && turn.anchorTs === null) {
+ return withTurn(state, { ...turn, phase: "think", anchorTs: tsMs, words, voice: true, lastEventTs: tsMs });
+ }
+ return withTurn(state, openTurn(state, tsMs, { phase: "think", anchorTs: tsMs, words, voice: true }));
+ }
+
+ case "MessageSent": {
+ const role = str(p.role);
+ if (role === "user") {
+ // Typed. A voice transcript already opened the turn — do not reopen.
+ if (turn.phase !== "idle" || justClosed(turn, tsMs)) return state;
+ return withTurn(
+ state,
+ openTurn(state, tsMs, { phase: "think", anchorTs: tsMs, words: countWords(str(p.text)), voice: false }),
+ );
+ }
+ if (role === "assistant" && !turn.voice && turn.phase !== "idle") {
+ return withTurn(state, endTurn(turn, tsMs));
+ }
+ return state;
+ }
+
+ // ---- the brain ----------------------------------------------------------
+ case "BrainTurnStarted": {
+ const joined = joinTurn(state, tsMs, "think");
+ return withTurn(state, {
+ ...joined,
+ provider: str(p.provider) || joined.provider,
+ model: str(p.model) || joined.model,
+ attempts: joined.attempts + 1,
+ brainStartedTs: tsMs,
+ brainMs: null,
+ });
+ }
+ case "BrainTTFT": {
+ if (turn.phase === "idle") return state;
+ const estimate = sinceAnchor(turn, tsMs) ?? (turn.brainStartedTs === null ? null : tsMs - turn.brainStartedTs);
+ return withTurn(state, {
+ ...turn,
+ ttftMs: turn.ttftMs ?? estimate,
+ cacheHit: p.cache_hit === true,
+ model: str(p.model) || turn.model,
+ lastEventTs: tsMs,
+ });
+ }
+ case "BrainTurnCompleted": {
+ if (turn.phase === "idle" && !justClosed(turn, tsMs)) return state;
+ const joined = joinTurn(state, tsMs, turn.phase === "idle" ? "think" : turn.phase);
+ const done: TurnState = {
+ ...joined,
+ brainMs: joined.brainStartedTs === null ? joined.brainMs : Math.max(0, tsMs - joined.brainStartedTs),
+ brainStartedTs: null,
+ provider: str(p.provider) || joined.provider,
+ model: str(p.model) || joined.model,
+ tokensIn: joined.tokensIn + num(p.tokens_in),
+ tokensOut: joined.tokensOut + num(p.tokens_out),
+ costUsd: joined.costUsd + num(p.cost_usd),
+ lastEventTs: tsMs,
+ };
+ // A voice turn goes on to speak; anything else (a typed chat, a turn
+ // the brain ran on its own) is over when the brain is.
+ if (!done.voice) return withTurn(state, endTurn(done, tsMs));
+ return withTurn(state, { ...done, phase: done.toolsOpen > 0 ? "act" : "speak" });
+ }
+
+ // ---- tools, computer use, workers -----------------------------------------
+ case "ToolCallStarted":
+ case "ActionProposed": {
+ if (!str(p.tool_name)) return state;
+ const joined = joinTurn(state, tsMs, "act");
+ return withTurn(state, { ...joined, tools: joined.tools + 1, toolsOpen: joined.toolsOpen + 1 });
+ }
+ case "ToolCallCompleted":
+ case "ActionExecuted":
+ case "ActionDenied": {
+ if (turn.phase === "idle") return state;
+ const failed = name === "ActionDenied" || p.success === false;
+ const toolsOpen = Math.max(0, turn.toolsOpen - 1);
+ const backToThinking = toolsOpen === 0 && turn.phase === "act" && !turn.cu;
+ return withTurn(state, {
+ ...turn,
+ toolsOpen,
+ toolsFailed: turn.toolsFailed + (failed ? 1 : 0),
+ phase: backToThinking ? "think" : turn.phase,
+ lastEventTs: tsMs,
+ });
+ }
+ case "CUControlStarted": {
+ const joined = joinTurn(state, tsMs, "act");
+ return withTurn(state, { ...joined, cu: true });
+ }
+ case "CUControlEnded": {
+ if (turn.phase === "idle") return state;
+ return withTurn(state, {
+ ...turn,
+ phase: turn.toolsOpen > 0 ? "act" : turn.brainStartedTs !== null ? "think" : turn.phase,
+ lastEventTs: tsMs,
+ });
+ }
+ case "JarvisAgentTaskStarted": {
+ if (turn.phase === "idle") return state;
+ return withTurn(state, { ...turn, workers: turn.workers + 1, lastEventTs: tsMs });
+ }
+
+ // ---- the measured marks ---------------------------------------------------
+ case "LatencySpan": {
+ if (turn.phase === "idle" && !justClosed(turn, tsMs)) return state;
+ const patch = latencyPatch(turn, str(p.phase), num(p.duration_ms));
+ if (!patch) return state;
+ return withTurn(state, { ...turn, ...patch, lastEventTs: tsMs });
+ }
+ case "LatencyTurnComplete": {
+ if (turn.phase === "idle" && !justClosed(turn, tsMs)) return state;
+ const stages = obj(p.stages_ms);
+ let next = turn;
+ for (const [phase, value] of Object.entries(stages)) {
+ const patch = latencyPatch(next, phase, num(value));
+ if (patch) next = { ...next, ...patch };
+ }
+ return withTurn(state, next === turn ? turn : { ...next, lastEventTs: tsMs });
+ }
+ case "AudioOutFirst": {
+ if (turn.phase === "idle") return state;
+ return withTurn(state, {
+ ...turn,
+ phase: "speak",
+ firstAudioMs: turn.firstAudioMs ?? sinceAnchor(turn, tsMs),
+ lastEventTs: tsMs,
+ });
+ }
+
+ // ---- the supervisor's state: the phase, and the end ------------------------
+ case "SystemStateChanged": {
+ const next = str(p.new_state).toLowerCase();
+ if (next === "thinking") {
+ const joined = joinTurn(state, tsMs, turn.phase === "act" ? "act" : "think");
+ return withTurn(state, { ...joined, voice: true });
+ }
+ if (next === "speaking") {
+ const joined = joinTurn(state, tsMs, "speak");
+ return withTurn(state, { ...joined, voice: true });
+ }
+ if (next === "listening" || next === "idle") {
+ // Back to the mic after speaking (or an interrupted answer): over.
+ // LISTENING right after the wake word is the turn's own `hear` phase.
+ if (turn.phase === "hear" || turn.phase === "idle") return state;
+ return withTurn(state, endTurn(turn, tsMs));
+ }
+ return state;
+ }
+ case "VoiceTurnCompleted": {
+ if (turn.phase === "idle" && !justClosed(turn, tsMs)) return state;
+ const joined: TurnState = turn.phase === "idle" ? { ...turn, phase: "speak" } : turn;
+ const filled: TurnState = {
+ ...joined,
+ provider: joined.provider || str(p.provider),
+ model: joined.model || str(p.model),
+ tokensIn: joined.attempts > 0 ? joined.tokensIn : num(p.tokens_in),
+ tokensOut: joined.attempts > 0 ? joined.tokensOut : num(p.tokens_out),
+ costUsd: joined.attempts > 0 ? joined.costUsd : num(p.cost_usd),
+ tools: Math.max(joined.tools, Array.isArray(p.tool_calls) ? p.tool_calls.length : 0),
+ };
+ return withTurn(state, endTurn(filled, tsMs));
+ }
+ case "ErrorOccurred": {
+ if (turn.phase === "idle") return state;
+ const layer = str(p.layer) || str(p.source_layer);
+ const counted = { ...turn, errors: turn.errors + 1, lastEventTs: tsMs };
+ // The brain failing ends the thinking; anything else is noted.
+ if (layer === "brain" && (turn.phase === "think" || turn.phase === "act")) {
+ return withTurn(state, endTurn(counted, tsMs));
+ }
+ return withTurn(state, counted);
+ }
+ default:
+ return state;
+ }
+}
+
+/** Which turn figure a latency mark fills, if any — the first mark wins. */
+function latencyPatch(turn: TurnState, phase: string, ms: number): Partial<TurnState> | null {
+ if (!Number.isFinite(ms) || ms < 0) return null;
+ switch (phase) {
+ case "stt_finalize":
+ return turn.sttMs === null ? { sttMs: ms } : null;
+ case "ack_first_audio":
+ return turn.ackMs === null ? { ackMs: ms } : null;
+ case "brain_first_token":
+ case "realtime_first_transcript":
+ // Precise where BrainTTFT's wall-clock delta was an estimate.
+ return { ttftMs: ms };
+ case "turn_to_first_audio":
+ case "realtime_first_audio":
+ return { firstAudioMs: ms };
+ case "brain_first_audio":
+ return turn.firstAudioMs === null ? { firstAudioMs: ms } : null;
+ default:
+ return null;
+ }
+}
diff --git a/jarvis/ui/web/frontend/src/views/MissionDeckView.tsx b/jarvis/ui/web/frontend/src/views/MissionDeckView.tsx
index 98a6ab1054..e6f3489d68 100644
--- a/jarvis/ui/web/frontend/src/views/MissionDeckView.tsx
+++ b/jarvis/ui/web/frontend/src/views/MissionDeckView.tsx
@@ -7,18 +7,14 @@ import { DeckDock } from "@/components/deck/DeckDock";
import { DeckOrb } from "@/components/deck/DeckOrb";
import { HudLamp } from "@/components/deck/HudFrame";
import {
- FlowCard,
IdeGridCard,
OutputsCard,
RunsCard,
TerminalsCard,
} from "@/components/deck/DeckActivityCards";
-import {
- ApiStatsCard,
- AppShotCard,
- ComputerUseCard,
- LiveCounter,
-} from "@/components/deck/DeckSignalCards";
+import { ApiStatsCard, CaptureCard, LiveCounter } from "@/components/deck/DeckSignalCards";
+import { LogCard } from "@/components/deck/DeckLogCard";
+import { TurnCard } from "@/components/deck/DeckTurnCard";
import { WikiCard } from "@/components/deck/DeckWiki";
import { useVoiceReadiness } from "@/hooks/useVoiceReadiness";
import { writeDeckMode } from "@/lib/deckMode";
@@ -35,11 +31,20 @@ import { useT } from "@/i18n";
* rotated; read upright):
*
* ┌ voice bars · lamps · live counter ─────────── name · brain · switch ┐
- * │ dock │ [right now] [computer use][api] [ WIKI — 3D, tall ] │
- * │ │ ( ORB ) [ ] │
- * │ │ [outputs][run] [app shot] [terminals] [ide grid] │
+ * │ dock │ [log — the [response][api] [ WIKI — 3D, tall ] │
+ * │ │ terminal] ( ORB ) [ ] │
+ * │ │ [outputs][run] [capture] [terminals] [ide grid] │
* └──────┴───────────────────────────────────────────────────────────────┘
*
+ * Two of the sketch's cards were re-thought on 2026-08-18 (maintainer): the
+ * "right now" trace doubled the run inspector, which the small RUNS card
+ * already opens, so the tall left slot is now the LOG — a terminal of what
+ * the assistant heard, thought, did and said, with timings, that is never
+ * blank; and the live Computer-Use screen mirror gave way to the RESPONSE
+ * instrument — the turn's phases and how long each stage took. Computer Use
+ * still shows: as the "control" lamp, as the response card's act phase, and
+ * as lines in the log.
+ *
* Every card is a window onto a section and reads that section's own data;
* its title jumps there. The dock on the left is the ONLY place the sections
* are listed — the sidebar steps aside while the deck is up (App.tsx).
@@ -68,13 +73,21 @@ export function MissionDeckView({
const setActiveSection = useEventStore((s) => s.setActiveSection);
const cuActive = useDeckStore((s) => s.cu.active);
const wordsSession = useDeckStore((s) => s.wordsSession);
+ const turnPhase = useDeckStore((s) => s.turn.phase);
const { warming } = useVoiceReadiness();
const running = useMemo(
() => thinkingSteps.filter((s) => s.status === "active"),
[thinkingSteps],
);
- const busy = chatThinking || running.length > 0 || voiceState === "thinking";
+ // The deck's own turn counts too: the text chat's thinking flag never arms
+ // for a voice turn, and the orb must sweep for those as well.
+ const busy =
+ chatThinking ||
+ running.length > 0 ||
+ voiceState === "thinking" ||
+ turnPhase === "think" ||
+ turnPhase === "act";
const mood: DeckMood = !connected
? "offline"
@@ -170,13 +183,13 @@ export function MissionDeckView({
<DeckDock />
<div className="grid min-h-0 flex-1 grid-cols-1 gap-3 overflow-y-auto p-3 lg:grid-cols-[minmax(200px,3fr)_minmax(0,6fr)_minmax(240px,4fr)] lg:grid-rows-[minmax(0,1fr)_minmax(0,0.6fr)] lg:overflow-hidden">
- {/* LEFT top: what is happening right now */}
- <FlowCard steps={thinkingSteps} className="min-h-0" />
+ {/* LEFT top: the log — the terminal of the session */}
+ <LogCard className="min-h-0" />
- {/* CENTRE top: computer use + api on a strip, the orb underneath */}
+ {/* CENTRE top: the response instrument + api on a strip, the orb underneath */}
<div className="flex min-h-0 flex-col gap-3">
<div className="grid shrink-0 grid-cols-2 gap-3" style={{ height: "36%" }}>
- <ComputerUseCard className="min-h-0" />
+ <TurnCard className="min-h-0" />
<ApiStatsCard className="min-h-0" />
</div>
<div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-2 px-2 text-center">
@@ -206,9 +219,9 @@ export function MissionDeckView({
<RunsCard className="min-h-0" />
</div>
- {/* CENTRE bottom: the last capture, centred and not too wide */}
+ {/* CENTRE bottom: the last capture (briefly), then the ledger; centred and not too wide */}
<div className="flex min-h-[8rem] items-stretch justify-center">
- <AppShotCard className="w-full max-w-[28rem]" />
+ <CaptureCard className="w-full max-w-[28rem]" />
</div>
{/* RIGHT bottom: terminals and the coding workspace */}
diff --git a/tests/unit/screen_context/test_service.py b/tests/unit/screen_context/test_service.py
index 94e6d44bd6..66872e591a 100644
--- a/tests/unit/screen_context/test_service.py
+++ b/tests/unit/screen_context/test_service.py
@@ -871,6 +871,33 @@ async def test_the_capture_is_announced_before_the_shutter() -> None:
]
+async def test_the_deck_mirror_is_filled_before_the_receipt_goes_out() -> None:
+ """The deck fetches the picture the moment it hears the receipt.
+
+ The bus awaits the WebSocket send inside ``publish``, so a mirror filled
+ AFTER the receipt let the front page ask for a frame that was not there
+ yet — or get the previous capture under the new receipt's number.
+ """
+ from jarvis.screen_context.last_frame import LastFrameMirror
+
+ mirror = LastFrameMirror(ttl_s=120)
+ seen_at_receipt: list[int | None] = []
+
+ class PeekingBus(RecordingBus):
+ async def publish(self, event) -> None:
+ await super().publish(event)
+ if type(event).__name__ == "ScreenCaptureCompleted":
+ held = mirror.get()
+ seen_at_receipt.append(None if held is None else held.seq)
+
+ service = make_service(bus=PeekingBus(), last_frame_mirror=mirror)
+
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert outcome.status == "captured"
+ assert seen_at_receipt == [1], "the picture must be held when the receipt is published"
+
+
async def test_capture_events_keep_the_turn_trace_id() -> None:
from uuid import uuid4