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(ui): add the Visualization section for what a run actually drew
rubenluetke10-beepf3b00d61e3f4
diff --git a/jarvis/plugins/tool/navigate.py b/jarvis/plugins/tool/navigate.pyindex 6f0c47dd4f..bdc5613479 100644--- a/jarvis/plugins/tool/navigate.py+++ b/jarvis/plugins/tool/navigate.py@@ -53,7 +53,14 @@ KNOWN: frozenset[str] = frozenset("voice-shortcuts","voice-language","voice-api-keys",+ "visualization","agentic-ide",+ # The other two ids of the coding surface. They resolve to the same+ # workspace, and they were missing here while being valid SECTION_IDS —+ # which left the parity guard below red and made "open the terminal+ # grid" an unknown section to the brain.+ "agentic-ide-classic",+ "chat-workspace",})@@ -133,6 +140,19 @@ _ALIASES: dict[str, str] = {"fondo de pantalla": "wallpaper", # i18n-allow: input vocab"task bar": "taskbar","taskleiste": "taskbar",+ # The Visualization board. The English id is a mouthful in the other two+ # locales, so the spoken forms carry more weight here than for a section+ # whose name is already a common noun.+ "visualisation": "visualization",+ "visuals": "visualization",+ "charts": "visualization",+ "diagrams": "visualization",+ "visualisierung": "visualization", # i18n-allow: input vocab+ "visualisierungen": "visualization", # i18n-allow: input vocab+ "diagramme": "visualization", # i18n-allow: input vocab+ "visualización": "visualization", # i18n-allow: input vocab+ "visualizaciones": "visualization", # i18n-allow: input vocab+ "gráficos": "visualization", # i18n-allow: input vocab"contact": "contacts","kontakt": "contacts","kontakte": "contacts",diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 3a008fc42d..2d3771d588 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -75,6 +75,10 @@ DETACHABLE_VIEWS: dict[str, str] = {"voice-shortcuts": "Voice Shortcuts","voice-language": "Dictation Language","voice-api-keys": "Voice Input Keys",+ # The Visualization board. Detachable for the reason it exists at all: a+ # picture is something you keep looking at WHILE you carry on working, and+ # on a second monitor it stops competing with the section that produced it.+ "visualization": "Visualization",}META_FILE_PATH = DATA_DIR / ".jarvis-running"#: Timeout for the initial lock acquire, in seconds. 0 = non-blocking,diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsxindex e40f2111cc..f982ee8853 100644--- a/jarvis/ui/web/frontend/src/App.tsx+++ b/jarvis/ui/web/frontend/src/App.tsx@@ -29,6 +29,7 @@ import { installDictationFocusTracker } from "@/lib/dictationTarget";import { SubscriptionRealtimeTransportBroker } from "@/components/voice/SubscriptionRealtimeTransportBroker";import { useDesktopWallpaper } from "@/hooks/useDesktopWallpaper";import { installWallpaperSync } from "@/store/wallpaper";+import { cn } from "@/lib/utils";/** Where the collapsed/expanded choice for the nav sidebar is remembered. */const NAV_COLLAPSED_KEY = "jarvis.sidebar.collapsed.v1";@@ -61,6 +62,45 @@ function DesktopWallpaper() {);}+/**+ * The surface the active section is drawn on.+ *+ * Two grounds, because the app has two kinds of screen. Everything the app+ * writes itself sits on the wallpaper and gets the readability floor that comes+ * with it (`.jarvis-section-stage` in index.css). The Visualization section+ * shows pictures somebody ELSE produced — a rendered chart, a diagram, a framed+ * page — and the same floor damages those: an inherited text halo lands on the+ * labels inside an SVG, and busy artwork behind a transparent PNG makes it+ * impossible to tell what the picture actually looks like.+ *+ * The choice belongs to the shell rather than to the view. The stage is the+ * surface a section is laid out ON, and it has to hold in BOTH shapes this+ * component renders: the full window with nav and top bar, and the chrome-less+ * detached window where the section is the whole screen.+ *+ * Exported for its own test: rendering the whole shell to assert one class+ * would drag in the WebSocket, the wallpaper sync and the onboarding gate.+ */+export function SectionStage({+ visualization,+ children,+}: {+ visualization: boolean;+ children: React.ReactNode;+}) {+ return (+ <div+ className={cn(+ "min-h-0 flex-1",+ visualization ? "jarvis-visualization-stage" : "jarvis-section-stage",+ )}+ data-testid={visualization ? "jarvis-visualization-stage" : "jarvis-section-stage"}+ >+ {children}+ </div>+ );+}+export default function App() {useWebSocket();useBrainStatus();@@ -208,6 +248,11 @@ export default function App() {? activeSection === "chats": !detachedViews.includes("chats");+ // Which ground the section is drawn on — see `SectionStage`. Read here rather+ // than inside it so both window shapes below get the same answer from one+ // place.+ const visualizationActive = activeSection === "visualization";+/** A detached solo window is one section in its own desktop window: the* section IS the window, so the app chrome around it — nav, top bar,@@ -222,9 +267,9 @@ export default function App() {<DesktopWallpaper />{brokerMounted && <SubscriptionRealtimeTransportBroker />}<main className="relative z-10 flex min-w-0 flex-1 flex-col">- <div className="jarvis-section-stage min-h-0 flex-1">+ <SectionStage visualization={visualizationActive}><MainView />- </div>+ </SectionStage></main><ToastLayer /><CommandActivityLayer />@@ -264,9 +309,9 @@ export default function App() {<InputIsolationBanner /><TopBar /><VoiceWarmingBanner />- <div className="jarvis-section-stage min-h-0 flex-1">+ <SectionStage visualization={visualizationActive}><MainView />- </div>+ </SectionStage></main><ToastLayer />diff --git a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsxindex 284635079f..1ab7882dbf 100644--- a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx+++ b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useState } from "react";-import { ArrowUp, Bot, CreditCard, FlaskConical, Laptop, Lock, LogIn, LogOut, Sparkles, Terminal, type LucideIcon } from "lucide-react";+import { ArrowUp, Bot, CreditCard, FlaskConical, Frame, Laptop, Lock, LogIn, LogOut, Sparkles, Terminal, type LucideIcon } from "lucide-react";import { agentBrandNow, useAgentBrand } from "@/lib/agentBrand";import { PromptWriterCard } from "@/components/PromptWriterCard";import { cn } from "@/lib/utils";@@ -520,10 +520,22 @@ function BridgeMeta({* noise and is not surfaced.*/function BridgeStatusStrip({ status }: { status: SubagentStatus }) {+ const t = useT();const activeRow = status.mapping.find((row) => row.is_active_brain);const live = Boolean(activeRow?.key_set);const worker = PROVIDER_LABELS[status.brain_primary] ?? status.brain_primary;const model = status.model_resolved ?? status.sub_model_override ?? null;+ /*+ * The one place in this section that talks to another one.+ *+ * This strip describes the worker that RUNS; whatever it drew ends up in the+ * run archive, and until now the only way to that picture was to remember the+ * filename and go looking for it in Outputs. `requestVisual` hands the stage a+ * target and moves the app there in a single state update — see+ * VisualStageRequest in store/events.ts for why the section is asked rather+ * than reached into.+ */+ const requestVisual = useEventStore((s) => s.requestVisual);return (<div className="flex flex-wrap items-center gap-x-3 gap-y-2 rounded-2xl border border-border bg-card/60 px-4 py-3 backdrop-blur">@@ -557,6 +569,16 @@ function BridgeStatusStrip({ status }: { status: SubagentStatus }) {{status.time_cap_min} min · max {status.concurrency} parallel</BridgeMeta>)}+ <button+ type="button"+ onClick={() => requestVisual()}+ data-testid="agent-show-visuals"+ title={t("visualization.open_from_agent_hint")}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-full border border-border bg-secondary/40 px-2.5 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:border-primary/50 hover:text-foreground"+ >+ <Frame className="h-3 w-3" aria-hidden />+ {t("visualization.open_from_agent")}+ </button></div></div>);diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsxindex ff8c40a169..86e00e790d 100644--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx@@ -151,6 +151,11 @@ const TelephonySetupView = lazyView(() =>const WallpaperView = lazyView(() =>import("@/views/WallpaperView").then((m) => ({ default: m.WallpaperView })),);+const VisualizationView = lazyView(() =>+ import("@/views/VisualizationView").then((m) => ({+ default: m.VisualizationView,+ })),+);type IdleWindow = Window & {requestIdleCallback?: (@@ -423,6 +428,11 @@ function SwitchOnActiveSection({ active }: { active: string }) {return <AgentInstructionsView />;case "wallpaper":return <WallpaperView />;+ // The visual stage for what a run produced. Rendered through the same+ // switch as every other section — the shell only decides what the stage+ // AROUND it looks like (see App.tsx).+ case "visualization":+ return <VisualizationView />;// Deliberately nothing: the coding workspace is rendered by the STICKY// branch in `MainView` above, which keeps it mounted across section// changes. This switch is not rendered at all while one of those ids isdiff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsxindex 550912e91d..04d34613a3 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx@@ -18,6 +18,7 @@ import {MessageSquareWarning,ScrollText,MessagesSquare,+ Frame,Image as ImageIcon,Loader2,type LucideIcon,@@ -94,6 +95,15 @@ const NAV_GROUPS: NavItem[][] = [{ id: "tasks", labelKey: "nav.tasks", icon: ListTodo },{ id: "sessions", labelKey: "nav.sessions", icon: Mic },{ id: "run_inspector", labelKey: "nav.run_inspector", icon: Gauge },+ // The visual stage. Sits with the content group next to Outputs on+ // purpose: it reads the same run archive, it just shows the pictures in it+ // instead of listing the files.+ {+ id: "visualization",+ labelKey: "nav.visualization",+ icon: Frame,+ fallbackLabel: "Visualization",+ },{ id: "board", labelKey: "nav.board", icon: Sparkles },{ id: "memory", labelKey: "nav.wiki", icon: Notebook },{ id: "contacts", labelKey: "nav.contacts", icon: Contact },diff --git a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsxindex b67ecc0c83..e7a4b9e3f7 100644--- a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx@@ -104,6 +104,7 @@ const DETACHABLE_SECTIONS = new Set<SectionId>(["voice-shortcuts","voice-language","voice-api-keys",+ "visualization",]);/**diff --git a/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts b/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.tsnew file mode 100644index 0000000000..9f2e15db44--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts@@ -0,0 +1,186 @@+/**+ * The visual artifacts a run left behind — the data behind the Visualization+ * section.+ *+ * No new REST surface: `/api/outputs` already lists the runs and+ * `/api/outputs/{slug}/artifacts` already lists their files, so this hook is a+ * read over what the Outputs view reads too. What it adds is the SELECTION —+ * which of those files are things a person can look at — and a flat, newest-+ * first list across runs, because "show me what came out of this" is a question+ * about pictures, not about directories.+ *+ * The scan is BOUNDED (`DEFAULT_RUN_SCAN_LIMIT`). One artifact listing per run+ * is one filesystem walk on the backend, and a machine with three hundred+ * archived runs would pay for all of them on every visit to the section. The+ * limit is stated in the UI rather than hidden, so a missing older picture reads+ * as "not scanned" instead of "not there".+ */+import { useQueries } from "@tanstack/react-query";++import {+ useOutputsList,+ type ArtifactSummary,+ type ArtifactsResponse,+ type OutputSummary,+} from "@/hooks/useOutputs";++/** How a visual is put on screen — one branch of the stage per kind. */+export type VisualKind = "image" | "vector" | "page" | "document";++/**+ * Extension → kind. Deliberately narrow: everything here must render inside the+ * desktop WebView without a plugin or a converter. A format that only *some*+ * hosts can draw would make the stage a coin flip, and a blank frame is a worse+ * answer than not listing the file at all (it still shows up in Outputs).+ */+const VISUAL_EXTENSIONS: ReadonlyArray<readonly [string, VisualKind]> = [+ [".png", "image"],+ [".jpg", "image"],+ [".jpeg", "image"],+ [".gif", "image"],+ [".webp", "image"],+ [".bmp", "image"],+ [".avif", "image"],+ [".svg", "vector"],+ [".html", "page"],+ [".htm", "page"],+ [".pdf", "document"],+];++/** The kind this filename renders as, or null when it is not a visual. */+export function classifyVisual(path: string): VisualKind | null {+ const lower = path.toLowerCase();+ for (const [extension, kind] of VISUAL_EXTENSIONS) {+ if (lower.endsWith(extension)) return kind;+ }+ return null;+}++/** One renderable artifact, already carrying the run it belongs to. */+export interface VisualArtifact {+ /** Run directory name — the `/api/outputs/{slug}` path segment. */+ slug: string;+ /** What the user asked for, when the run recorded it. */+ utterance?: string;+ /** Artifact path relative to the run directory. */+ path: string;+ /** Last path segment — what the tile is labelled with. */+ name: string;+ kind: VisualKind;+ size: number;+ mtime: number;+ /** Ready-to-use `src` for an `<img>`/`<iframe>` (served inline). */+ url: string;+}++/** Newest runs scanned for visuals. See the module docstring for the why. */+export const DEFAULT_RUN_SCAN_LIMIT = 10;++/**+ * Encode an artifact path segment by segment.+ *+ * Same rule as `useOutputs.encodeArtifactPath` (not exported there): `encodeURI`+ * leaves `#`, `?` and `&` raw, so a file called `chart#2.png` would be truncated+ * at the `#` and 404.+ */+function encodeArtifactPath(path: string): string {+ return path.split("/").map(encodeURIComponent).join("/");+}++/** The inline URL a visual is rendered from. */+export function visualUrl(slug: string, path: string): string {+ return `/api/outputs/${encodeURIComponent(slug)}/files/${encodeArtifactPath(+ path,+ )}/download?disposition=inline`;+}++/** A stable identity for one artifact — the selection key and the React key. */+export function visualId(artifact: Pick<VisualArtifact, "slug" | "path">): string {+ return `${artifact.slug}::${artifact.path}`;+}++function toVisuals(run: OutputSummary, files: ArtifactSummary[]): VisualArtifact[] {+ const visuals: VisualArtifact[] = [];+ for (const file of files) {+ const kind = classifyVisual(file.path);+ if (kind === null) continue;+ visuals.push({+ slug: run.slug,+ utterance: run.utterance,+ path: file.path,+ name: file.path.split("/").pop() ?? file.path,+ kind,+ size: file.size,+ mtime: file.mtime,+ url: visualUrl(run.slug, file.path),+ });+ }+ return visuals;+}++export interface VisualArtifactsResult {+ /** Every visual found, newest file first. */+ visuals: VisualArtifact[];+ /** How many runs were actually looked at (≤ `limit`). */+ scannedRuns: number;+ /** Runs that exist but were outside the scan window. */+ skippedRuns: number;+ /** True while the run list or any artifact listing is still in flight. */+ isLoading: boolean;+ /** The run list could not be read at all — the honest "backend is down" case. */+ isError: boolean;+ refetch: () => void;+}++/**+ * Every visual artifact of the newest `limit` runs, newest file first.+ *+ * A run whose artifact listing fails contributes nothing instead of taking the+ * section down with it: half a gallery is still a gallery, and the failure is+ * almost always a run directory that was cleaned up between the two requests.+ */+export function useVisualArtifacts(+ limit: number = DEFAULT_RUN_SCAN_LIMIT,+): VisualArtifactsResult {+ const outputs = useOutputsList();+ const runs = outputs.data ?? [];+ // `/api/outputs` is already sorted newest-first; sorting again here would be+ // a second, weaker opinion about the same order.+ const scanned = runs.slice(0, limit);++ return useQueries({+ queries: scanned.map((run) => ({+ // Same key as `useArtifactsForOutput`, so the Outputs view and this+ // section share one cache entry rather than each fetching their own.+ queryKey: ["output-artifacts", run.slug],+ queryFn: async (): Promise<ArtifactsResponse> => {+ const response = await fetch(+ `/api/outputs/${encodeURIComponent(run.slug)}/artifacts`,+ );+ if (!response.ok) throw new Error(`HTTP ${response.status}`);+ return response.json();+ },+ // No poll: a gallery that re-listed ten run directories every few seconds+ // would keep a disk busy for pictures that almost never change. The header+ // carries an explicit refresh instead.+ staleTime: 30_000,+ })),+ combine: (results) => {+ const visuals = results.flatMap((result, index) =>+ result.data ? toVisuals(scanned[index], result.data.files ?? []) : [],+ );+ visuals.sort((a, b) => b.mtime - a.mtime);+ return {+ visuals,+ scannedRuns: scanned.length,+ skippedRuns: Math.max(0, runs.length - scanned.length),+ isLoading: outputs.isLoading || results.some((r) => r.isLoading),+ isError: outputs.isError,+ refetch: () => {+ void outputs.refetch();+ for (const result of results) void result.refetch();+ },+ };+ },+ });+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 33b58a5bde..aa95f0b610 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -80,6 +80,7 @@"tasks": "Aufgaben","sessions": "Transkription","run_inspector": "Run Inspector",+ "visualization": "Visualisierung","clis": "CLIs","cli_test_hub": "CLI Test Hub","clis_hub": "CLIs & CLI Test Hub",@@ -4102,5 +4103,26 @@"polished": "aufgeräumt","show_original": "Zeigen, was wirklich gesagt wurde","hide_original": "Original ausblenden"+ },+ "visualization": {+ "title": "Visualisierung",+ "subtitle": "Die Bilder, Diagramme und Seiten aus deinen Durchläufen",+ "refresh": "Aktualisieren",+ "scan_note": "Die neuesten {0} Durchläufe durchsucht, {1} ältere nicht.",+ "empty_title": "Noch nichts zu sehen",+ "empty_body": "Diagramme, Grafiken, Bilder und HTML-Seiten, die ein Durchlauf als Datei speichert, erscheinen hier. In den durchsuchten Durchläufen war nichts Visuelles dabei.",+ "error_title": "Das Archiv der Durchläufe ist nicht lesbar",+ "error_body": "Die Liste der Durchläufe ist gerade nicht verfügbar. Versuch es gleich noch einmal.",+ "render_failed": "Diese Datei lässt sich hier nicht anzeigen. Öffne sie stattdessen im Browser oder auf dem Desktop.",+ "sandbox_note": "Nur Vorschau: Skripte und externe Inhalte sind blockiert. Für die vollständige Seite im Browser öffnen.",+ "zoom_in": "Vergrößern",+ "zoom_out": "Verkleinern",+ "zoom_fit": "Einpassen",+ "open_external": "Öffnen",+ "download": "Kopie speichern",+ "reveal": "Im Ordner zeigen",+ "reveal_failed": "Die Datei konnte nicht im Ordner gezeigt werden.",+ "open_from_agent": "Visualisierungen",+ "open_from_agent_hint": "Zeigt die Bilder, Diagramme und Seiten der letzten Läufe an."}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 4db370ac29..04fdbd0176 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -80,6 +80,7 @@"tasks": "Tasks","sessions": "Transcription","run_inspector": "Run Inspector",+ "visualization": "Visualization","clis": "CLIs","cli_test_hub": "CLI Test Hub","clis_hub": "CLIs & CLI Test Hub",@@ -4102,5 +4103,26 @@"polished": "tidied up","show_original": "Show what was actually said","hide_original": "Hide the original"+ },+ "visualization": {+ "title": "Visualization",+ "subtitle": "The pictures, diagrams and pages your runs produced",+ "refresh": "Refresh",+ "scan_note": "Newest {0} runs scanned, {1} older ones not.",+ "empty_title": "Nothing to show yet",+ "empty_body": "Charts, diagrams, images and HTML pages a run saves as a file appear here. Nothing visual was found in the runs that were scanned.",+ "error_title": "The run archive could not be read",+ "error_body": "The list of runs is unavailable right now. Try again in a moment.",+ "render_failed": "This file could not be displayed. Open it in your browser or on the desktop instead.",+ "sandbox_note": "Preview only: scripts and external content are blocked. Open it in your browser for the full page.",+ "zoom_in": "Zoom in",+ "zoom_out": "Zoom out",+ "zoom_fit": "Fit",+ "open_external": "Open",+ "download": "Save a copy",+ "reveal": "Show in folder",+ "reveal_failed": "That file could not be shown in the folder.",+ "open_from_agent": "Visuals",+ "open_from_agent_hint": "Show the images, diagrams and pages the latest runs produced."}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex b39aab366e..4e3f69abc4 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -80,6 +80,7 @@"tasks": "Tareas","sessions": "Transcripción","run_inspector": "Run Inspector",+ "visualization": "Visualización","clis": "CLIs","cli_test_hub": "CLI Test Hub","clis_hub": "CLIs & CLI Test Hub",@@ -4102,5 +4103,26 @@"polished": "pulido","show_original": "Mostrar lo que se dijo realmente","hide_original": "Ocultar el original"+ },+ "visualization": {+ "title": "Visualización",+ "subtitle": "Las imágenes, los diagramas y las páginas que produjeron tus ejecuciones",+ "refresh": "Actualizar",+ "scan_note": "Se revisaron las {0} ejecuciones más recientes; {1} más antiguas, no.",+ "empty_title": "Todavía no hay nada que mostrar",+ "empty_body": "Aquí aparecen los gráficos, diagramas, imágenes y páginas HTML que una ejecución guarda como archivo. En las ejecuciones revisadas no había nada visual.",+ "error_title": "No se pudo leer el archivo de ejecuciones",+ "error_body": "La lista de ejecuciones no está disponible ahora mismo. Inténtalo de nuevo en un momento.",+ "render_failed": "Este archivo no se puede mostrar aquí. Ábrelo en el navegador o en el escritorio.",+ "sandbox_note": "Solo vista previa: los scripts y el contenido externo están bloqueados. Ábrelo en el navegador para ver la página completa.",+ "zoom_in": "Acercar",+ "zoom_out": "Alejar",+ "zoom_fit": "Ajustar",+ "open_external": "Abrir",+ "download": "Guardar una copia",+ "reveal": "Mostrar en la carpeta",+ "reveal_failed": "No se pudo mostrar el archivo en la carpeta.",+ "open_from_agent": "Visuales",+ "open_from_agent_hint": "Muestra las imágenes, diagramas y páginas de las últimas ejecuciones."}}diff --git a/jarvis/ui/web/frontend/src/index.css b/jarvis/ui/web/frontend/src/index.cssindex 9432617510..4ceeb2b844 100644--- a/jarvis/ui/web/frontend/src/index.css+++ b/jarvis/ui/web/frontend/src/index.css@@ -561,6 +561,28 @@0 0 12px rgb(var(--shell-rgb) / 0.6);}+ /*+ * The visualization viewport — a section stage's opposite number.+ *+ * The readability floor above works by putting a text halo on EVERY+ * descendant, which is right for a screen made of the app's own text and+ * wrong for one made of somebody else's picture: the halo lands on the labels+ * inside a rendered SVG chart and on the type of a framed HTML page, where it+ * reads as a printing error. So this stage takes the opposite deal — no+ * inherited shadow, and a quiet opaque ground instead of the wallpaper, so a+ * diagram with a transparent background is judged against one flat colour+ * rather than against whichever artwork the user picked.+ *+ * Chosen by the shell (App.tsx) rather than by the view, for the same reason+ * the section stage is: it is the surface the section is drawn ON, and a view+ * that painted its own would keep it in a detached window but lose it the+ * moment the shell laid something else out around it.+ */+ .jarvis-visualization-stage {+ background: rgb(var(--shell-rgb) / 0.94);+ text-shadow: none;+ }+/* Subtle grid pattern in the background — gives a dashboard feel withoutdistracting. Drawn in the accent so it reads as the app's own texture;slightly stronger on paper, where a 4 % line simply disappears. */diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.tsindex 561fdc469c..191c148432 100644--- a/jarvis/ui/web/frontend/src/store/events.ts+++ b/jarvis/ui/web/frontend/src/store/events.ts@@ -77,6 +77,9 @@ export type SectionId =| "voice-shortcuts"| "voice-language"| "voice-api-keys"+ // The visual stage: the pictures, diagrams and rendered pages a run produced,+ // shown at full size instead of as a filename in a list.+ | "visualization"| "agentic-ide"// The rebuilt chat surface — projects, their chats, one conversation on// screen. Lives alongside "agentic-ide" until its parity checklist is empty.@@ -121,6 +124,7 @@ export const SECTION_IDS = ["voice-shortcuts","voice-language","voice-api-keys",+ "visualization","agentic-ide","chat-workspace","agentic-ide-classic",@@ -186,6 +190,7 @@ export const SECTION_LABELS: Record<SectionId, string> = {"voice-shortcuts": "Voice Shortcuts","voice-language": "Dictation Language","voice-api-keys": "Voice Input Keys",+ visualization: "Visualization","agentic-ide": "Agentic IDE","chat-workspace": "Chat","agentic-ide-classic": "Terminal grid",@@ -273,6 +278,30 @@ export interface CliConnectCoach {statusCommand: string | null; // e.g. "gh auth status" — optional, for a manual recheck}+/**+ * "Put this on the Visualization stage" — one view asking another to show+ * something.+ *+ * The section owns WHICH visual is on its stage; every other surface can only+ * ask. That direction matters: a component that reached into the section and+ * set its selection would break the moment the section is not mounted (it is+ * unmounted whenever another section is on screen), whereas a request simply+ * waits in the store until the stage reads it.+ *+ * `target` is a `visualId(artifact)` — or the string `"latest"` for "whatever+ * the newest picture is", which is what a caller who has not looked at the+ * gallery actually means.+ *+ * `seq` exists because the same request twice must still work. Asking for+ * "latest" again after clicking around the gallery has to pull the stage back;+ * without a counter the store value would be unchanged and the effect that+ * honours it would never re-run.+ */+export interface VisualStageRequest {+ target: string;+ seq: number;+}+/*** Whether Jarvis is currently an Agentic IDE, for any surface that must say so.*@@ -325,6 +354,12 @@ interface EventStore {* mounted instance would steal every pane's output stream.*/detachedViews: SectionId[];+ /**+ * The pending "show this" request for the Visualization stage, or null when+ * nobody has asked for anything (the stage then keeps its own selection).+ * Written by `requestVisual`, read by the section — see VisualStageRequest.+ */+ visualStage: VisualStageRequest | null;transcription: string;transcriptionFinal: boolean;toasts: Toast[];@@ -395,6 +430,13 @@ interface EventStore {clearEvents: () => void;setActiveSection: (s: SectionId) => void;setDetachedViews: (views: SectionId[]) => void;+ /**+ * Route a visual into the Visualization section and go there.+ *+ * The one entry point for "show me this" from anywhere in the app. Pass a+ * `visualId(artifact)`, or omit the argument for the newest visual.+ */+ requestVisual: (target?: string) => void;setTranscription: (text: string, isFinal: boolean) => void;pushToast: (kind: Toast["kind"],@@ -470,6 +512,7 @@ export const useEventStore = create<EventStore>((set, get) => ({typeof window === "undefined" ? "" : window.location.search,),detachedViews: [],+ visualStage: null,transcription: "",transcriptionFinal: true,toasts: [],@@ -508,6 +551,16 @@ export const useEventStore = create<EventStore>((set, get) => ({setActiveSection: (s) => set({ activeSection: s }),setDetachedViews: (views) => set({ detachedViews: views }),+ requestVisual: (target = "latest") =>+ set((state) => ({+ visualStage: { target, seq: (state.visualStage?.seq ?? 0) + 1 },+ // A solo window is pinned to the one section it was opened for, so the+ // navigation half of this is skipped there — switching it would blank the+ // very view the user split off to keep. The request itself still lands,+ // which is what a detached Visualization window needs.+ activeSection: state.solo ? state.activeSection : "visualization",+ })),+setTranscription: (text, isFinal) =>set({ transcription: text, transcriptionFinal: isFinal }),diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsxnew file mode 100644index 0000000000..36a0df9a2c--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx@@ -0,0 +1,203 @@+/**+ * The Visualization section — what it selects, what it shows, what it admits.+ *+ * Three contracts are worth pinning:+ * - only files that can actually be DRAWN are offered (a run's logs and JSON+ * are not visuals, and listing them would make the gallery a file browser),+ * - the shell, not the view, decides the ground the section sits on — the+ * readability halo that helps the app's own text damages a rendered picture,+ * - the bounded scan is stated on screen, so an older run that was not looked+ * at never reads as a run that produced nothing.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++import { SectionStage } from "@/App";+import { VisualizationView } from "@/views/VisualizationView";+import { classifyVisual, visualUrl } from "@/hooks/useVisualArtifacts";+import type { ArtifactSummary, OutputSummary } from "@/hooks/useOutputs";++// ViewHeader lives in ChatsView, which subscribes to a WS client on mount —+// null keeps that a deterministic no-op in jsdom (same pattern as OutputsView).+vi.mock("@/hooks/useWebSocket", () => ({+ getWSClient: () => null,+}));++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.clearAllMocks();+});++function installFetchMock(+ runs: OutputSummary[],+ artifactsBySlug: Record<string, ArtifactSummary[]>,+) {+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url.includes("/capabilities")) {+ return {+ ok: true,+ status: 200,+ json: async () => ({ native_file_actions: false, platform: "linux" }),+ };+ }+ const artifacts = /\/api\/outputs\/([^/]+)\/artifacts/.exec(url);+ if (artifacts) {+ const slug = decodeURIComponent(artifacts[1]);+ return {+ ok: true,+ status: 200,+ json: async () => ({ files: artifactsBySlug[slug] ?? [] }),+ };+ }+ if (url.includes("/api/outputs")) {+ return { ok: true, status: 200, json: async () => ({ sessions: runs }) };+ }+ return { ok: true, status: 200, json: async () => ({}) };+ });+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++function renderView() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },+ });+ return render(+ <QueryClientProvider client={client}>+ <VisualizationView />+ </QueryClientProvider>,+ );+}++function file(path: string, over: Partial<ArtifactSummary> = {}): ArtifactSummary {+ return {+ path,+ size: 2048,+ mtime: 1_700_000_000,+ is_text: false,+ preview: null,+ ...over,+ };+}++describe("classifyVisual", () => {+ it("accepts what the WebView can draw", () => {+ expect(classifyVisual("chart.png")).toBe("image");+ expect(classifyVisual("out/PHOTO.JPEG")).toBe("image");+ expect(classifyVisual("diagram.svg")).toBe("vector");+ expect(classifyVisual("report.html")).toBe("page");+ expect(classifyVisual("paper.pdf")).toBe("document");+ });++ it("rejects everything else, however data-shaped", () => {+ // These are real deliverables — they simply belong in Outputs, not on a+ // stage that promises a picture.+ for (const name of ["run.log", "data.csv", "notes.md", "result.json", "app.py"]) {+ expect(classifyVisual(name)).toBeNull();+ }+ });++ it("encodes each path segment, so '#' in a filename survives", () => {+ // encodeURI would leave the '#' raw and the server would see a fragment.+ expect(visualUrl("run-1", "figs/chart#2.png")).toContain("chart%232.png");+ });+});++describe("VisualizationView", () => {+ it("lists only the visual artifacts and stages the newest one", async () => {+ installFetchMock(+ [+ { slug: "run-new", utterance: "draw the architecture" },+ { slug: "run-old", utterance: "summarise the logs" },+ ],+ {+ "run-new": [+ file("artifacts/diagram.svg", { mtime: 2_000 }),+ file("artifacts/build.log", { mtime: 2_500, is_text: true }),+ ],+ "run-old": [file("artifacts/old-chart.png", { mtime: 1_000 })],+ },+ );++ renderView();++ const gallery = await screen.findByTestId("visualization-gallery");+ await waitFor(() => expect(gallery.querySelectorAll("li")).toHaveLength(2));+ // The .log is a deliverable, but not a picture.+ expect(screen.queryByText("build.log")).toBeNull();++ // Newest file first, and the stage opens on it without a click.+ const image = await screen.findByTestId("visualization-image");+ expect(image.getAttribute("src")).toContain("diagram.svg");+ });++ it("switches the stage to the artifact that was clicked", async () => {+ installFetchMock([{ slug: "run-1", utterance: "make two charts" }], {+ "run-1": [+ file("a/first.png", { mtime: 2_000 }),+ file("a/second.png", { mtime: 1_000 }),+ ],+ });++ renderView();++ const second = await screen.findByText("second.png");+ fireEvent.click(second);++ await waitFor(() =>+ expect(+ screen.getByTestId("visualization-image").getAttribute("src"),+ ).toContain("second.png"),+ );+ });++ it("frames a page rather than drawing it as an image", async () => {+ installFetchMock([{ slug: "run-1", utterance: "build a report" }], {+ "run-1": [file("report.html")],+ });++ renderView();++ const frame = await screen.findByTestId("visualization-frame");+ // Inert preview: an empty sandbox is an opaque origin with no scripts, on+ // top of the no-script CSP the backend already sends for inline HTML.+ expect(frame.getAttribute("sandbox")).toBe("");+ expect(screen.queryByTestId("visualization-image")).toBeNull();+ });++ it("says so when the scanned runs produced nothing visual", async () => {+ installFetchMock([{ slug: "run-1", utterance: "tidy the notes" }], {+ "run-1": [file("notes.md", { is_text: true })],+ });++ renderView();++ await screen.findByTestId("visualization-empty");+ expect(screen.queryByTestId("visualization-stage")).toBeNull();+ });+});++describe("SectionStage", () => {+ it("drops the wallpaper readability halo for the visualization section", () => {+ const { container, rerender } = render(+ <SectionStage visualization={false}>+ <span>section</span>+ </SectionStage>,+ );+ expect(container.firstElementChild?.className).toContain("jarvis-section-stage");++ rerender(+ <SectionStage visualization>+ <span>section</span>+ </SectionStage>,+ );+ const stage = container.firstElementChild;+ expect(stage?.className).toContain("jarvis-visualization-stage");+ // Never both: the halo is inherited by every descendant, which is exactly+ // what must not happen over a rendered picture.+ expect(stage?.className).not.toContain("jarvis-section-stage");+ });+});diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.tsxnew file mode 100644index 0000000000..8d246fd932--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.tsx@@ -0,0 +1,425 @@+import { useCallback, useEffect, useMemo, useState } from "react";+import {+ Download,+ ExternalLink,+ FileImage,+ FolderOpen,+ Frame,+ Loader2,+ Maximize2,+ RefreshCw,+ ShieldAlert,+ ZoomIn,+ ZoomOut,+} from "lucide-react";++import { Button } from "@/components/ui/button";+import { ScrollArea } from "@/components/ui/scroll-area";+import { ViewHeader } from "@/views/ChatsView";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";+import { openExternalUrl } from "@/lib/openExternal";+import {+ artifactDownloadUrl,+ revealArtifact,+ useOutputsCapabilities,+} from "@/hooks/useOutputs";+import {+ DEFAULT_RUN_SCAN_LIMIT,+ useVisualArtifacts,+ visualId,+ type VisualArtifact,+} from "@/hooks/useVisualArtifacts";++/**+ * The Visualization section — everything a run DREW, at full size.+ *+ * The app could already tell you that a chart exists: Outputs lists it as a+ * filename in a directory, one row among the logs and the JSON. What it could+ * not do is show it to you. A picture reduced to its filename is the one+ * artifact class that loses all of its meaning in a list, so this section reads+ * the same run archive and puts the images, vector drawings and rendered pages+ * on a stage instead.+ *+ * It owns no data of its own — see `useVisualArtifacts`. That is deliberate: a+ * second store of "the visuals" would need its own writer, its own cleanup and+ * its own answer for the runs that existed before the feature. Reading the+ * archive means every run ever made is already in here.+ *+ * Detachable (`DETACHABLE_VIEWS` in jarvis/ui/desktop_app.py): a diagram is the+ * thing people put on a second monitor while they work in the first window.+ */++const ZOOM_STEPS = [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4] as const;++/** Human file size, rounded the way a caption wants it. */+function formatSize(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+}++/** The run label a tile is filed under — the utterance, else the raw slug. */+function runLabel(artifact: VisualArtifact): string {+ return artifact.utterance?.trim() || artifact.slug;+}++export function VisualizationView() {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const capabilities = useOutputsCapabilities();+ const { visuals, scannedRuns, skippedRuns, isLoading, isError, refetch } =+ useVisualArtifacts();++ /*+ * The selection is held as an ID, not as the object: the list is refetched,+ * and a stored object would pin a stale copy of an artifact whose file has+ * since been rewritten by a re-run.+ */+ const [selectedId, setSelectedId] = useState<string | null>(null);++ /*+ * Another surface asked for something to be put on the stage.+ *+ * The request arrives through the store rather than as a prop, because the+ * asker is never this section's parent — it is the agent strip in a different+ * view, and that view is unmounted by the time this one renders. Each request+ * carries a counter, so the store value is a NEW object even when the target+ * is unchanged; that is what lets "show me the latest" work a second time+ * after the user has clicked around the gallery. See VisualStageRequest.+ */+ const visualStage = useEventStore((s) => s.visualStage);+ useEffect(() => {+ if (visualStage === null) return;+ // "latest" clears the pin instead of naming an id: the gallery is+ // newest-first and refetches, so an id resolved now would go stale as soon+ // as a newer picture lands, while "nothing selected" always falls through+ // to the newest one below.+ setSelectedId(visualStage.target === "latest" ? null : visualStage.target);+ }, [visualStage]);++ const selected = useMemo(() => {+ if (visuals.length === 0) return null;+ return visuals.find((v) => visualId(v) === selectedId) ?? visuals[0];+ }, [visuals, selectedId]);++ // "fit" is a mode, not a factor: it means "as large as the stage allows",+ // which no number can express while the window is resizable.+ const [zoom, setZoom] = useState<number | "fit">("fit");+ const [failed, setFailed] = useState(false);+ const selectedKey = selected ? visualId(selected) : null;+ // A new picture starts fitted and un-failed — carrying a 4× zoom from a+ // thumbnail-sized icon onto a full-page diagram shows a corner of it.+ useEffect(() => {+ setZoom("fit");+ setFailed(false);+ }, [selectedKey]);++ const stepZoom = useCallback((direction: 1 | -1) => {+ setZoom((current) => {+ const from = current === "fit" ? 1 : current;+ const index = ZOOM_STEPS.indexOf(from as (typeof ZOOM_STEPS)[number]);+ // A zoom that came from "fit" may sit between two steps; nearest-step+ // search keeps the buttons predictable in that case.+ const base =+ index >= 0+ ? index+ : ZOOM_STEPS.reduce(+ (best, step, i) =>+ Math.abs(step - from) < Math.abs(ZOOM_STEPS[best] - from) ? i : best,+ 0,+ );+ const next = Math.min(ZOOM_STEPS.length - 1, Math.max(0, base + direction));+ return ZOOM_STEPS[next];+ });+ }, []);++ const onReveal = useCallback(+ async (artifact: VisualArtifact) => {+ try {+ await revealArtifact(artifact.slug, artifact.path);+ } catch {+ pushToast("error", t("visualization.reveal_failed"));+ }+ },+ [pushToast, t],+ );++ const zoomable = selected?.kind === "image" || selected?.kind === "vector";++ return (+ <div className="flex h-full min-h-0 flex-col">+ <ViewHeader+ icon={<Frame className="h-4 w-4 text-primary" aria-hidden />}+ title={t("visualization.title")}+ subtitle={t("visualization.subtitle")}+ right={+ <Button+ variant="outline"+ size="sm"+ onClick={() => refetch()}+ disabled={isLoading}+ data-testid="visualization-refresh"+ >+ {isLoading ? (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />+ ) : (+ <RefreshCw className="mr-1.5 h-3.5 w-3.5" aria-hidden />+ )}+ {t("visualization.refresh")}+ </Button>+ }+ />++ <div className="flex min-h-0 flex-1">+ {/* Gallery rail — every visual found, newest first. */}+ <aside className="flex w-64 shrink-0 flex-col border-r border-border">+ <ScrollArea className="min-h-0 flex-1">+ <ul className="space-y-1 p-2" data-testid="visualization-gallery">+ {visuals.map((artifact) => {+ const id = visualId(artifact);+ return (+ <li key={id}>+ <button+ type="button"+ onClick={() => setSelectedId(id)}+ aria-current={id === selectedKey}+ className={cn(+ "flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-xs transition-colors",+ id === selectedKey+ ? "bg-primary/15 text-foreground"+ : "text-muted-foreground hover:bg-secondary/60 hover:text-foreground",+ )}+ >+ <FileImage className="h-3.5 w-3.5 shrink-0" aria-hidden />+ <span className="min-w-0 flex-1">+ <span className="block truncate font-medium text-foreground">+ {artifact.name}+ </span>+ <span className="block truncate">{runLabel(artifact)}</span>+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ </ScrollArea>+ {/* The scan window, stated rather than hidden: an older picture that+ is not in the list must read as "not looked at", never as gone. */}+ <p className="border-t border-border px-3 py-2 text-[11px] text-muted-foreground">+ {t("visualization.scan_note")+ .replace("{0}", String(scannedRuns || DEFAULT_RUN_SCAN_LIMIT))+ .replace("{1}", String(skippedRuns))}+ </p>+ </aside>++ <section className="flex min-h-0 min-w-0 flex-1 flex-col">+ {selected === null ? (+ <EmptyStage+ loading={isLoading}+ error={isError}+ title={t(isError ? "visualization.error_title" : "visualization.empty_title")}+ body={t(isError ? "visualization.error_body" : "visualization.empty_body")}+ />+ ) : (+ <>+ <div+ className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4"+ data-testid="visualization-stage"+ >+ {failed ? (+ <p className="text-sm text-muted-foreground">+ {t("visualization.render_failed")}+ </p>+ ) : (+ <VisualFrame+ artifact={selected}+ zoom={zoom}+ onError={() => setFailed(true)}+ />+ )}+ </div>++ {/* Caption + actions. One row, because the stage is the point and+ every pixel spent on chrome is a pixel off the picture. */}+ <footer className="flex shrink-0 items-center gap-3 border-t border-border px-4 py-2">+ <div className="min-w-0 flex-1">+ <p className="truncate text-xs font-medium">{selected.path}</p>+ <p className="truncate text-[11px] text-muted-foreground">+ {runLabel(selected)} · {formatSize(selected.size)}+ </p>+ </div>++ {zoomable && (+ <div className="flex shrink-0 items-center gap-1">+ <Button+ variant="ghost"+ size="sm"+ onClick={() => stepZoom(-1)}+ title={t("visualization.zoom_out")}+ aria-label={t("visualization.zoom_out")}+ >+ <ZoomOut className="h-3.5 w-3.5" aria-hidden />+ </Button>+ <span className="w-12 text-center text-[11px] tabular-nums text-muted-foreground">+ {zoom === "fit" ? t("visualization.zoom_fit") : `${Math.round(zoom * 100)}%`}+ </span>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => stepZoom(1)}+ title={t("visualization.zoom_in")}+ aria-label={t("visualization.zoom_in")}+ >+ <ZoomIn className="h-3.5 w-3.5" aria-hidden />+ </Button>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => setZoom("fit")}+ title={t("visualization.zoom_fit")}+ aria-label={t("visualization.zoom_fit")}+ >+ <Maximize2 className="h-3.5 w-3.5" aria-hidden />+ </Button>+ </div>+ )}++ <div className="flex shrink-0 items-center gap-1">+ <Button+ variant="ghost"+ size="sm"+ onClick={() =>+ void openExternalUrl(`${window.location.origin}${selected.url}`)+ }+ title={t("visualization.open_external")}+ >+ <ExternalLink className="mr-1.5 h-3.5 w-3.5" aria-hidden />+ {t("visualization.open_external")}+ </Button>+ <Button variant="ghost" size="sm" asChild>+ <a+ href={artifactDownloadUrl(selected.slug, selected.path)}+ download+ title={t("visualization.download")}+ >+ <Download className="h-3.5 w-3.5" aria-hidden />+ </a>+ </Button>+ {/* Desktop only: a headless host has no file manager to open,+ so the button is absent rather than dead. */}+ {capabilities.data?.native_file_actions && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => void onReveal(selected)}+ title={t("visualization.reveal")}+ >+ <FolderOpen className="h-3.5 w-3.5" aria-hidden />+ </Button>+ )}+ </div>+ </footer>+ </>+ )}+ </section>+ </div>+ </div>+ );+}++/**+ * The picture itself.+ *+ * Raster and vector go through `<img>`, which cannot execute anything even when+ * the SVG carries a script. Pages and PDFs need a document frame, and those are+ * the two cases where the file's own content is being interpreted — the backend+ * already serves both under the no-script CSP (`VIEW_CSP`, outputs_routes.py),+ * and the frame is sandboxed on top so the preview stays inert even if that+ * header is ever loosened.+ */+function VisualFrame({+ artifact,+ zoom,+ onError,+}: {+ artifact: VisualArtifact;+ zoom: number | "fit";+ onError: () => void;+}) {+ const t = useT();+ // Natural width is measured rather than assumed, so a numeric zoom is a real+ // multiple of the file's own pixels and the stage gets scroll extents that+ // match what is drawn. `transform: scale()` would give neither. Height+ // follows from the aspect ratio and is left to the browser.+ const [naturalWidth, setNaturalWidth] = useState<number | null>(null);++ if (artifact.kind === "image" || artifact.kind === "vector") {+ const scaled =+ zoom !== "fit" && naturalWidth !== null+ ? { width: `${naturalWidth * zoom}px`, maxWidth: "none", maxHeight: "none" }+ : undefined;+ return (+ <img+ src={artifact.url}+ alt={artifact.name}+ data-testid="visualization-image"+ onLoad={(event) => setNaturalWidth(event.currentTarget.naturalWidth)}+ onError={onError}+ style={scaled}+ className={cn(+ "rounded-md bg-background/40 shadow-sm",+ zoom === "fit" && "max-h-full max-w-full object-contain",+ )}+ />+ );+ }++ return (+ <div className="flex h-full w-full min-w-0 flex-col gap-2">+ <iframe+ src={artifact.url}+ title={artifact.name}+ data-testid="visualization-frame"+ onError={onError}+ // Empty sandbox = opaque origin, no scripts, no forms, no navigation.+ // A PDF still renders: the browser's own viewer is not the framed+ // document's script context.+ sandbox=""+ className="min-h-0 flex-1 rounded-md border border-border bg-white"+ />+ <p className="flex items-center gap-1.5 text-[11px] text-muted-foreground">+ <ShieldAlert className="h-3 w-3 shrink-0" aria-hidden />+ {t("visualization.sandbox_note")}+ </p>+ </div>+ );+}++function EmptyStage({+ loading,+ error,+ title,+ body,+}: {+ loading: boolean;+ error: boolean;+ title: string;+ body: string;+}) {+ return (+ <div+ className="flex min-h-0 flex-1 flex-col items-center justify-center gap-2 p-8 text-center"+ data-testid="visualization-empty"+ >+ {loading && !error ? (+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />+ ) : (+ <Frame className="h-6 w-6 text-muted-foreground" aria-hidden />+ )}+ <p className="text-sm font-medium">{title}</p>+ <p className="max-w-sm text-xs text-muted-foreground">{body}</p>+ </div>+ );+}diff --git a/tests/unit/ui/test_desktop_detached_windows.py b/tests/unit/ui/test_desktop_detached_windows.pyindex 408d78870a..f8425663a7 100644--- a/tests/unit/ui/test_desktop_detached_windows.py+++ b/tests/unit/ui/test_desktop_detached_windows.py@@ -389,6 +389,61 @@ def test_detachable_views_have_distinct_titles_per_label() -> None:seen[title] = view+def test_visualization_view_detaches_and_reattaches(monkeypatch) -> None:+ """The visual stage is a first-class detachable view.++ It is the section people put on a second monitor — a diagram is something+ you keep looking at WHILE working in the main window — so it must survive+ the whole window lifecycle: its own title, a registry entry, the open/close+ round trip, and the mirrored events that tell every other window about it.+ """+ import sys++ app = _app(monkeypatch)+ created: list[_FakeWindow] = []+ monkeypatch.setitem(sys.modules, "webview", _fake_webview(created))++ opened = app.open_detached_window("visualization")++ assert opened == {"ok": True, "already_open": False, "view": "visualization"}+ assert created[0].title == f"{WINDOW_TITLE} — Visualization"+ assert "?view=visualization&solo=1" in created[0].url+ assert app.detached_views_snapshot() == ["visualization"]+ assert app.published == [("visualization", True)]++ assert app.close_detached_window("visualization") == {+ "ok": True,+ "view": "visualization",+ }+ assert created[0].destroyed is True++ # The window's own X and the reattach route share one deregistration path.+ app._on_detached_closed("visualization")+ assert app.detached_views_snapshot() == []+ assert app.published[-1] == ("visualization", False)+ # Main is still alive, so the process must not arm the quit flag.+ assert app._user_requested_quit is False+++def test_visualization_window_gets_no_broker_token(monkeypatch) -> None:+ """Only the voice surface may run a realtime broker.++ Two live brokers publish competing WebRTC offers, so the token is injected+ into the "chats" window and nowhere else. Pinned per detachable view rather+ than once, because every view added to the registry passes through the same+ injection hook.+ """+ app = _app(monkeypatch)+ window = _FakeWindow()++ app._inject_into_secondary(window, "visualization")++ js = "".join(window.evaluated)+ assert "__JARVIS_EMBEDDED_DESKTOP = true" in js+ assert "__JARVIS_REALTIME_BROKER_TOKEN" not in js+ assert "jarvis-token-ready" in js++# --- routes ------------------------------------------------------------------