Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(deck): the full mission deck — dock, orb, and a card for every signal
Haraldb8edf7ebde2b
diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsxindex f982ee8853..146711b93c 100644--- a/jarvis/ui/web/frontend/src/App.tsx+++ b/jarvis/ui/web/frontend/src/App.tsx@@ -1,6 +1,7 @@import { useCallback, useEffect, useState } from "react";import { isSectionId, useEventStore } from "@/store/events";+import { useDeckStore } from "@/store/deck";import { useWebSocket } from "@/hooks/useWebSocket";import { useBrainStatus } from "@/hooks/useBrainStatus";import { useVoiceStatus } from "@/hooks/useVoiceStatus";@@ -235,6 +236,16 @@ export default function App() {const activeSection = useEventStore((s) => s.activeSection);const solo = useEventStore((s) => s.solo);const detachedViews = useEventStore((s) => s.detachedViews);+ const deckMode = useDeckStore((s) => s.mode);++ /*+ * The mission deck is a full stage: it brings its own section dock, so the+ * sidebar (and the resizer that belongs to it) steps aside while the deck is+ * on screen. Every other section — and the classic chat view behind the+ * deck's switch — keeps the sidebar exactly as before; a section reached+ * from the dock lands there.+ */+ const deckOnStage = activeSection === "chats" && deckMode === "deck";/** The realtime broker must exist exactly ONCE across all windows: it@@ -283,20 +294,24 @@ export default function App() {{brokerMounted && <SubscriptionRealtimeTransportBroker />}<DesktopWallpaper />- <Sidebar- width={sidebar.size}- collapsed={navCollapsed}- onToggleCollapsed={toggleNav}- />+ {!deckOnStage && (+ <>+ <Sidebar+ width={sidebar.size}+ collapsed={navCollapsed}+ onToggleCollapsed={toggleNav}+ />- <PaneResizer- orientation="vertical"- onPointerDown={startSidebarResize}- onDoubleClick={sidebar.reset}- onNudge={sidebar.nudge}- active={sidebar.isResizing}- title="Drag to resize the sidebar — double-click to reset"- />+ <PaneResizer+ orientation="vertical"+ onPointerDown={startSidebarResize}+ onDoubleClick={sidebar.reset}+ onNudge={sidebar.nudge}+ active={sidebar.isResizing}+ title="Drag to resize the sidebar — double-click to reset"+ />+ </>+ )}<main className="relative z-10 flex min-w-0 flex-1 flex-col">{/* App-wide macOS permission alert — topmost so a missing grant isdiff --git a/jarvis/ui/web/frontend/src/components/deck/DeckActivityCards.tsx b/jarvis/ui/web/frontend/src/components/deck/DeckActivityCards.tsxnew file mode 100644index 0000000000..0a3a4c2227--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/deck/DeckActivityCards.tsx@@ -0,0 +1,512 @@+import { useEffect, useMemo, useRef } from "react";+import { useQuery } from "@tanstack/react-query";+import {+ Activity,+ FolderOpen,+ Gauge,+ MessagesSquare,+ Notebook,+ Terminal,+} from "lucide-react";+import { useEventStore } from "@/store/events";+import { useDeckStore } from "@/store/deck";+import { useRuns } from "@/hooks/useRuns";+import { useOutputsList, type OutputSummary } from "@/hooks/useOutputs";+import { fetchIdeState, fetchTerminalActivity, type IdeState, type ActivityResponse } from "@/lib/agenticIdeApi";+import { fetchWikiGraph, fetchWikiTree } from "@/lib/wikiApi";+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";+import { useT } from "@/i18n";++/**+ * The deck's activity cards — each one a small window onto a section, fed by+ * the data that section already has. Every figure is real; a card that has+ * 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}+ 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+// ----------------------------------------------------------------------++function outcomeTone(outcome: string): string {+ const o = outcome.toLowerCase();+ if (o.includes("error") || o.includes("fail")) return "bg-destructive";+ if (o.includes("ok") || o.includes("success") || o.includes("done")) return "bg-emerald-400";+ if (o.includes("running") || o.includes("open") || o.includes("live")) return "bg-primary animate-pulse";+ return "bg-muted-foreground";+}++function fmtClock(ms: number): string {+ if (!ms) return "";+ return new Date(ms).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });+}++export function RunsCard({ className }: { className?: string }) {+ const t = useT();+ const setActiveSection = useEventStore((s) => s.setActiveSection);+ const runs = useRuns();+ const items: RunListItem[] = (runs.data ?? []).slice(0, 6);+ const live = items.some((r) => r.ended_ms === null);++ return (+ <DeckCard+ icon={Gauge}+ title={t("deck.card_runs")}+ meta={runs.data ? runs.data.length : undefined}+ live={live}+ onOpen={() => setActiveSection("run_inspector")}+ openLabel={t("deck.open_section")}+ className={className}+ bodyClassName="overflow-y-auto"+ >+ {items.length === 0 ? (+ <p className="text-[11px] text-muted-foreground">+ {runs.isError ? t("deck.unavailable") : t("deck.runs_empty")}+ </p>+ ) : (+ <ul className="space-y-1">+ {items.map((r) => (+ <li key={r.session_id} className="flex items-center gap-2 text-[11px]">+ <span className={cn("h-1.5 w-1.5 shrink-0 rounded-full", outcomeTone(r.outcome))} aria-hidden />+ <span className="min-w-0 flex-1 truncate text-foreground">+ {r.preview || r.outcome || r.session_id.slice(0, 8)}+ </span>+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground">+ {r.turn_count > 0 ? `${r.turn_count}t · ` : ""}+ {fmtClock(r.started_ms)}+ </span>+ </li>+ ))}+ </ul>+ )}+ </DeckCard>+ );+}++// ----------------------------------------------------------------------+// Outputs — what the sub-agents delivered+// ----------------------------------------------------------------------++const OUTPUT_TONE: Record<string, string> = {+ running: "bg-primary animate-pulse",+ success: "bg-emerald-400",+ error: "bg-destructive",+ cancelled: "bg-muted-foreground",+ unknown: "bg-muted-foreground",+};++export function OutputsCard({ className }: { className?: string }) {+ const t = useT();+ const setActiveSection = useEventStore((s) => s.setActiveSection);+ const outputs = useOutputsList();+ const items: OutputSummary[] = (outputs.data ?? []).slice(0, 6);+ const running = items.filter((o) => o.status === "running").length;++ return (+ <DeckCard+ icon={FolderOpen}+ title={t("deck.card_outputs")}+ meta={running > 0 ? running : outputs.data ? outputs.data.length : undefined}+ live={running > 0}+ onOpen={() => setActiveSection("outputs")}+ openLabel={t("deck.open_section")}+ className={className}+ bodyClassName="overflow-y-auto"+ >+ {items.length === 0 ? (+ <p className="text-[11px] text-muted-foreground">+ {outputs.isError ? t("deck.unavailable") : t("deck.outputs_empty")}+ </p>+ ) : (+ <ul className="space-y-1">+ {items.map((o) => (+ <li key={o.slug} className="flex items-center gap-2 text-[11px]">+ <span+ className={cn("h-1.5 w-1.5 shrink-0 rounded-full", OUTPUT_TONE[o.status ?? "unknown"])}+ aria-hidden+ />+ <span className="min-w-0 flex-1 truncate text-foreground">+ {o.utterance || o.summary || o.slug}+ </span>+ {typeof o.artifact_count === "number" && o.artifact_count > 0 && (+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground">+ {o.artifact_count}+ </span>+ )}+ </li>+ ))}+ </ul>+ )}+ </DeckCard>+ );+}++// ----------------------------------------------------------------------+// IDE grid — the coding workspace, shrunk to its panes' states+// ----------------------------------------------------------------------++/**+ * A miniature of the Agentic IDE's terminal grid, WITHOUT mounting a single+ * terminal. The IDE's panes are live xterm instances bound to PTY streams,+ * and a second mounted copy steals every pane's output from the first+ * (MainView's sticky-mount comment explains the defect). So this is a status+ * mirror: one tile per pane, its agent, and what it is doing — read from the+ * same endpoints the IDE polls, and nothing more.+ */+const ACTIVITY_TONE: Record<string, string> = {+ starting: "bg-amber-400 animate-pulse",+ working: "bg-primary animate-pulse",+ waiting: "bg-sky-400",+ done: "bg-emerald-400",+ idle: "bg-muted-foreground",+ stopped: "bg-muted-foreground",+ error: "bg-destructive",+};++export function IdeGridCard({ className }: { className?: string }) {+ const t = useT();+ const setActiveSection = useEventStore((s) => s.setActiveSection);++ const state = useQuery<IdeState>({+ queryKey: ["deck", "ide-state"],+ queryFn: fetchIdeState,+ refetchInterval: 5_000,+ retry: false,+ });+ const activeId = state.data?.active_id ?? undefined;+ const activity = useQuery<ActivityResponse>({+ queryKey: ["deck", "ide-activity", activeId ?? "-"],+ queryFn: () => fetchTerminalActivity(activeId),+ enabled: Boolean(state.data?.active),+ refetchInterval: 3_000,+ retry: false,+ });++ const panes = state.data?.session?.terminals ?? [];+ const activityByKey = useMemo(() => {+ const m = new Map<string, string>();+ for (const row of activity.data?.terminals ?? []) {+ if (row.activity) m.set(row.key, row.activity);+ }+ return m;+ }, [activity.data]);+ const working = panes.filter((p) => activityByKey.get(p.key) === "working").length;+ const workspaces = state.data?.workspaces?.length ?? 0;+ const projectName = state.data?.session?.project?.name ?? "";++ return (+ <DeckCard+ icon={MessagesSquare}+ title={t("deck.card_ide")}+ meta={+ panes.length > 0+ ? `${working}/${panes.length}`+ : workspaces > 0+ ? workspaces+ : undefined+ }+ live={working > 0}+ onOpen={() => setActiveSection("agentic-ide")}+ openLabel={t("deck.open_section")}+ className={className}+ >+ {panes.length === 0 ? (+ <p className="text-[11px] text-muted-foreground">+ {state.isError ? t("deck.unavailable") : t("deck.ide_empty")}+ </p>+ ) : (+ <div className="flex h-full min-h-0 flex-col gap-1.5">+ {projectName && (+ <div className="truncate font-mono text-[10px] text-muted-foreground">{projectName}</div>+ )}+ <div+ className="grid min-h-0 flex-1 gap-1.5"+ style={{ gridTemplateColumns: `repeat(${Math.min(4, Math.max(1, Math.ceil(Math.sqrt(panes.length))))}, minmax(0, 1fr))` }}+ >+ {panes.slice(0, 12).map((p) => {+ const act = activityByKey.get(p.key) ?? (p.status === "live" ? "idle" : p.status);+ return (+ <div+ key={p.key}+ title={`${p.display_name || p.name} · ${act}`}+ className={cn(+ "flex min-h-[2.4rem] flex-col justify-between rounded-md border border-border/60 px-1.5 py-1",+ act === "working" && "border-primary/50",+ act === "error" && "border-destructive/60",+ )}+ >+ <div className="flex items-center gap-1">+ <span className={cn("h-1.5 w-1.5 shrink-0 rounded-full", ACTIVITY_TONE[act] ?? ACTIVITY_TONE.idle)} aria-hidden />+ <span className="truncate text-[10px] text-foreground">{p.display_name || p.name}</span>+ </div>+ <span className="truncate font-mono text-[9px] text-muted-foreground">{p.agent}</span>+ </div>+ );+ })}+ </div>+ </div>+ )}+ </DeckCard>+ );+}++// ----------------------------------------------------------------------+// Terminals — shell and CLI lines as they run+// ----------------------------------------------------------------------++const LINE_TONE: Record<string, string> = {+ cmd: "text-emerald-400",+ cli: "text-primary",+ out: "text-foreground/90",+ err: "text-destructive",+ note: "text-muted-foreground",+};++export function TerminalsCard({ className }: { className?: string }) {+ const t = useT();+ const setActiveSection = useEventStore((s) => s.setActiveSection);+ const lines = useDeckStore((s) => s.termLines);+ // The ToolExecutor's run_shell activity is the same class of thing — the+ // brain running a command — so it belongs on this card too, in front.+ const shell = useCommandActivityStore((s) => s.entries);+ const running = shell.filter((e) => e.status === "running").length;+ const endRef = useRef<HTMLDivElement | null>(null);++ useEffect(() => {+ endRef.current?.scrollIntoView({ block: "end" });+ }, [lines.length, shell.length]);++ const shellLines = shell.slice(-6).map((e) => ({+ id: `sh-${e.id}`,+ kind: e.status === "failed" || e.status === "blocked" ? "err" : "cmd",+ text: e.status === "running" ? `$ ${e.command}` : `$ ${e.command} · ${e.status}`,+ }));+ const shown = [...shellLines, ...lines.slice(-40).map((l) => ({ id: l.id, kind: l.kind, text: l.text }))];++ return (+ <DeckCard+ icon={Terminal}+ title={t("deck.card_terminals")}+ meta={running > 0 ? running : undefined}+ live={running > 0}+ onOpen={() => setActiveSection("clis")}+ openLabel={t("deck.open_section")}+ className={className}+ bodyClassName="overflow-y-auto"+ >+ {shown.length === 0 ? (+ <p className="text-[11px] text-muted-foreground">{t("deck.terminals_empty")}</p>+ ) : (+ <div className="font-mono text-[10.5px] leading-relaxed">+ {shown.map((l) => (+ <div key={l.id} className={cn("truncate", LINE_TONE[l.kind] ?? LINE_TONE.out)}>+ {l.text}+ </div>+ ))}+ <div ref={endRef} />+ </div>+ )}+ </DeckCard>+ );+}++// ----------------------------------------------------------------------+// Wiki — the memory, as a small constellation+// ----------------------------------------------------------------------++/**+ * A miniature of the wiki graph: real nodes and edges from `/api/wiki/graph`,+ * laid out on a deterministic spiral (no physics — the full graph view has+ * that; here it would cost a worker for a thumbnail). Pages that changed+ * this session glow. Capped so it stays a constellation, not a hairball.+ */+const WIKI_NODE_CAP = 90;++export function WikiCard({ className }: { className?: string }) {+ const t = useT();+ const setActiveSection = useEventStore((s) => s.setActiveSection);+ const changes = useDeckStore((s) => s.wikiChanges);+ const canvasRef = useRef<HTMLCanvasElement | null>(null);++ const tree = useQuery({ queryKey: ["deck", "wiki-tree"], queryFn: fetchWikiTree, refetchInterval: 60_000, retry: false });+ const graph = useQuery({ queryKey: ["deck", "wiki-graph"], queryFn: fetchWikiGraph, refetchInterval: 60_000, retry: false });++ const pages = tree.data?.stats?.total_pages;+ const links = tree.data?.stats?.total_links;+ const changedSlugs = useMemo(() => new Set(changes.map((c) => c.slug)), [changes]);++ useEffect(() => {+ const canvas = canvasRef.current;+ const nodes = graph.data?.nodes ?? [];+ const edges = graph.data?.edges ?? [];+ if (!canvas || nodes.length === 0) return;+ const rect = canvas.getBoundingClientRect();+ if (rect.width < 10 || rect.height < 10) return;+ const dpr = Math.min(2, window.devicePixelRatio || 1);+ canvas.width = Math.round(rect.width * dpr);+ canvas.height = Math.round(rect.height * dpr);+ const ctx = canvas.getContext("2d");+ if (!ctx) return;+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ ctx.clearRect(0, 0, rect.width, rect.height);++ const cs = getComputedStyle(document.documentElement);+ const primary = `hsl(${cs.getPropertyValue("--primary").trim()})`;+ const muted = `hsl(${cs.getPropertyValue("--muted-foreground").trim()})`;++ // Most-linked pages first, so the cap keeps the hubs.+ const degree = new Map<string, number>();+ for (const e of edges) {+ degree.set(e.source, (degree.get(e.source) ?? 0) + 1);+ degree.set(e.target, (degree.get(e.target) ?? 0) + 1);+ }+ const kept = [...nodes]+ .sort((a, b) => (degree.get(b.id) ?? 0) - (degree.get(a.id) ?? 0))+ .slice(0, WIKI_NODE_CAP);+ const cx = rect.width / 2, cy = rect.height / 2;+ const maxR = Math.min(cx, cy) - 6;+ const pos = new Map<string, [number, number]>();+ kept.forEach((n, i) => {+ // Fermat spiral: hubs at the centre, leaves at the rim, evenly spread.+ const r = maxR * Math.sqrt((i + 0.5) / kept.length);+ const a = i * 2.39996; // golden angle+ pos.set(n.id, [cx + r * Math.cos(a), cy + r * Math.sin(a)]);+ });++ ctx.lineWidth = 0.6;+ ctx.strokeStyle = muted;+ ctx.globalAlpha = 0.28;+ for (const e of edges) {+ const a = pos.get(e.source), b = pos.get(e.target);+ if (!a || !b) continue;+ ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.stroke();+ }+ ctx.globalAlpha = 1;+ for (const n of kept) {+ const p = pos.get(n.id);+ if (!p) continue;+ const hot = changedSlugs.has(n.id);+ const d = degree.get(n.id) ?? 0;+ ctx.beginPath();+ ctx.arc(p[0], p[1], hot ? 3 : Math.min(2.6, 1 + d * 0.15), 0, Math.PI * 2);+ ctx.fillStyle = hot ? primary : muted;+ ctx.globalAlpha = hot ? 1 : 0.7;+ ctx.fill();+ if (hot) {+ ctx.beginPath(); ctx.arc(p[0], p[1], 6, 0, Math.PI * 2);+ ctx.strokeStyle = primary; ctx.globalAlpha = 0.45; ctx.lineWidth = 1; ctx.stroke();+ }+ }+ ctx.globalAlpha = 1;+ }, [graph.data, changedSlugs]);++ return (+ <DeckCard+ icon={Notebook}+ title={t("deck.card_wiki")}+ meta={typeof pages === "number" ? `${pages}${typeof links === "number" ? ` · ${links}` : ""}` : undefined}+ live={changes.length > 0}+ onOpen={() => setActiveSection("memory")}+ openLabel={t("deck.open_section")}+ className={className}+ bodyClassName="p-0"+ >+ {graph.isError || (graph.data && graph.data.ok === false) ? (+ <p className="px-2.5 py-2 text-[11px] text-muted-foreground">{t("deck.unavailable")}</p>+ ) : (+ <div className="relative h-full min-h-[5rem] w-full">+ <canvas ref={canvasRef} className="absolute inset-0 h-full w-full" aria-hidden />+ {changes.length > 0 && (+ <div className="absolute bottom-1 left-2 right-2 truncate font-mono text-[9px] text-primary">+ {changes.slice(0, 3).map((c) => c.slug).join(" · ")}+ </div>+ )}+ </div>+ )}+ </DeckCard>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/deck/DeckCard.tsx b/jarvis/ui/web/frontend/src/components/deck/DeckCard.tsxnew file mode 100644index 0000000000..2daf33dd25--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/deck/DeckCard.tsx@@ -0,0 +1,93 @@+import type { ReactNode } from "react";+import type { LucideIcon } from "lucide-react";+import { ArrowUpRight } from "lucide-react";+import { cn } from "@/lib/utils";++/**+ * One panel on the deck.+ *+ * Deliberately NOT a filled box: the app's convention (index.css, "Frontend+ * theming") is that the wallpaper shines through untinted and the stage's+ * text halo keeps ink readable on it. So a card is a hairline, an eyebrow+ * that names it in plain words, and its content — nothing that could hide+ * the artwork behind a slab.+ *+ * `onOpen` makes the whole eyebrow a jump into the section the card is a+ * window onto; the arrow says so.+ */+export function DeckCard({+ icon: Icon,+ title,+ meta,+ onOpen,+ openLabel,+ live,+ className,+ bodyClassName,+ children,+}: {+ icon: LucideIcon;+ title: string;+ /** Small trailing figure or word next to the title (a count, a state). */+ meta?: ReactNode;+ onOpen?: () => void;+ openLabel?: string;+ /** Something is happening in here right now — the eyebrow lights up. */+ live?: boolean;+ className?: string;+ bodyClassName?: string;+ children: ReactNode;+}) {+ const head = (+ <>+ <Icon className={cn("h-3 w-3 shrink-0", live ? "text-primary" : "text-muted-foreground")} />+ <span+ className={cn(+ "truncate font-mono text-[10px] uppercase tracking-[0.2em]",+ live ? "text-primary" : "text-muted-foreground",+ )}+ >+ {title}+ </span>+ {meta !== undefined && (+ <span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground">+ {meta}+ </span>+ )}+ {onOpen && (+ <ArrowUpRight+ className={cn(+ "h-3 w-3 shrink-0 opacity-0 transition-opacity group-hover/card:opacity-100",+ meta === undefined && "ml-auto",+ )}+ />+ )}+ </>+ );++ return (+ <section+ className={cn(+ "group/card flex min-h-0 flex-col rounded-lg border border-border/70",+ live && "border-primary/40",+ className,+ )}+ >+ {onOpen ? (+ <button+ type="button"+ onClick={onOpen}+ title={openLabel}+ className="flex w-full items-center gap-2 border-b border-border/60 px-2.5 py-1.5 text-left transition-colors hover:bg-primary/5"+ >+ {head}+ </button>+ ) : (+ <div className="flex items-center gap-2 border-b border-border/60 px-2.5 py-1.5">{head}</div>+ )}+ <div className={cn("min-h-0 flex-1 overflow-hidden px-2.5 py-2", bodyClassName)}>+ {children}+ </div>+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/deck/DeckDock.tsx b/jarvis/ui/web/frontend/src/components/deck/DeckDock.tsxnew file mode 100644index 0000000000..10906b27f6--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/deck/DeckDock.tsx@@ -0,0 +1,177 @@+import { useCallback, useMemo, useRef, useState } from "react";+import { useEventStore, type SectionId } from "@/store/events";+import { NAV_GROUPS, resolveNavLabel } from "@/components/layout/navGroups";+import { useSectionHealth } from "@/hooks/useProviders";+import { usePluginAttention } from "@/hooks/usePluginAttention";+import { layoutDock } from "@/lib/dockMagnify";+import { cn } from "@/lib/utils";+import { useT } from "@/i18n";++/**+ * The deck's section dock — every section of the app as one icon, on the+ * left edge, with the magnification desktop docks made familiar.+ *+ * It replaces the sidebar ONLY while the deck is on screen (App.tsx): the+ * sections appear once, not twice, and the rigid list becomes the smooth+ * one. Clicking an icon jumps to that section, where the ordinary sidebar is+ * waiting; the deck's own dock is not a second navigation, it IS the+ * navigation for this one surface.+ *+ * The list is the sidebar's own `NAV_GROUPS` — one source, so a section added+ * there appears here without anyone remembering to add it twice (AP-4). The+ * attention signals are the sidebar's too: a provider error lights API Keys,+ * a plugin that needs a reconnect lights Plugins.+ *+ * Magnification is pure geometry from `lib/dockMagnify.ts`; this component+ * only measures the pointer and applies the resulting transforms. Motion is+ * suppressed for users who asked for less of it — the dock then simply+ * highlights the hovered icon.+ */+const BASE = 30; // px — icon box at rest+const GAP = 8; // px — between icon boxes at rest+const PAD = 12; // px — dock padding top/bottom++export function DeckDock({ className }: { className?: string }) {+ const t = useT();+ const activeSection = useEventStore((s) => s.activeSection);+ const setActiveSection = useEventStore((s) => s.setActiveSection);+ const conversations = useEventStore((s) => s.conversations);+ const { health } = useSectionHealth();+ const pluginAttention = usePluginAttention();++ const items = useMemo(() => NAV_GROUPS.flat(), []);+ const groupBreaks = useMemo(() => {+ // Index of the first item of every group after the first — a hairline is+ // drawn above these so the dock keeps the sidebar's grouping.+ const breaks = new Set<number>();+ let n = 0;+ for (let g = 0; g < NAV_GROUPS.length; g++) {+ if (g > 0) breaks.add(n);+ n += NAV_GROUPS[g].length;+ }+ return breaks;+ }, []);++ const apikeysError = useMemo(+ () => Object.values(health).some((h) => h?.status === "error"),+ [health],+ );++ const reduced = useMemo(+ () => window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false,+ [],+ );++ const railRef = useRef<HTMLDivElement | null>(null);+ const [pointerY, setPointerY] = useState<number | null>(null);++ const onMove = useCallback((e: React.PointerEvent<HTMLDivElement>) => {+ const rect = railRef.current?.getBoundingClientRect();+ if (!rect) return;+ setPointerY(e.clientY - rect.top - PAD);+ }, []);+ const onLeave = useCallback(() => setPointerY(null), []);++ const layout = useMemo(+ () => layoutDock(items.length, BASE, GAP, reduced ? null : pointerY),+ [items.length, pointerY, reduced],+ );++ return (+ <nav+ aria-label={t("deck.sections")}+ className={cn("relative flex h-full w-16 shrink-0 flex-col items-center", className)}+ >+ <div+ ref={railRef}+ onPointerMove={onMove}+ onPointerLeave={onLeave}+ className="relative w-full flex-1 overflow-visible"+ style={{ paddingTop: PAD, paddingBottom: PAD }}+ >+ {/* Height follows the magnified extent so the dock never clips. */}+ <div className="relative w-full" style={{ height: layout.extent }}>+ {items.map((item, i) => {+ const li = layout.items[i];+ const isActive =+ activeSection === item.id || item.matchIds?.includes(activeSection);+ const count = item.id === "chats" ? conversations.length : 0;+ const attention =+ (item.id === "apikeys" && apikeysError) ||+ (item.id === "skills" && pluginAttention.count > 0);+ const label = resolveNavLabel(t, item);+ const hot = li.scale > 1.35;++ return (+ <div key={item.id} className="contents">+ {groupBreaks.has(i) && (+ <span+ aria-hidden+ className="absolute left-4 right-4 h-px bg-border"+ style={{ top: li.center - li.size / 2 - GAP / 2 - 0.5 }}+ />+ )}+ <button+ type="button"+ onClick={() => setActiveSection(item.id)}+ aria-label={label}+ aria-current={isActive ? "page" : undefined}+ title={label}+ className={cn(+ "absolute left-1/2 flex items-center justify-center rounded-xl border transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",+ isActive+ ? "border-primary/50 bg-primary/15 text-primary"+ : "border-transparent text-muted-foreground hover:text-foreground",+ hot && !isActive && "border-border/60 bg-card/30 text-foreground",+ )}+ style={{+ top: li.center - li.size / 2,+ width: li.size,+ height: li.size,+ transform: "translateX(-50%)",+ // The icon scales with its box; the box is what pushes+ // neighbours, so nothing overlaps.+ transition: reduced ? undefined : "top 90ms linear, width 90ms linear, height 90ms linear",+ }}+ >+ <item.icon+ className="shrink-0"+ style={{ width: Math.round(16 * li.scale), height: Math.round(16 * li.scale) }}+ />++ {/* Live pip: something is going on in this section. */}+ {(count > 0 || attention) && (+ <span+ aria-hidden+ className={cn(+ "absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full ring-2 ring-background",+ attention ? "bg-destructive" : "bg-primary",+ )}+ />+ )}++ {/* Label flies out while magnified — the dock has no room+ for text otherwise, and a hovered icon should name+ itself without a tooltip delay. */}+ {hot && (+ <span+ className="pointer-events-none absolute left-full ml-3 whitespace-nowrap rounded-md border border-border bg-background/90 px-2 py-0.5 text-xs text-foreground shadow-sm"+ >+ {label}+ {count > 0 && (+ <span className="ml-1.5 font-mono text-[10px] text-primary">{count}</span>+ )}+ </span>+ )}+ </button>+ </div>+ );+ })}+ </div>+ </div>+ </nav>+ );+}++export type { SectionId };diff --git a/jarvis/ui/web/frontend/src/components/deck/DeckOrb.tsx b/jarvis/ui/web/frontend/src/components/deck/DeckOrb.tsxnew file mode 100644index 0000000000..42d3d48a11--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/deck/DeckOrb.tsx@@ -0,0 +1,143 @@+import { useEffect, useMemo, useRef, useState } from "react";+import { useEventStore } from "@/store/events";+import { VoiceOrb } from "@/components/agentic/VoiceOrb";+import { MascotGigi } from "@/components/MascotGigi";+import type { ThinkingStep } from "@/lib/thinkingSteps";+import { cn } from "@/lib/utils";++/**+ * The centre of the deck: the voice orb with the mascot inside it, ringed by+ * one arc per running step.+ *+ * The orb is the app's own (`agentic/VoiceOrb`), driven by the real voice+ * state — it breathes, listens and speaks the way it does everywhere else in+ * the product, so the deck's centre is recognisably the assistant and not a+ * new mascot. The mascot sits on top of it; the arcs are the deck's addition:+ * every active reasoning step (a tool, a worker, a look at the screen) is one+ * bright arc, so parallel work is visible as parallel arcs.+ *+ * Motion only while something runs. An idle orb still breathes (that is the+ * VoiceOrb's own idle), but the sweep and the arcs stop.+ */+export function DeckOrb({+ steps,+ busy,+ size = 260,+ className,+}: {+ steps: ThinkingStep[];+ busy: boolean;+ size?: number;+ className?: string;+}) {+ const voiceState = useEventStore((s) => s.voiceState);+ const reduced = useMemo(+ () => window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false,+ [],+ );++ // A slow sweep that only turns while something runs.+ const [sweep, setSweep] = useState(0);+ const raf = useRef<number | null>(null);+ useEffect(() => {+ if (!busy || reduced) return;+ let start: number | null = null;+ const tick = (ts: number) => {+ if (start === null) start = ts;+ setSweep(((ts - start) / 30) % 360);+ raf.current = requestAnimationFrame(tick);+ };+ raf.current = requestAnimationFrame(tick);+ return () => {+ if (raf.current !== null) cancelAnimationFrame(raf.current);+ };+ }, [busy, reduced]);++ const R = size / 2;+ const orbSize = Math.round(size * 0.62);+ const point = (deg: number, r: number): [number, number] => {+ const rad = ((deg - 90) * Math.PI) / 180;+ return [R + r * Math.cos(rad), R + r * Math.sin(rad)];+ };++ const arcs = steps.slice(0, 8).map((step, i, all) => {+ const span = 320 / Math.max(1, all.length);+ const a0 = -160 + i * span + 3;+ const a1 = a0 + span - 6;+ const [x0, y0] = point(a0, R * 0.86);+ const [x1, y1] = point(a1, R * 0.86);+ return {+ id: step.id,+ d: `M ${x0} ${y0} A ${R * 0.86} ${R * 0.86} 0 ${a1 - a0 > 180 ? 1 : 0} 1 ${x1} ${y1}`,+ note: step.kind === "note",+ };+ });++ const [sx, sy] = point(sweep, R * 0.95);+ const [ex, ey] = point(sweep + 36, R * 0.95);++ return (+ <div className={cn("relative shrink-0", className)} style={{ width: size, height: size }}>+ <svg viewBox={`0 0 ${size} ${size}`} className="absolute inset-0 h-full w-full" aria-hidden>+ {/* Scale ring: 60 ticks, brighter every 15° — a dial, not a decoration:+ it is what the arcs and the sweep are read against. */}+ {Array.from({ length: 60 }, (_, i) => {+ const deg = i * 6;+ const [ax, ay] = point(deg, R * 0.72);+ const [bx, by] = point(deg, R * 0.76);+ return (+ <line+ key={deg}+ x1={ax}+ y1={ay}+ x2={bx}+ y2={by}+ stroke="hsl(var(--primary))"+ strokeWidth={1}+ opacity={i % 5 === 0 ? 0.45 : 0.14}+ />+ );+ })}+ <circle+ cx={R}+ cy={R}+ r={R * 0.86}+ fill="none"+ stroke="hsl(var(--border))"+ strokeWidth={1}+ opacity={0.6}+ />+ {arcs.map((a) => (+ <path+ key={a.id}+ d={a.d}+ fill="none"+ stroke={a.note ? "hsl(var(--muted-foreground))" : "hsl(var(--primary))"}+ strokeWidth={3}+ strokeLinecap="round"+ opacity={0.9}+ />+ ))}+ {busy && !reduced && (+ <path+ d={`M ${sx} ${sy} A ${R * 0.95} ${R * 0.95} 0 0 1 ${ex} ${ey}`}+ fill="none"+ stroke="hsl(var(--primary))"+ strokeWidth={1.5}+ strokeLinecap="round"+ opacity={0.55}+ />+ )}+ </svg>++ <div className="absolute inset-0 grid place-items-center">+ <div className="relative" style={{ width: orbSize, height: orbSize }}>+ <VoiceOrb state={voiceState} size={orbSize} className="absolute inset-0" />+ <div className="absolute inset-0 grid place-items-center">+ <MascotGigi size={Math.round(orbSize * 0.42)} reactToVoice enableComments={false} />+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/deck/DeckSignalCards.tsx b/jarvis/ui/web/frontend/src/components/deck/DeckSignalCards.tsxnew file mode 100644index 0000000000..15f4734469--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/deck/DeckSignalCards.tsx@@ -0,0 +1,320 @@+import { useEffect, useMemo, useState } from "react";+import { Camera, Coins, MousePointer2 } from "lucide-react";+import { useEventStore } from "@/store/events";+import { useDeckStore } from "@/store/deck";+import { countWords } from "@/lib/deckState";+import { DeckCard } from "@/components/deck/DeckCard";+import { cn } from "@/lib/utils";+import { useT } from "@/i18n";++/**+ * The deck's signal cards — the pictures 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.+ */++// ----------------------------------------------------------------------+// Computer Use — what the assistant is doing on the screen+// ----------------------------------------------------------------------++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]);++ 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}+ 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>++ {/* Phase strip: observe → plan → act → verify. */}+ <div className="flex items-center gap-1 border-t border-border/60 px-2 py-1">+ {CU_PHASES.map((ph) => (+ <span+ key={ph}+ className={cn(+ "flex-1 truncate text-center font-mono text-[8px] uppercase tracking-wider",+ cu.active && cu.phase === ph+ ? "text-primary"+ : "text-muted-foreground/70",+ )}+ >+ {ph}+ </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>+ );+}++// ----------------------------------------------------------------------+// 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 }) {+ const t = useT();+ const capture = useDeckStore((s) => s.capture);+ const [gone, setGone] = useState(false);+ const src = capture ? `/api/deck/frame?s=${capture.seq}` : null;++ 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);+ return () => window.clearInterval(id);+ }, [capture]);++ const fresh = capture && !gone;++ return (+ <DeckCard+ icon={Camera}+ title={t("deck.card_shot")}+ meta={fresh && capture ? `${capture.width}×${capture.height}` : undefined}+ live={Boolean(fresh)}+ className={className}+ bodyClassName="p-0"+ >+ <div className="relative h-full min-h-[5rem] overflow-hidden bg-black/20">+ {fresh && src ? (+ <>+ <img+ key={src}+ src={src}+ alt=""+ onError={() => setGone(true)}+ 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))}+ </span>+ )}+ </div>+ </>+ ) : (+ <div className="flex h-full items-center justify-center px-3 text-center text-[11px] text-muted-foreground">+ {t("deck.shot_empty")}+ </div>+ )}+ </div>+ </DeckCard>+ );+}++// ----------------------------------------------------------------------+// API stats — what this session cost+// ----------------------------------------------------------------------++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`;+ 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)}`;+}++export function ApiStatsCard({ className }: { className?: string }) {+ const t = useT();+ const usage = useDeckStore((s) => s.usage);+ const setActiveSection = useEventStore((s) => s.setActiveSection);+ const models = useMemo(+ () => Object.entries(usage.byModel).sort((a, b) => b[1].costUsd - a[1].costUsd || b[1].turns - a[1].turns).slice(0, 4),+ [usage.byModel],+ );++ return (+ <DeckCard+ icon={Coins}+ title={t("deck.card_api")}+ meta={usage.turns > 0 ? `${usage.turns} ${t("deck.turns")}` : undefined}+ onOpen={() => setActiveSection("apikeys")}+ openLabel={t("deck.open_section")}+ className={className}+ >+ {usage.turns === 0 ? (+ <p className="text-[11px] text-muted-foreground">{t("deck.api_empty")}</p>+ ) : (+ <div className="flex h-full flex-col gap-2">+ <div className="grid grid-cols-3 gap-2">+ <Stat label={t("deck.api_in")} value={fmtTokens(usage.tokensIn)} />+ <Stat label={t("deck.api_out")} value={fmtTokens(usage.tokensOut)} />+ <Stat label={t("deck.api_cost")} value={fmtUsd(usage.costUsd)} hot />+ </div>+ {models.length > 0 && (+ <ul className="space-y-0.5 border-t border-border/60 pt-1.5">+ {models.map(([name, m]) => (+ <li key={name} className="flex items-center gap-2 font-mono text-[10px]">+ <span className="min-w-0 flex-1 truncate text-foreground">{name}</span>+ <span className="shrink-0 tabular-nums text-muted-foreground">+ {m.turns}× · {fmtTokens(m.tokensIn + m.tokensOut)}+ </span>+ <span className="shrink-0 tabular-nums text-primary">{fmtUsd(m.costUsd)}</span>+ </li>+ ))}+ </ul>+ )}+ {usage.lastCacheHit && (+ <span className="font-mono text-[9px] uppercase tracking-wider text-emerald-400">+ {t("deck.api_cache_hit")}+ </span>+ )}+ </div>+ )}+ </DeckCard>+ );+}++function Stat({ label, value, hot }: { label: string; value: string; hot?: boolean }) {+ return (+ <div className="flex flex-col">+ <span className="font-mono text-[9px] uppercase tracking-[0.14em] text-muted-foreground">{label}</span>+ <span className={cn("font-mono text-sm tabular-nums", hot ? "text-primary" : "text-foreground")}>{value}</span>+ </div>+ );+}++// ----------------------------------------------------------------------+// Live counter — words, as they are spoken+// ----------------------------------------------------------------------++/**+ * The big number is the live transcript's word count and moves with every+ * partial the recogniser sends — that is the "in the millisecond" the+ * maintainer asked for. Underneath: the session total (final transcripts)+ * and today's dictation words from the dictation statistics.+ */+export function LiveCounter({ className }: { className?: string }) {+ const t = useT();+ const transcription = useEventStore((s) => s.transcription);+ const transcriptionFinal = useEventStore((s) => s.transcriptionFinal);+ const voiceState = useEventStore((s) => s.voiceState);+ const wordsSession = useDeckStore((s) => s.wordsSession);+ const utterances = useDeckStore((s) => s.utterances);+ const [today, setToday] = useState<number | null>(null);++ useEffect(() => {+ let alive = true;+ const load = async () => {+ try {+ const res = await fetch("/api/dictation/stats");+ if (!res.ok) return;+ const data = (await res.json()) as { today?: { words?: number } };+ if (alive && typeof data.today?.words === "number") setToday(data.today.words);+ } catch {+ /* the strip just stays away */+ }+ };+ void load();+ const id = window.setInterval(load, 60_000);+ return () => {+ alive = false;+ window.clearInterval(id);+ };+ }, [utterances]);++ const live = !transcriptionFinal && voiceState === "listening" ? countWords(transcription) : 0;+ const listening = voiceState === "listening";++ return (+ <div className={cn("flex items-baseline gap-3", className)}>+ <span+ className={cn(+ "font-mono text-2xl font-semibold tabular-nums leading-none transition-colors",+ listening ? "text-primary" : "text-foreground",+ )}+ aria-live="polite"+ >+ {listening ? live : wordsSession}+ </span>+ <span className="font-mono text-[9px] uppercase tracking-[0.16em] text-muted-foreground">+ {listening ? t("deck.words_live") : t("deck.words_session")}+ </span>+ {today !== null && (+ <span className="font-mono text-[10px] tabular-nums text-muted-foreground">+ · {t("deck.words_today").replace("{0}", String(today))}+ </span>+ )}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.tsindex 86e3d2006f..10291eb0a5 100644--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts@@ -21,6 +21,7 @@ import {useCommandActivityStore,COMMAND_ACTIVITY_EVENTS,} from "@/store/commandActivity";+import { useDeckStore } from "@/store/deck";import { WSAudioLevel, WSEventEnvelope, WSWelcome } from "@/schema/ws";import { useI18nStore, hydrateUiLanguage, hydrateReplyLanguage, translate } from "@/i18n";import { hydrateUiTheme } from "@/hooks/useTheme";@@ -179,6 +180,13 @@ export function useWebSocket(): void {);}+ // Mission deck: cost, computer-use, capture, terminals, wiki, words.+ // The reducer hands back the same object for every event it does not+ // read, so this is one cheap call, not a re-render per event.+ useDeckStore+ .getState()+ .ingest(env.event_name, env.payload, Math.floor(env.timestamp_ns / 1_000_000));+// Jarvis-Agents dashboard: build the live tree from the Phase-5.5 events.if (SUB_AGENT_EVENT_NAMES.has(env.event_name)) {useSubAgentStorediff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex e7a09ceb8d..3ef4325b50 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -4345,6 +4345,36 @@"stat_model": "Modell","stat_running": "Läuft","switch_to_classic": "Klassischer Chat",- "switch_to_deck": "Deck"+ "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",+ "outputs_empty": "Noch keine Ergebnisse.",+ "card_ide": "Coding-Workspace",+ "ide_empty": "Kein Workspace offen.",+ "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",+ "card_api": "API diese Sitzung",+ "api_empty": "Noch keine Hirn-Antworten.",+ "api_in": "Rein",+ "api_out": "Raus",+ "api_cost": "Kosten",+ "turns": "Antworten",+ "api_cache_hit": "Cache-Treffer",+ "words_live": "Wörter · live",+ "words_session": "Wörter · Sitzung",+ "words_today": "{0} heute",+ "mood_speaking": "spricht"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 229b7fcf42..efd01b0ad0 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -4345,6 +4345,36 @@"stat_model": "Model","stat_running": "Running","switch_to_classic": "Classic chat",- "switch_to_deck": "Deck"+ "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",+ "outputs_empty": "No outputs yet.",+ "card_ide": "Coding workspace",+ "ide_empty": "No workspace open.",+ "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",+ "card_api": "API this session",+ "api_empty": "No brain turns yet.",+ "api_in": "In",+ "api_out": "Out",+ "api_cost": "Cost",+ "turns": "turns",+ "api_cache_hit": "cache hit",+ "words_live": "words · live",+ "words_session": "words · session",+ "words_today": "{0} today",+ "mood_speaking": "speaking"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 4c81fdafc3..bb0e1bf057 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -4345,6 +4345,36 @@"stat_model": "Modelo","stat_running": "Activos","switch_to_classic": "Chat clásico",- "switch_to_deck": "Panel"+ "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",+ "outputs_empty": "Aún no hay resultados.",+ "card_ide": "Espacio de código",+ "ide_empty": "Ningún espacio abierto.",+ "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",+ "card_api": "API en esta sesión",+ "api_empty": "Aún sin respuestas del cerebro.",+ "api_in": "Entrada",+ "api_out": "Salida",+ "api_cost": "Coste",+ "turns": "respuestas",+ "api_cache_hit": "acierto de caché",+ "words_live": "palabras · en vivo",+ "words_session": "palabras · sesión",+ "words_today": "{0} hoy",+ "mood_speaking": "hablando"}}diff --git a/jarvis/ui/web/frontend/src/lib/deckState.test.ts b/jarvis/ui/web/frontend/src/lib/deckState.test.tsnew file mode 100644index 0000000000..df7b88a3dc--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/deckState.test.ts@@ -0,0 +1,176 @@+import { describe, expect, it } from "vitest";+import {+ MAX_TERM_LINES,+ countWords,+ emptyDeckState,+ reduceDeck,+ splitTerminalData,+ type DeckState,+} from "@/lib/deckState";++/**+ * The deck shows numbers a person will act on, so each one has to be traced+ * to the payload it came from and nothing else. These tests pin that: cost+ * and tokens add up exactly, Computer-Use follows its events, a capture bumps+ * a sequence, terminal noise is stripped, and unrelated events change nothing.+ */++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));+ }+ return s;+}++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, "SomethingNew", { x: 1 }, 1)).toBe(start);+ });++ it("adds brain cost and tokens per turn and per model", () => {+ const s = fold([+ ["BrainTurnCompleted", { tokens_in: 100, tokens_out: 20, cost_usd: 0.01, provider: "openrouter", model: "sonnet" }],+ ["BrainTurnCompleted", { tokens_in: 50, tokens_out: 10, cost_usd: 0.005, provider: "openrouter", model: "sonnet" }],+ ["BrainTurnCompleted", { tokens_in: 10, tokens_out: 5, cost_usd: 0.001, provider: "anthropic", model: "opus" }],+ ]);+ expect(s.usage.turns).toBe(3);+ expect(s.usage.tokensIn).toBe(160);+ expect(s.usage.tokensOut).toBe(35);+ expect(s.usage.costUsd).toBeCloseTo(0.016, 6);+ expect(s.usage.lastModel).toBe("opus");+ expect(s.usage.byModel.sonnet).toEqual({ turns: 2, tokensIn: 150, tokensOut: 30, costUsd: 0.015 });+ expect(s.usage.byModel.opus.turns).toBe(1);+ });++ it("tolerates a turn without usage figures", () => {+ const s = fold([["BrainTurnCompleted", { provider: "ollama" }]]);+ expect(s.usage.turns).toBe(1);+ expect(s.usage.tokensIn).toBe(0);+ expect(s.usage.costUsd).toBe(0);+ expect(s.usage.byModel.ollama.turns).toBe(1);+ });++ it("follows a computer-use mission from start to end", () => {+ let s = fold([["CUControlStarted", { mission_id: "m1" }]]);+ expect(s.cu.active).toBe(true);+ expect(s.cu.phase).toBe("observe");++ s = fold(+ [+ ["CUStepProfiled", { phase: "plan", step_idx: 3 }],+ ["ActionPlanned", { action_kind: "click", target_hint: "{role:Button,name:Save}" }],+ ["ObservationCaptured", { screenshot_hash: "ab".repeat(32), window_title: "Docker Desktop" }],+ ["ActionExecuted", { success: true }],+ ],+ s,+ );+ expect(s.cu.stepIdx).toBe(3);+ expect(s.cu.phase).toBe("act");+ expect(s.cu.lastActionKind).toBe("click");+ expect(s.cu.lastTargetHint).toBe("{role:Button,name:Save}");+ expect(s.cu.lastFrameSha).toBe("ab".repeat(32));+ expect(s.cu.windowTitle).toBe("Docker Desktop");+ expect(s.cu.frames).toBe(1);+ expect(s.cu.lastActionOk).toBe(true);++ s = fold([["CUControlEnded", { reason: "finished" }]], s);+ expect(s.cu.active).toBe(false);+ expect(s.cu.phase).toBe("idle");+ expect(s.cu.endedReason).toBe("finished");+ // The last frame stays: the card keeps showing what was done.+ expect(s.cu.lastFrameSha).toBe("ab".repeat(32));+ });++ it("ignores ordinary tool results while no computer-use mission runs", () => {+ const start = emptyDeckState();+ // ActionExecuted also fires for plain tool calls — those belong to the+ // thinking trace, not to the CU card.+ expect(reduceDeck(start, "ActionExecuted", { success: false }, 1)).toBe(start);+ });++ it("bumps the capture sequence on every completed screen capture", () => {+ let s = fold([["ScreenCaptureCompleted", { target_kind: "monitor", target_label: "Monitor 1", width: 1920, height: 1080, redaction_count: 2 }]]);+ expect(s.capture?.seq).toBe(1);+ expect(s.capture?.targetLabel).toBe("Monitor 1");+ expect(s.capture?.redactions).toBe(2);+ s = fold([["ScreenCaptureCompleted", { width: 800, height: 600 }]], s);+ expect(s.capture?.seq).toBe(2);+ expect(s.capture?.width).toBe(800);+ });++ it("collects terminal commands, output lines and CLI calls in order", () => {+ const s = fold([+ ["TerminalCommandExecuted", { terminal_id: "t1", command: "pytest -q" }],+ ["TerminalOutput", { terminal_id: "t1", data: "\x1b[32m3 passed\x1b[0m\r\n" }],+ ["CliInvoked", { cli_name: "gh", command_preview: "pr list" }],+ ["CliInvocationFinished", { cli_name: "gh", exit_code: 0, duration_ms: 420 }],+ ["CliInvocationFinished", { cli_name: "gh", exit_code: 1, duration_ms: 12 }],+ ]);+ expect(s.termLines.map((l) => [l.kind, l.text])).toEqual([+ ["cmd", "pytest -q"],+ ["out", "3 passed"],+ ["cli", "gh pr list"],+ ["note", "gh · exit 0 · 420 ms"],+ ["err", "gh · exit 1 · 12 ms"],+ ]);+ });++ it("caps the terminal buffer", () => {+ let s = emptyDeckState();+ for (let i = 0; i < MAX_TERM_LINES + 25; i++) {+ s = reduceDeck(s, "TerminalOutput", { terminal_id: "t", data: `line ${i}\n` }, i);+ }+ expect(s.termLines).toHaveLength(MAX_TERM_LINES);+ expect(s.termLines[0].text).toBe("line 25");+ });++ it("keeps the newest wiki change per page at the front", () => {+ const s = fold([+ ["WikiPageChanged", { slug: "a", kind: "created" }],+ ["WikiPageChanged", { slug: "b", kind: "created" }],+ ["WikiPageChanged", { slug: "a", kind: "updated" }],+ ]);+ expect(s.wikiChanges.map((c) => `${c.slug}:${c.kind}`)).toEqual(["a:updated", "b:created"]);+ });++ it("counts spoken words from final transcripts only", () => {+ const s = fold([+ ["TranscriptPartial", { transcript: { text: "this is not" } }],+ ["TranscriptFinal", { transcript: { text: " Sortier mir die Rechnungen " } }],+ ["TranscriptFinal", { transcript: { text: "" } }],+ ["TranscriptFinal", { transcript: { text: "Danke" } }],+ ]);+ expect(s.wordsSession).toBe(5);+ expect(s.wordsLast).toBe(1);+ expect(s.utterances).toBe(2);+ });+});++describe("countWords", () => {+ it("counts runs of non-space characters", () => {+ expect(countWords("")).toBe(0);+ expect(countWords(" ")).toBe(0);+ expect(countWords("ein")).toBe(1);+ expect(countWords("ein zwei\tdrei\nvier")).toBe(4);+ });+});++describe("splitTerminalData", () => {+ it("strips ANSI colour and cursor sequences", () => {+ expect(splitTerminalData("\x1b[1;32mok\x1b[0m\n")).toEqual(["ok"]);+ expect(splitTerminalData("\x1b[2K\x1b[1Gprogress 50%\r")).toEqual(["progress 50%"]);+ });++ it("strips OSC window-title sequences terminated by BEL or ESC backslash", () => {+ expect(splitTerminalData("\x1b]0;my title\x07real\n")).toEqual(["real"]);+ expect(splitTerminalData("\x1b]0;my title\x1b\\real\n")).toEqual(["real"]);+ });++ it("keeps CR-only redraws as their own lines and drops empties", () => {+ expect(splitTerminalData("10%\r20%\r30%\r\n\n")).toEqual(["10%", "20%", "30%"]);+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/deckState.ts b/jarvis/ui/web/frontend/src/lib/deckState.tsnew file mode 100644index 0000000000..48a6448882--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/deckState.ts@@ -0,0 +1,418 @@+/**+ * Mission-deck state model — the pure event→state mapping behind the deck's+ * cards (MissionDeckView.tsx).+ *+ * 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.+ *+ * Every figure here is REAL and sourced from a payload the backend already+ * publishes. Nothing is estimated: `BrainTurnCompleted` carries token counts+ * and cost, `CUStepProfiled` the phase, `ObservationCaptured` the frame hash,+ * `TranscriptFinal` the words. A card whose number cannot be sourced this way+ * does not get one.+ *+ * Pure module on purpose: no React, no zustand, no timers — covered by+ * deckState.test.ts (same pattern as thinkingSteps.ts / commandActivity.ts).+ */++export interface BrainUsageByModel {+ turns: number;+ tokensIn: number;+ tokensOut: number;+ costUsd: number;+}++export interface BrainUsage {+ turns: number;+ tokensIn: number;+ tokensOut: number;+ costUsd: number;+ lastProvider: string;+ lastModel: string;+ lastTurnTs: number | null;+ /** True when the last turn was answered from a prompt cache. */+ lastCacheHit: boolean;+ byModel: Record<string, BrainUsageByModel>;+}++export type CuPhase = "observe" | "uia" | "plan" | "think" | "act" | "verify" | "idle";++export interface CuState {+ active: boolean;+ missionId: string;+ phase: CuPhase;+ stepIdx: number;+ /** "click" | "type" | "hotkey" | "wait" | "verify" — raw from ActionPlanned. */+ lastActionKind: string;+ /** Raw target description ("{role:Button,name:Save}"), never translated. */+ lastTargetHint: string;+ lastActionOk: boolean | null;+ /** sha256 of the newest observation frame — served by /api/deck/cu-frame. */+ lastFrameSha: string | null;+ windowTitle: string;+ frames: number;+ startedTs: number | null;+ endedReason: string;+}++export interface CaptureState {+ /** Bumps on every ScreenCaptureCompleted — the card refetches on change. */+ seq: number;+ ts: number;+ targetKind: string;+ targetLabel: string;+ width: number;+ height: number;+ redactions: number;+}++export type TermLineKind = "cmd" | "out" | "err" | "cli" | "note";++export interface TermLine {+ id: string;+ ts: number;+ kind: TermLineKind;+ /** Raw runtime text (a command, one output line). Never translated. */+ text: string;+ /** terminal_id / cli name — lets the card group by source. */+ source: string;+}++export interface WikiChange {+ slug: string;+ kind: string;+ ts: number;+}++export interface DeckState {+ usage: BrainUsage;+ cu: CuState;+ capture: CaptureState | null;+ termLines: TermLine[];+ wikiChanges: WikiChange[];+ /** Words in every final transcript this session. */+ wordsSession: number;+ /** Words in the most recent final transcript. */+ wordsLast: number;+ /** How many utterances were finalised. */+ utterances: number;+}++/** Hard caps — a long session must not grow any list unbounded. */+export const MAX_TERM_LINES = 80;+export const MAX_WIKI_CHANGES = 12;++const CU_PHASES: readonly CuPhase[] = ["observe", "uia", "plan", "think", "act", "verify"];++export function emptyDeckState(): DeckState {+ return {+ usage: {+ turns: 0,+ tokensIn: 0,+ tokensOut: 0,+ costUsd: 0,+ lastProvider: "",+ lastModel: "",+ lastTurnTs: null,+ lastCacheHit: false,+ byModel: {},+ },+ cu: {+ active: false,+ missionId: "",+ phase: "idle",+ stepIdx: 0,+ lastActionKind: "",+ lastTargetHint: "",+ lastActionOk: null,+ lastFrameSha: null,+ windowTitle: "",+ frames: 0,+ startedTs: null,+ endedReason: "",+ },+ capture: null,+ termLines: [],+ wikiChanges: [],+ wordsSession: 0,+ wordsLast: 0,+ utterances: 0,+ };+}++let seq = 0;+function nextId(): string {+ seq += 1;+ return `dk-${seq}`;+}++function str(v: unknown): string {+ return typeof v === "string" ? v : "";+}++function num(v: unknown): number {+ return typeof v === "number" && Number.isFinite(v) ? v : 0;+}++function obj(v: unknown): Record<string, unknown> {+ return v && typeof v === "object" ? (v as Record<string, unknown>) : {};+}++/**+ * Word count the way a person counts: runs of non-space characters. Good+ * enough for every language the app speaks; a CJK-aware count would need a+ * segmenter and would only matter for a locale the recogniser does not have.+ */+export function countWords(text: string): number {+ const trimmed = text.trim();+ if (!trimmed) return 0;+ return trimmed.split(/\s+/).length;+}++// Terminal output arrives as raw PTY data: ANSI colour, cursor moves, CR-only+// progress lines. The deck shows plain lines, so strip the escapes and split+// on newlines; a bare "\r" redraw is treated as its own line rather than+// dropped, which keeps progress bars visible instead of blank.+// CSI (colours, cursor moves), OSC (window titles, terminated by BEL or+// ESC \), and the charset selectors — each introduced by ESC (0x1b).+// eslint-disable-next-line no-control-regex+const ANSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][A-Z0-9]/g;++export function splitTerminalData(data: string): string[] {+ return data+ .replace(ANSI_RE, "")+ .split(/\r\n|\n|\r/)+ .map((l) => l.replace(/\t/g, " ").trimEnd())+ .filter((l) => l.length > 0);+}++function pushLines(lines: TermLine[], added: TermLine[]): TermLine[] {+ const merged = lines.concat(added);+ return merged.length > MAX_TERM_LINES ? merged.slice(merged.length - MAX_TERM_LINES) : merged;+}++/**+ * Fold one WS event into the deck state.+ *+ * 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.+ */+export function reduceDeck(+ state: DeckState,+ name: string,+ payload: unknown,+ tsMs: number,+): DeckState {+ const p = obj(payload);++ switch (name) {+ // ---- brain: what this session has cost ------------------------------+ case "BrainTurnCompleted": {+ const tokensIn = num(p.tokens_in);+ const tokensOut = num(p.tokens_out);+ const costUsd = num(p.cost_usd);+ const provider = str(p.provider);+ const model = str(p.model);+ const key = model || provider || "unknown";+ const prev = state.usage.byModel[key] ?? {+ turns: 0,+ tokensIn: 0,+ tokensOut: 0,+ costUsd: 0,+ };+ return {+ ...state,+ usage: {+ ...state.usage,+ turns: state.usage.turns + 1,+ tokensIn: state.usage.tokensIn + tokensIn,+ tokensOut: state.usage.tokensOut + tokensOut,+ costUsd: state.usage.costUsd + costUsd,+ lastProvider: provider || state.usage.lastProvider,+ lastModel: model || state.usage.lastModel,+ lastTurnTs: tsMs,+ byModel: {+ ...state.usage.byModel,+ [key]: {+ turns: prev.turns + 1,+ tokensIn: prev.tokensIn + tokensIn,+ tokensOut: prev.tokensOut + tokensOut,+ costUsd: prev.costUsd + costUsd,+ },+ },+ },+ };+ }+ case "BrainTTFT":+ return {+ ...state,+ usage: {+ ...state.usage,+ lastCacheHit: Boolean(p.cache_hit),+ lastModel: str(p.model) || state.usage.lastModel,+ },+ };++ // ---- computer use: what it is doing right now ------------------------+ case "CUControlStarted":+ return {+ ...state,+ cu: {+ ...emptyDeckState().cu,+ active: true,+ missionId: str(p.mission_id),+ phase: "observe",+ startedTs: tsMs,+ },+ };+ case "CUControlEnded":+ return {+ ...state,+ cu: {+ ...state.cu,+ active: false,+ phase: "idle",+ endedReason: str(p.reason) || "finished",+ },+ };+ case "CUStepProfiled": {+ const phase = str(p.phase) as CuPhase;+ return {+ ...state,+ cu: {+ ...state.cu,+ // A step event while no control session is open means the deck+ // joined mid-mission (page reload); mark it active so the card+ // shows something rather than "idle" over a moving cursor.+ active: true,+ phase: CU_PHASES.includes(phase) ? phase : state.cu.phase,+ stepIdx: Math.max(state.cu.stepIdx, num(p.step_idx)),+ },+ };+ }+ case "ActionPlanned":+ return {+ ...state,+ cu: {+ ...state.cu,+ phase: "act",+ lastActionKind: str(p.action_kind),+ lastTargetHint: str(p.target_hint),+ lastActionOk: null,+ },+ };+ case "ActionVerified":+ case "ActionExecuted": {+ // Only meaningful while a CU mission runs — the same events fire for+ // ordinary tool calls, which the thinking trace already shows.+ if (!state.cu.active) return state;+ const ok = typeof p.success === "boolean" ? p.success : null;+ return { ...state, cu: { ...state.cu, lastActionOk: ok } };+ }+ case "ObservationCaptured": {+ const sha = str(p.screenshot_hash);+ return {+ ...state,+ cu: {+ ...state.cu,+ lastFrameSha: sha || state.cu.lastFrameSha,+ windowTitle: str(p.window_title) || state.cu.windowTitle,+ frames: state.cu.frames + 1,+ },+ };+ }++ // ---- screen capture: the one-shot look --------------------------------+ case "ScreenCaptureCompleted":+ 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),+ },+ };++ // ---- terminals: shell + CLI ---------------------------------------------+ case "TerminalCommandExecuted": {+ const command = str(p.command);+ if (!command) return state;+ return {+ ...state,+ termLines: pushLines(state.termLines, [+ { id: nextId(), ts: tsMs, kind: "cmd", text: command, source: str(p.terminal_id) },+ ]),+ };+ }+ case "TerminalOutput": {+ const lines = splitTerminalData(str(p.data));+ if (lines.length === 0) return state;+ const source = str(p.terminal_id);+ return {+ ...state,+ termLines: pushLines(+ state.termLines,+ lines.map((text) => ({ id: nextId(), ts: tsMs, kind: "out" as const, text, source })),+ ),+ };+ }+ case "CliInvoked": {+ const cli = str(p.cli_name);+ const preview = str(p.command_preview);+ const text = preview ? `${cli} ${preview}`.trim() : cli;+ if (!text) return state;+ return {+ ...state,+ termLines: pushLines(state.termLines, [+ { id: nextId(), ts: tsMs, kind: "cli", text, source: cli },+ ]),+ };+ }+ case "CliInvocationFinished": {+ const cli = str(p.cli_name);+ const code = typeof p.exit_code === "number" ? p.exit_code : null;+ const ms = num(p.duration_ms);+ const text = code === null ? `${cli} · ${ms} ms` : `${cli} · exit ${code} · ${ms} ms`;+ return {+ ...state,+ termLines: pushLines(state.termLines, [+ { id: nextId(), ts: tsMs, kind: code === 0 || code === null ? "note" : "err", text, source: cli },+ ]),+ };+ }++ // ---- wiki: what memory just wrote ------------------------------------+ case "WikiPageChanged": {+ const slug = str(p.slug);+ if (!slug) return state;+ const next = [{ slug, kind: str(p.kind), ts: tsMs }]+ .concat(state.wikiChanges.filter((c) => c.slug !== slug))+ .slice(0, MAX_WIKI_CHANGES);+ return { ...state, wikiChanges: next };+ }++ // ---- words: the live counter's ground truth ---------------------------+ case "TranscriptFinal": {+ const transcript = obj(p.transcript);+ const words = countWords(str(transcript.text));+ if (words === 0) return state;+ return {+ ...state,+ wordsSession: state.wordsSession + words,+ wordsLast: words,+ utterances: state.utterances + 1,+ };+ }++ default:+ return state;+ }+}diff --git a/jarvis/ui/web/frontend/src/lib/dockMagnify.test.ts b/jarvis/ui/web/frontend/src/lib/dockMagnify.test.tsnew file mode 100644index 0000000000..141bcc3d24--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/dockMagnify.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from "vitest";+import { DOCK_MAX_SCALE, DOCK_RADIUS_UNITS, layoutDock, magnifyScale } from "@/lib/dockMagnify";++describe("magnifyScale", () => {+ it("is full size under the pointer and rest size beyond the radius", () => {+ expect(magnifyScale(0)).toBeCloseTo(DOCK_MAX_SCALE, 6);+ expect(magnifyScale(DOCK_RADIUS_UNITS)).toBe(1);+ expect(magnifyScale(DOCK_RADIUS_UNITS + 5)).toBe(1);+ expect(magnifyScale(Number.NaN)).toBe(1);+ });++ it("falls off smoothly and symmetrically", () => {+ const near = magnifyScale(0.5);+ const far = magnifyScale(1.5);+ expect(near).toBeGreaterThan(far);+ expect(far).toBeGreaterThan(1);+ expect(magnifyScale(-1.2)).toBeCloseTo(magnifyScale(1.2), 9);+ // Cosine window: at half the radius the lift is exactly half.+ expect(magnifyScale(DOCK_RADIUS_UNITS / 2)).toBeCloseTo(1 + (DOCK_MAX_SCALE - 1) / 2, 6);+ });+});++describe("layoutDock", () => {+ it("lays icons out at rest with the base stride when there is no pointer", () => {+ const { items, extent } = layoutDock(4, 32, 8, null);+ expect(items.map((i) => i.scale)).toEqual([1, 1, 1, 1]);+ expect(items.map((i) => i.center)).toEqual([24, 64, 104, 144]);+ expect(extent).toBe(4 * 40 + 8);+ });++ it("magnifies the icon under the pointer and pushes the rest outward", () => {+ const rest = layoutDock(5, 32, 8, null);+ // Pointer exactly on the centre of the third icon.+ const { items, extent } = layoutDock(5, 32, 8, rest.items[2].center);++ expect(items[2].scale).toBeCloseTo(DOCK_MAX_SCALE, 6);+ expect(items[1].scale).toBeGreaterThan(1);+ expect(items[3].scale).toBeCloseTo(items[1].scale, 9);+ // The row grew — nothing overlaps because everything after the big icon+ // moved by exactly the extra room it needs.+ expect(extent).toBeGreaterThan(rest.extent);+ for (let i = 1; i < items.length; i++) {+ const prevEnd = items[i - 1].center + items[i - 1].size / 2;+ const thisStart = items[i].center - items[i].size / 2;+ expect(thisStart).toBeGreaterThanOrEqual(prevEnd + 8 - 1e-9);+ }+ });++ it("leaves distant icons untouched", () => {+ const rest = layoutDock(12, 32, 8, null);+ const { items } = layoutDock(12, 32, 8, rest.items[0].center);+ expect(items[11].scale).toBe(1);+ expect(items[11].size).toBe(32);+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/dockMagnify.ts b/jarvis/ui/web/frontend/src/lib/dockMagnify.tsnew file mode 100644index 0000000000..d5889ffa87--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/dockMagnify.ts@@ -0,0 +1,79 @@+/**+ * The dock's magnification curve — the pure math behind DeckDock.tsx.+ *+ * The effect the maintainer asked for is the one desktop docks made familiar:+ * the icon under the pointer grows, its neighbours grow a little less, and+ * everything else stays put — a smooth hill, not a step. Two things make it+ * feel right rather than jumpy, and both live here so they can be tested+ * without a DOM:+ *+ * 1. A cosine falloff over a fixed radius. Linear falloff has a visible kink+ * where it hits zero; cosine eases into rest.+ * 2. Positions derived from the SCALES, not from the pointer. Each icon's+ * centre is the running sum of the sizes before it, so growing one pushes+ * the rest outward by exactly the space it takes — no overlap, no gap.+ */++/** Largest scale for the icon directly under the pointer. */+export const DOCK_MAX_SCALE = 1.75;+/** How far (in base-icon units) the hill reaches to either side. */+export const DOCK_RADIUS_UNITS = 2.6;++/**+ * Scale for one icon given the pointer's distance from its rest centre, in+ * base-icon units. 1 at rest, `DOCK_MAX_SCALE` when the pointer is centred.+ */+export function magnifyScale(+ distanceUnits: number,+ maxScale = DOCK_MAX_SCALE,+ radiusUnits = DOCK_RADIUS_UNITS,+): number {+ const d = Math.abs(distanceUnits);+ if (!Number.isFinite(d) || d >= radiusUnits) return 1;+ // Cosine window: 1 at d=0, 0 at d=radius, zero slope at both ends.+ const w = 0.5 * (1 + Math.cos((Math.PI * d) / radiusUnits));+ return 1 + (maxScale - 1) * w;+}++export interface DockLayoutItem {+ scale: number;+ /** Centre along the dock axis, in px from the dock's start (rest gap included). */+ center: number;+ /** Rendered size along the axis, in px. */+ size: number;+}++/**+ * Lay out `count` icons of `baseSize` px with `gap` px between them, given the+ * pointer position along the axis (`pointer`, px from the start; null = at+ * rest). Returns one entry per icon and the total extent.+ *+ * Positions come from the scales — every icon starts where the previous one+ * ended — so the row grows to make room instead of overlapping.+ */+export function layoutDock(+ count: number,+ baseSize: number,+ gap: number,+ pointer: number | null,+ maxScale = DOCK_MAX_SCALE,+ radiusUnits = DOCK_RADIUS_UNITS,+): { items: DockLayoutItem[]; extent: number } {+ const items: DockLayoutItem[] = [];+ const stride = baseSize + gap;+ // Rest centres are what the pointer is measured against: measuring against+ // the *magnified* centres would make an icon chase the pointer as it grows.+ const restCenters = Array.from({ length: count }, (_, i) => gap + i * stride + baseSize / 2);++ let cursor = gap;+ for (let i = 0; i < count; i++) {+ const scale =+ pointer === null+ ? 1+ : magnifyScale((pointer - restCenters[i]) / stride, maxScale, radiusUnits);+ const size = baseSize * scale;+ items.push({ scale, center: cursor + size / 2, size });+ cursor += size + gap;+ }+ return { items, extent: cursor };+}diff --git a/jarvis/ui/web/frontend/src/store/deck.ts b/jarvis/ui/web/frontend/src/store/deck.tsnew file mode 100644index 0000000000..46c95b1c99--- /dev/null+++ b/jarvis/ui/web/frontend/src/store/deck.ts@@ -0,0 +1,43 @@+import { create } from "zustand";+import { emptyDeckState, reduceDeck, type DeckState } from "@/lib/deckState";+import { readDeckMode, writeDeckMode, type DeckMode } from "@/lib/deckMode";++/**+ * The mission deck's own store: what its cards show, and which surface the+ * "chats" section is on.+ *+ * Fed from the WebSocket hook with one `ingest` call per event, the same way+ * the command-activity and thinking-trace stores are. Kept apart from the big+ * event store because none of this is read anywhere else — and because the+ * reducer returns the same object for the (vast) majority of events, which+ * `set` turns into a no-op without waking a single subscriber.+ *+ * The surface mode lives here rather than in a view's local state so the app+ * shell can read it: on the deck the sidebar gives way to the deck's own dock+ * (App.tsx), and a view cannot tell the shell that from the inside.+ */+interface DeckStore extends DeckState {+ mode: DeckMode;+ setMode: (mode: DeckMode) => void;+ ingest: (name: string, payload: unknown, tsMs: number) => void;+ /** Tests and a fresh session — forget everything but the surface choice. */+ resetDeck: () => void;+}++export const useDeckStore = create<DeckStore>((set, get) => ({+ ...emptyDeckState(),+ mode: readDeckMode(),++ setMode: (mode) => {+ writeDeckMode(mode);+ set({ mode });+ },++ ingest: (name, payload, tsMs) => {+ const before = get();+ const after = reduceDeck(before, name, payload, tsMs);+ if (after !== before) set(after);+ },++ resetDeck: () => set(emptyDeckState()),+}));diff --git a/jarvis/ui/web/frontend/src/views/ChatsSurface.tsx b/jarvis/ui/web/frontend/src/views/ChatsSurface.tsxindex 9a93b4d636..47d068d087 100644--- a/jarvis/ui/web/frontend/src/views/ChatsSurface.tsx+++ b/jarvis/ui/web/frontend/src/views/ChatsSurface.tsx@@ -1,7 +1,6 @@-import { useState } from "react";import { ChatsView } from "@/views/ChatsView";import { MissionDeckView, SurfaceSwitch } from "@/views/MissionDeckView";-import { readDeckMode, type DeckMode } from "@/lib/deckMode";+import { useDeckStore } from "@/store/deck";/*** The "chats" section: the mission deck, with the classic chat view one click@@ -14,12 +13,12 @@ import { readDeckMode, type DeckMode } from "@/lib/deckMode";* remembered. When the deck grows those features the switch can go; until then* it is what makes this a safe change rather than a lossy one.*- * The mode lives here rather than in the event store on purpose: nothing on the- * backend cares which surface is on screen, and a preference that never leaves- * the browser has no business on the event bus.+ * The mode lives in the deck store rather than here: the app shell reads it to+ * hide the sidebar while the deck (which brings its own dock) is on screen.*/export function ChatsSurface() {- const [mode, setMode] = useState<DeckMode>(() => readDeckMode());+ const mode = useDeckStore((s) => s.mode);+ const setMode = useDeckStore((s) => s.setMode);const accessory = <SurfaceSwitch mode={mode} onChange={setMode} />;return mode === "classic" ? (diff --git a/jarvis/ui/web/frontend/src/views/MissionDeckView.tsx b/jarvis/ui/web/frontend/src/views/MissionDeckView.tsxindex efb3046fe3..9b90f5ba4c 100644--- a/jarvis/ui/web/frontend/src/views/MissionDeckView.tsx+++ b/jarvis/ui/web/frontend/src/views/MissionDeckView.tsx@@ -1,37 +1,49 @@-import {- useCallback,- useEffect,- useMemo,- useRef,- useState,- type ReactNode,-} from "react";-import { LayoutList, Radio } from "lucide-react";-import { useEventStore, type SectionId } from "@/store/events";-import { NAV_GROUPS, resolveNavLabel } from "@/components/layout/navGroups";+import { useMemo, type ReactNode } from "react";+import { useEventStore, type VoiceState } from "@/store/events";import { ChatInput } from "@/components/ChatInput";-import { MascotGigi } from "@/components/MascotGigi";+import { VoiceWaveform, type WaveformPhase } from "@/components/overlay/VoiceWaveform";+import { voiceInputLevelRef } from "@/lib/voiceInputLevel";+import { DeckDock } from "@/components/deck/DeckDock";+import { DeckOrb } from "@/components/deck/DeckOrb";+import {+ FlowCard,+ IdeGridCard,+ OutputsCard,+ RunsCard,+ TerminalsCard,+ WikiCard,+} from "@/components/deck/DeckActivityCards";+import {+ ApiStatsCard,+ AppShotCard,+ ComputerUseCard,+ LiveCounter,+} from "@/components/deck/DeckSignalCards";import { useVoiceReadiness } from "@/hooks/useVoiceReadiness";+import { writeDeckMode } from "@/lib/deckMode";import { cn } from "@/lib/utils";import { useT } from "@/i18n";-import { writeDeckMode } from "@/lib/deckMode";-import type { ThinkingStep } from "@/lib/thinkingSteps";/*** The mission deck — the front page.*- * One surface that answers "what is going on" without a single navigation- * step: every section on the left with its live state, what the assistant is- * doing right now on the right, and the one place you talk to it in the middle.+ * One stage that shows everything the assistant is and does, without a+ * single navigation step, and the one place you talk to it in the middle.+ * The layout follows the maintainer's sketch of 2026-08-17:+ *+ * ┌ voice bars · live word counter ───────────────── name · brain · switch ┐+ * │ dock │ flow / runs ORB computer-use / api stats │+ * │ │ ide grid terminals · wiki app-shot / outputs │+ * └──────┴──────────────── talk: speak or type ─────────────────────────────┘*- * Everything on screen is REAL. There is no filler telemetry: a number that- * cannot be sourced from the store is simply not shown, because a deck whose- * figures are decorative teaches the user to stop reading it. That is why there- * is no cost meter and no context gauge here yet — the events exist on the bus- * (`BrainTTFT`, `BudgetWarning`) but nothing feeds them into this store, and- * inventing a plausible value would be worse than the gap.+ * Every card is a window onto a section and reads that section's own data;+ * clicking its eyebrow 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), so nothing appears twice.*- * Colours come from theme tokens only, so the deck holds in both appearances.+ * Nothing on this screen is invented. A number the store cannot source is+ * not shown, because a deck whose figures are decorative teaches the person+ * reading it to stop.*/export function MissionDeckView({headerAccessory,@@ -45,19 +57,17 @@ export function MissionDeckView({const brainModel = useEventStore((s) => s.brainModel);const connected = useEventStore((s) => s.connected);const voiceState = useEventStore((s) => s.voiceState);- const messages = useEventStore((s) => s.messages);const chatThinking = useEventStore((s) => s.chatThinking);const thinkingSteps = useEventStore((s) => s.thinkingSteps);- const conversations = useEventStore((s) => s.conversations);+ const messages = useEventStore((s) => s.messages);const setActiveSection = useEventStore((s) => s.setActiveSection);const { warming } = useVoiceReadiness();- // The live steps drive both the "running now" column and the ring around the- // mascot, so an active step is the deck's definition of "busy".const running = useMemo(() => thinkingSteps.filter((s) => s.status === "active"),[thinkingSteps],);+ const busy = chatThinking || running.length > 0 || voiceState === "thinking";const mood: DeckMood = !connected? "offline"@@ -65,17 +75,16 @@ export function MissionDeckView({? "fail": voiceState === "listening"? "listening"- : chatThinking || running.length > 0- ? "busy"- : "ready";+ : voiceState === "speaking"+ ? "speaking"+ : busy+ ? "busy"+ : "ready";- // The headline: the assistant's last word, or the honest state when it has- // not said anything yet in this session.const lastAssistant = useMemo(() => [...messages].reverse().find((m) => m.role === "assistant"),[messages],);-const headline = lastAssistant? lastAssistant.content: warming@@ -84,116 +93,111 @@ export function MissionDeckView({return (<div className="flex h-full min-h-0 flex-col">- <DeckHeader- assistantName={assistantName}- brainProvider={brainProvider}- brainModel={brainModel}- mood={mood}- runningCount={running.length}- accessory={headerAccessory}- />-- <div className="grid min-h-0 flex-1 grid-cols-1 lg:grid-cols-[minmax(160px,220px)_minmax(0,1fr)_minmax(200px,300px)]">- <SectionRail onJump={setActiveSection} chatCount={conversations.length} />-- <main className="flex min-h-0 flex-col border-border lg:border-x">- <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-4 px-6 py-6 text-center">- <CoreOrb mood={mood} steps={running} />-- <div className="font-mono text-[10px] uppercase tracking-[0.24em] text-primary">- {t(`deck.mood_${mood}`)}- </div>+ {/* Header strip: voice bars + live counter left, identity + brain right. */}+ <header className="flex flex-wrap items-center gap-x-5 gap-y-2 border-b border-border/70 px-4 py-2">+ <div className="flex items-center gap-3">+ <VoiceWaveform+ levelRef={voiceInputLevelRef}+ phase={waveformPhase(voiceState, connected)}+ count={14}+ className="h-6"+ />+ <span className="font-mono text-[10px] uppercase tracking-[0.18em] text-primary">+ {t(`deck.mood_${mood}`)}+ </span>+ </div>++ <LiveCounter className="ml-2" />++ <div className="ml-auto flex flex-wrap items-center gap-x-5 gap-y-1">+ <span className="font-display text-sm font-bold uppercase tracking-[0.18em]">+ {assistantName}+ </span>+ <HeaderStat+ label={t("deck.stat_brain")}+ value={brainProvider || "—"}+ hot+ onClick={() => setActiveSection("apikeys")}+ />+ <HeaderStat+ label={t("deck.stat_model")}+ value={brainModel || "—"}+ onClick={() => setActiveSection("apikeys")}+ />+ {headerAccessory}+ </div>+ </header>++ {/* Stage: dock on the left edge, cards around the orb. */}+ <div className="flex min-h-0 flex-1">+ <DeckDock className="border-r border-border/60" />++ <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(200px,3fr)] lg:grid-rows-[minmax(0,1fr)_minmax(0,0.85fr)] lg:overflow-hidden">+ {/* Row 1 — left: flow over runs */}+ <div className="flex min-h-0 flex-col gap-3">+ <FlowCard steps={thinkingSteps} className="min-h-0 flex-1" />+ <RunsCard className="max-h-[38%] shrink-0" />+ </div>- <p className="max-w-[46ch] text-pretty text-base leading-relaxed text-foreground">+ {/* Row 1 — centre: the orb and the headline */}+ <div className="flex min-h-0 flex-col items-center justify-center gap-3 px-2 text-center">+ <DeckOrb steps={running} busy={busy} size={250} />+ <p className="max-w-[46ch] text-pretty text-sm leading-relaxed text-foreground">{headline}</p>-- <ThoughtStream steps={thinkingSteps} active={chatThinking} /></div>- {/* The real composer — same component the classic view uses, so- dictation, file drop and Enter-to-send behave identically. */}- <div className="border-t border-border px-6 py-4">- <ChatInput />+ {/* Row 1 — right: computer use over api stats */}+ <div className="flex min-h-0 flex-col gap-3">+ <ComputerUseCard className="min-h-0 flex-1" />+ <ApiStatsCard className="shrink-0" /></div>- </main>-- <RunningColumn steps={thinkingSteps} />- </div>- </div>- );-}--type DeckMood = "ready" | "busy" | "listening" | "fail" | "offline";--const MOOD_DOT: Record<DeckMood, string> = {- ready: "bg-emerald-400",- busy: "bg-primary",- listening: "bg-primary",- fail: "bg-destructive",- offline: "bg-muted-foreground",-};-// -----------------------------------------------------------------------// Header — identity left, the values that steer a decision right.-// ----------------------------------------------------------------------+ {/* Row 2 — left: the coding workspace, shrunk */}+ <IdeGridCard className="min-h-[9rem]" />-function DeckHeader({- assistantName,- brainProvider,- brainModel,- mood,- runningCount,- accessory,-}: {- assistantName: string;- brainProvider: string;- brainModel: string;- mood: DeckMood;- runningCount: number;- accessory?: ReactNode;-}) {- const t = useT();- const setActiveSection = useEventStore((s) => s.setActiveSection);+ {/* Row 2 — centre: terminals and the wiki side by side */}+ <div className="grid min-h-[9rem] grid-cols-1 gap-3 sm:grid-cols-[3fr_2fr]">+ <TerminalsCard className="min-h-0" />+ <WikiCard className="min-h-0" />+ </div>- return (- <header className="flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-border px-4 py-2.5">- <div className="flex items-center gap-2">- <span- className={cn(- "h-2 w-2 shrink-0 rounded-full",- MOOD_DOT[mood],- (mood === "busy" || mood === "listening") && "animate-pulse",- )}- aria-hidden- />- <span className="font-display text-sm font-bold uppercase tracking-[0.18em]">- {assistantName}- </span>- <span className="font-mono text-[10px] uppercase tracking-[0.16em] text-primary">- {t(`deck.mood_${mood}`)}- </span>+ {/* Row 2 — right: the last capture over the outputs */}+ <div className="flex min-h-[9rem] flex-col gap-3">+ <AppShotCard className="min-h-0 flex-1" />+ <OutputsCard className="max-h-[48%] shrink-0" />+ </div>+ </div></div>- <div className="ml-auto flex flex-wrap items-center gap-x-5 gap-y-1">- <HeaderStat- label={t("deck.stat_brain")}- value={brainProvider || "—"}- hot- onClick={() => setActiveSection("apikeys")}- />- <HeaderStat- label={t("deck.stat_model")}- value={brainModel || "—"}- onClick={() => setActiveSection("apikeys")}- />- <HeaderStat label={t("deck.stat_running")} value={String(runningCount)} hot={runningCount > 0} />- {accessory}+ {/* The real composer — same component the classic view uses. */}+ <div className="border-t border-border px-6 py-3">+ <ChatInput /></div>- </header>+ </div>);}+type DeckMood = "ready" | "busy" | "listening" | "speaking" | "fail" | "offline";++function waveformPhase(state: VoiceState, connected: boolean): WaveformPhase {+ if (!connected) return "idle";+ switch (state) {+ case "connecting":+ return "connecting";+ case "listening":+ return "listening";+ case "thinking":+ return "working";+ case "speaking":+ return "speaking";+ case "error":+ return "error";+ default:+ return "idle";+ }+}+function HeaderStat({label,value,@@ -210,20 +214,12 @@ function HeaderStat({<span className="font-mono text-[10px] uppercase tracking-[0.14em] text-muted-foreground">{label}</span>- <span- className={cn(- "font-mono text-xs tabular-nums",- hot ? "text-primary" : "text-foreground",- )}- >+ <span className={cn("font-mono text-xs tabular-nums", hot ? "text-primary" : "text-foreground")}>{value}</span></>);-- if (!onClick) {- return <div className="flex items-baseline gap-1.5 whitespace-nowrap">{body}</div>;- }+ if (!onClick) return <div className="flex items-baseline gap-1.5 whitespace-nowrap">{body}</div>;return (<buttontype="button"@@ -235,297 +231,6 @@ function HeaderStat({);}-// -----------------------------------------------------------------------// Left — every section at once, straight from the sidebar's own list.-// ------------------------------------------------------------------------function SectionRail({- onJump,- chatCount,-}: {- onJump: (id: SectionId) => void;- chatCount: number;-}) {- const t = useT();- const activeSection = useEventStore((s) => s.activeSection);-- return (- <nav className="hidden min-h-0 flex-col overflow-hidden lg:flex">- <div className="flex items-center gap-2 border-b border-border px-3 py-2 font-mono text-[9px] uppercase tracking-[0.22em] text-primary">- <LayoutList className="h-3 w-3" />- {t("deck.sections")}- </div>-- <div className="min-h-0 flex-1 overflow-y-auto px-1.5 py-2">- {NAV_GROUPS.map((group, gi) => (- <div key={gi} className="mb-2">- {group.map((item) => {- // Only counts that are genuinely known are shown. "chats" is the- // one the store already holds; the rest stay blank rather than- // display a number nobody computed.- const count = item.id === "chats" ? chatCount : 0;- const isActive =- activeSection === item.id || item.matchIds?.includes(activeSection);- return (- <button- key={item.id}- type="button"- onClick={() => onJump(item.id)}- className={cn(- "flex w-full items-center gap-2 rounded-sm px-2 py-1 text-left transition-colors",- isActive ? "bg-primary/10" : "hover:bg-card/40",- )}- >- <item.icon- className={cn(- "h-3 w-3 shrink-0",- count > 0 ? "text-primary" : "text-muted-foreground",- )}- />- <span- className={cn(- "flex-1 truncate text-xs",- count > 0 ? "text-foreground" : "text-muted-foreground",- )}- >- {resolveNavLabel(t, item)}- </span>- {count > 0 && (- <span className="font-mono text-[10px] tabular-nums text-primary">- {count}- </span>- )}- </button>- );- })}- </div>- ))}- </div>- </nav>- );-}--// -----------------------------------------------------------------------// Centre — the mascot, ringed by one arc per running step.-// ------------------------------------------------------------------------const STEP_STROKE: Record<string, string> = {- brain: "hsl(var(--primary))",- tool: "hsl(var(--primary))",- computer: "hsl(var(--primary))",- worker: "hsl(var(--primary))",- note: "hsl(var(--muted-foreground))",-};--function CoreOrb({ mood, steps }: { mood: DeckMood; steps: ThinkingStep[] }) {- // A slow sweep that only turns while something is actually running — motion- // without a cause reads as a screensaver and stops meaning anything.- const [sweep, setSweep] = useState(0);- const raf = useRef<number | null>(null);- const busy = mood === "busy" || mood === "listening";-- useEffect(() => {- if (!busy || window.matchMedia("(prefers-reduced-motion: reduce)").matches) {- return;- }- let start: number | null = null;- const tick = (ts: number) => {- if (start === null) start = ts;- setSweep(((ts - start) / 28) % 360);- raf.current = requestAnimationFrame(tick);- };- raf.current = requestAnimationFrame(tick);- return () => {- if (raf.current !== null) cancelAnimationFrame(raf.current);- };- }, [busy]);-- const point = useCallback((deg: number, r: number): [number, number] => {- const rad = ((deg - 90) * Math.PI) / 180;- return [66 + r * Math.cos(rad), 66 + r * Math.sin(rad)];- }, []);-- const arcs = steps.slice(0, 6).map((step, i, all) => {- const span = 300 / Math.max(1, all.length);- const a0 = -150 + i * span + 3;- const a1 = a0 + (span - 6);- const [x0, y0] = point(a0, 52);- const [x1, y1] = point(a1, 52);- return {- id: step.id,- d: `M ${x0} ${y0} A 52 52 0 0 1 ${x1} ${y1}`,- stroke: STEP_STROKE[step.kind] ?? "hsl(var(--primary))",- };- });-- const [sx, sy] = point(sweep, 60);- const [ex, ey] = point(sweep + 40, 60);-- return (- <div className="relative h-[132px] w-[132px] shrink-0">- <svg viewBox="0 0 132 132" className="absolute inset-0 h-full w-full" aria-hidden>- {/* Scale ring — built once, static. */}- {Array.from({ length: 48 }, (_, i) => {- const deg = i * 7.5;- const [ax, ay] = point(deg, 38);- const [bx, by] = point(deg, 42);- return (- <line- key={deg}- x1={ax}- y1={ay}- x2={bx}- y2={by}- stroke="hsl(var(--primary))"- strokeWidth={1}- opacity={i % 6 === 0 ? 0.4 : 0.13}- />- );- })}-- {arcs.map((a) => (- <path- key={a.id}- d={a.d}- fill="none"- stroke={a.stroke}- strokeWidth={2.5}- strokeLinecap="round"- opacity={0.9}- />- ))}-- {busy && (- <path- d={`M ${sx} ${sy} A 60 60 0 0 1 ${ex} ${ey}`}- fill="none"- stroke="hsl(var(--primary))"- strokeWidth={1.2}- strokeLinecap="round"- opacity={0.5}- />- )}- </svg>-- <div className="absolute inset-0 grid place-items-center">- <MascotGigi size={54} reactToVoice enableComments={false} />- </div>- </div>- );-}--/**- * What the assistant is reasoning about, in its own words.- *- * Shows the newest step's translated label plus its raw detail. Deliberately- * one line: this is the pulse, not the transcript — the full trace lives in the- * running column beside it.- */-function ThoughtStream({ steps, active }: { steps: ThinkingStep[]; active: boolean }) {- const t = useT();- const latest = steps[steps.length - 1];-- if (!active && !latest) {- return <div className="min-h-[3.2em]" aria-hidden />;- }-- return (- <div className="w-full max-w-[46ch] border-l border-border pl-3 text-left">- <span className="block font-mono text-[9px] uppercase tracking-[0.2em] text-primary">- {t("deck.thinking_now")}- </span>- <span className="text-xs leading-relaxed text-muted-foreground">- {latest ? (- <>- {t(latest.labelKey)}- {latest.detail ? ` · ${latest.detail}` : ""}- </>- ) : (- t("deck.thinking_starting")- )}- </span>- </div>- );-}--// -----------------------------------------------------------------------// Right — every action the assistant is taking, live.-// ------------------------------------------------------------------------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",-};--function RunningColumn({ steps }: { steps: ThinkingStep[] }) {- const t = useT();- const shown = [...steps].reverse();-- return (- <aside className="flex min-h-0 flex-col overflow-hidden">- <div className="flex items-center gap-2 border-b border-border px-3 py-2 font-mono text-[9px] uppercase tracking-[0.22em] text-primary">- <Radio className="h-3 w-3" />- {t("deck.running")}- <span className="ml-auto tabular-nums text-muted-foreground">{steps.length}</span>- </div>-- <div className="min-h-0 flex-1 overflow-y-auto px-2 py-2">- {shown.length === 0 ? (- <p className="px-1 py-1 text-[11px] text-muted-foreground">- {t("deck.running_empty")}- </p>- ) : (- shown.map((step) => (- <div- key={step.id}- className={cn(- "mb-1 border-l px-2 py-1",- 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 pt-0.5 font-mono text-[10px] text-muted-foreground">- {step.detail}- </div>- )}- </div>- ))- )}- </div>- </aside>- );-}-/*** The escape hatch, rendered by the shell above both surfaces.*@@ -540,6 +245,7 @@ export function SurfaceSwitch({}) {const t = useT();const next = mode === "deck" ? "classic" : "deck";+ const label = t(next === "classic" ? "deck.switch_to_classic" : "deck.switch_to_deck");return (<button@@ -548,10 +254,10 @@ export function SurfaceSwitch({writeDeckMode(next);onChange(next);}}- title={t(next === "classic" ? "deck.switch_to_classic" : "deck.switch_to_deck")}+ title={label}className="flex items-center gap-1.5 rounded-lg border border-border px-2 py-1 font-mono text-[10px] uppercase tracking-[0.12em] text-muted-foreground transition-colors hover:border-primary/50 hover:text-primary">- {t(next === "classic" ? "deck.switch_to_classic" : "deck.switch_to_deck")}+ {label}</button>);}