Skip to content

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

feat(visualization): draw every run as an n8n-style node graph

rubenluetke10-beep0bf28af6f865
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 5f3a3e2055..de3b2010a1 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -4136,24 +4136,45 @@
},
"visualization": {
"title": "Visualisierung",
- "subtitle": "Die Bilder, Diagramme und Seiten aus deinen Durchläufen",
+ "subtitle": "Jeder Durchlauf als Workflow gezeichnet: was lief, was er tat, was dabei herauskam",
"refresh": "Aktualisieren",
- "scan_note": "Die neuesten {0} Durchläufe durchsucht, {1} ältere nicht.",
+ "runs": "Durchläufe",
+ "run_meta": "{0} Ergebnisdateien",
"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.",
+ "empty_body": "Sobald ein Durchlauf archiviert ist, erscheint er hier als Graph: die Anfrage, jeder Werkzeug-Schritt und die erzeugten Dateien.",
"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.",
+ "legend": "Obere Spur: was der Durchlauf tat, Schritt für Schritt. Untere Spur: die Dateien, die er hinterließ. Klick auf einen Knoten, um ihn zu inspizieren.",
+ "no_steps": "Für diesen Durchlauf sind keine Schritt-Aufzeichnungen erhalten — gezeigt werden Anfrage und Ergebnisdateien.",
+ "steps_dropped": "Langer Durchlauf: {0} weitere Schritte werden nicht gezeichnet.",
+ "node_start": "Anfrage",
+ "node_result": "Ergebnis",
+ "status_done": "Erfolgreich",
+ "status_failed": "Fehlgeschlagen",
+ "status_running": "Läuft",
+ "status_skipped": "Kein bestätigtes Ergebnis",
+ "field_tool": "Werkzeug",
+ "field_detail": "Aufruf",
+ "field_output": "Ausgabe",
+ "field_error": "Fehler",
+ "field_status": "Status",
+ "field_request": "Anfrage",
+ "field_answer": "Antwort",
+ "field_file": "Datei",
+ "field_size": "Größe",
+ "close": "Schließen",
+ "open_map_page": "Als Seite öffnen",
+ "open_map_page_hint": "Öffnet die Missions-Karte dieses Durchlaufs als eigenständige Seite im Browser — teilbar und druckbar.",
"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",
+ "zoom_reset": "Zoom zurücksetzen",
"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.",
- "mission_map": "Missions-Karte"
+ "open_from_agent_hint": "Zeigt als Graph, was die letzten Durchläufe getan und erzeugt haben."
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index bde7f1ebad..a260b8220c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -4136,24 +4136,45 @@
},
"visualization": {
"title": "Visualization",
- "subtitle": "The pictures, diagrams and pages your runs produced",
+ "subtitle": "Every run drawn as a workflow: what ran, what it did, what came out",
"refresh": "Refresh",
- "scan_note": "Newest {0} runs scanned, {1} older ones not.",
+ "runs": "Runs",
+ "run_meta": "{0} deliverables",
"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.",
+ "empty_body": "As soon as a run has been archived it appears here as a graph: the request, every tool step, and the files it produced.",
"error_title": "The run archive could not be read",
"error_body": "The list of runs is unavailable right now. Try again in a moment.",
+ "legend": "Top track: what the run did, step by step. Bottom track: the files it left behind. Click a node to inspect it.",
+ "no_steps": "No step records survived for this run — showing its request and deliverables.",
+ "steps_dropped": "Long run: {0} further steps are not drawn.",
+ "node_start": "Request",
+ "node_result": "Result",
+ "status_done": "Succeeded",
+ "status_failed": "Failed",
+ "status_running": "Running",
+ "status_skipped": "No confirmed result",
+ "field_tool": "Tool",
+ "field_detail": "Call",
+ "field_output": "Output",
+ "field_error": "Error",
+ "field_status": "Status",
+ "field_request": "Request",
+ "field_answer": "Answer",
+ "field_file": "File",
+ "field_size": "Size",
+ "close": "Close",
+ "open_map_page": "Open as page",
+ "open_map_page_hint": "Open this run's mission map as a standalone page in the browser — shareable and printable.",
"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",
+ "zoom_reset": "Reset zoom",
"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.",
- "mission_map": "Mission map"
+ "open_from_agent_hint": "Show what the latest runs did and produced, as a graph."
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 38b4a7063a..63c63af77c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -4136,24 +4136,45 @@
},
"visualization": {
"title": "Visualización",
- "subtitle": "Las imágenes, los diagramas y las páginas que produjeron tus ejecuciones",
+ "subtitle": "Cada ejecución dibujada como un flujo: qué corrió, qué hizo y qué produjo",
"refresh": "Actualizar",
- "scan_note": "Se revisaron las {0} ejecuciones más recientes; {1} más antiguas, no.",
+ "runs": "Ejecuciones",
+ "run_meta": "{0} archivos producidos",
"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.",
+ "empty_body": "En cuanto una ejecución quede archivada aparecerá aquí como un grafo: la petición, cada paso de herramienta y los archivos que produjo.",
"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.",
+ "legend": "Pista superior: lo que hizo la ejecución, paso a paso. Pista inferior: los archivos que dejó. Haz clic en un nodo para inspeccionarlo.",
+ "no_steps": "No se conservan registros de pasos de esta ejecución — se muestran su petición y sus archivos.",
+ "steps_dropped": "Ejecución larga: {0} pasos más no se dibujan.",
+ "node_start": "Petición",
+ "node_result": "Resultado",
+ "status_done": "Correcto",
+ "status_failed": "Fallido",
+ "status_running": "En curso",
+ "status_skipped": "Sin resultado confirmado",
+ "field_tool": "Herramienta",
+ "field_detail": "Llamada",
+ "field_output": "Salida",
+ "field_error": "Error",
+ "field_status": "Estado",
+ "field_request": "Petición",
+ "field_answer": "Respuesta",
+ "field_file": "Archivo",
+ "field_size": "Tamaño",
+ "close": "Cerrar",
+ "open_map_page": "Abrir como página",
+ "open_map_page_hint": "Abre el mapa de esta ejecución como página independiente en el navegador — se puede compartir e imprimir.",
"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",
+ "zoom_reset": "Restablecer zoom",
"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.",
- "mission_map": "Mapa de la misión"
+ "open_from_agent_hint": "Muestra como grafo lo que hicieron y produjeron las últimas ejecuciones."
}
}
diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx
index b3a8a9d9f5..552c9008a2 100644
--- a/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx
@@ -1,13 +1,16 @@
/**
- * The Visualization section — what it selects, what it shows, what it admits.
+ * The Visualization section — the run graph it draws, what it admits, and
+ * what a node click reveals.
*
- * 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.
+ * Contracts worth pinning:
+ * - a run renders as connected nodes (request → steps → result, deliverables
+ * on their own track), never as a flat file list,
+ * - a pre-feature archive with no step records still gets a graph (request +
+ * deliverables) and SAYS that the steps are missing,
+ * - clicking a node opens the inspector; an image deliverable previews via
+ * `<img>`, a page via an inert sandboxed frame,
+ * - the server-rendered mission map stays one click away ("open as page"),
+ * - only files the WebView can draw are offered a preview (`classifyVisual`).
*/
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
@@ -16,7 +19,11 @@ 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";
+import type {
+ ArtifactSummary,
+ OutputSummary,
+ PlanResponse,
+} 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).
@@ -33,6 +40,7 @@ afterEach(() => {
function installFetchMock(
runs: OutputSummary[],
artifactsBySlug: Record<string, ArtifactSummary[]>,
+ plansBySlug: Record<string, PlanResponse> = {},
) {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
@@ -43,6 +51,15 @@ function installFetchMock(
json: async () => ({ native_file_actions: false, platform: "linux" }),
};
}
+ const plan = /\/api\/outputs\/([^/]+)\/plan/.exec(url);
+ if (plan) {
+ const slug = decodeURIComponent(plan[1]);
+ return {
+ ok: true,
+ status: 200,
+ json: async () => plansBySlug[slug] ?? { plan: null, steps: [] },
+ };
+ }
const artifacts = /\/api\/outputs\/([^/]+)\/artifacts/.exec(url);
if (artifacts) {
const slug = decodeURIComponent(artifacts[1]);
@@ -83,6 +100,27 @@ function file(path: string, over: Partial<ArtifactSummary> = {}): ArtifactSummar
};
}
+const CHART_PLAN: PlanResponse = {
+ plan: { plan_id: "run-new", vision: "Draw the architecture", status: "complete" },
+ steps: [
+ {
+ step_id: "t1:0",
+ name: "python plot.py",
+ tool_name: "Bash",
+ status: "done",
+ output: "wrote diagram.svg",
+ },
+ {
+ step_id: "t1:1",
+ name: "out/diagram.svg",
+ tool_name: "Write",
+ status: "done",
+ writes: ["out/diagram.svg"],
+ },
+ ],
+ final_answer: "Architecture drawn.",
+};
+
describe("classifyVisual", () => {
it("accepts what the WebView can draw", () => {
expect(classifyVisual("chart.png")).toBe("image");
@@ -93,8 +131,8 @@ describe("classifyVisual", () => {
});
it("rejects everything else, however data-shaped", () => {
- // These are real deliverables — they simply belong in Outputs, not on a
- // stage that promises a picture.
+ // These are real deliverables — they get a node and file actions, just no
+ // rendered preview the WebView could only coin-flip on.
for (const name of ["run.log", "data.csv", "notes.md", "result.json", "app.py"]) {
expect(classifyVisual(name)).toBeNull();
}
@@ -107,67 +145,69 @@ describe("classifyVisual", () => {
});
describe("VisualizationView", () => {
- it("lists the visual artifacts plus one mission map per run, map staged first", async () => {
+ it("draws the newest run as request → steps → result plus deliverables", 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 })],
- },
+ [{ slug: "run-new", utterance: "Draw the architecture", status: "success" }],
+ { "run-new": [file("tasks/t1/artifacts/files/out/diagram.svg")] },
+ { "run-new": CHART_PLAN },
);
renderView();
- const gallery = await screen.findByTestId("visualization-gallery");
- // Two visuals + one mission map per scanned run.
- await waitFor(() => expect(gallery.querySelectorAll("li")).toHaveLength(4));
- // The .log is a deliverable, but not a picture.
- expect(screen.queryByText("build.log")).toBeNull();
+ await screen.findByTestId("graph-node-start");
+ await waitFor(() =>
+ expect(screen.getAllByTestId("graph-node-step")).toHaveLength(2),
+ );
+ expect(screen.getByTestId("graph-node-result")).toBeTruthy();
+ expect(screen.getAllByTestId("graph-node-artifact")).toHaveLength(1);
+ // The graph replaced the gallery: no flat file list anywhere.
+ expect(screen.queryByTestId("visualization-gallery")).toBeNull();
+ });
- // The newest run's mission map leads and is staged without a click — the
- // overview of what ran comes before its individual pictures.
- const frame = await screen.findByTestId("visualization-frame");
- expect(frame.getAttribute("src")).toContain("/api/outputs/run-new/graph");
+ it("still graphs a pre-feature archive and admits the steps are gone", async () => {
+ installFetchMock(
+ [{ slug: "run-old", utterance: "Summarise the logs", status: "unknown" }],
+ { "run-old": [file("tasks/t1/artifacts/files/old-chart.png")] },
+ // No plan entry -> the endpoint's stub contract {plan: null, steps: []}.
+ );
- // Its pictures are one click away.
- fireEvent.click(screen.getByText("diagram.svg"));
- const image = await screen.findByTestId("visualization-image");
- expect(image.getAttribute("src")).toContain("diagram.svg");
+ renderView();
+
+ await screen.findByTestId("graph-node-start");
+ await waitFor(() =>
+ expect(screen.getAllByTestId("graph-node-artifact")).toHaveLength(1),
+ );
+ expect(screen.queryAllByTestId("graph-node-step")).toHaveLength(0);
+ // The honesty line: missing step records are stated, not glossed over.
+ await screen.findByText(/No step records survived/);
});
- 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 }),
- ],
- });
+ it("opens the inspector with an image preview when a deliverable is clicked", async () => {
+ installFetchMock(
+ [{ slug: "run-new", utterance: "Draw the architecture", status: "success" }],
+ { "run-new": [file("tasks/t1/artifacts/files/out/diagram.svg")] },
+ { "run-new": CHART_PLAN },
+ );
renderView();
- const second = await screen.findByText("second.png");
- fireEvent.click(second);
+ fireEvent.click(await screen.findByTestId("graph-node-artifact"));
- await waitFor(() =>
- expect(
- screen.getByTestId("visualization-image").getAttribute("src"),
- ).toContain("second.png"),
- );
+ await screen.findByTestId("visualization-inspector");
+ const image = await screen.findByTestId("visualization-image");
+ expect(image.getAttribute("src")).toContain("diagram.svg");
});
- 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")],
- });
+ it("frames a page deliverable inertly rather than drawing it as an image", async () => {
+ installFetchMock(
+ [{ slug: "run-1", utterance: "Build a report", status: "success" }],
+ { "run-1": [file("tasks/t1/artifacts/files/report.html")] },
+ );
renderView();
+ fireEvent.click(await screen.findByTestId("graph-node-artifact"));
+
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.
@@ -175,20 +215,33 @@ describe("VisualizationView", () => {
expect(screen.queryByTestId("visualization-image")).toBeNull();
});
- it("still offers the mission map when a run produced nothing visual", async () => {
- // A text-only run is exactly when "what happened" needs drawing the most:
- // the map is the run's one visual, and file actions (download/reveal) are
- // absent because a server-rendered page is not an archived file.
- installFetchMock([{ slug: "run-1", utterance: "tidy the notes" }], {
- "run-1": [file("notes.md", { is_text: true })],
- });
+ it("shows a step's real call and output in the inspector", async () => {
+ installFetchMock(
+ [{ slug: "run-new", utterance: "Draw the architecture", status: "success" }],
+ { "run-new": [] },
+ { "run-new": CHART_PLAN },
+ );
renderView();
- const frame = await screen.findByTestId("visualization-frame");
- expect(frame.getAttribute("src")).toContain("/api/outputs/run-1/graph");
- expect(screen.queryByText("notes.md")).toBeNull();
- expect(screen.queryByTitle("Save a copy")).toBeNull();
+ fireEvent.click((await screen.findAllByTestId("graph-node-step"))[0]);
+
+ const inspector = await screen.findByTestId("visualization-inspector");
+ expect(inspector.textContent).toContain("python plot.py");
+ expect(inspector.textContent).toContain("wrote diagram.svg");
+ });
+
+ it("keeps the server-rendered mission map one click away", async () => {
+ installFetchMock(
+ [{ slug: "run-new", utterance: "Draw the architecture", status: "success" }],
+ { "run-new": [] },
+ { "run-new": CHART_PLAN },
+ );
+
+ renderView();
+
+ // The no-JS sibling of this canvas — shareable, printable, CSP-inert.
+ await screen.findByTestId("visualization-open-map");
});
it("says so when there are no runs at all", async () => {
@@ -197,7 +250,7 @@ describe("VisualizationView", () => {
renderView();
await screen.findByTestId("visualization-empty");
- expect(screen.queryByTestId("visualization-stage")).toBeNull();
+ expect(screen.queryByTestId("visualization-canvas")).toBeNull();
});
});
diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.tsx
index 1fa8d6e5ba..3d4656b5b8 100644
--- a/jarvis/ui/web/frontend/src/views/VisualizationView.tsx
+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.tsx
@@ -2,16 +2,28 @@ import { useCallback, useEffect, useMemo, useState } from "react";
import {
Download,
ExternalLink,
+ FileCode,
FileImage,
+ FileText,
+ Flag,
FolderOpen,
Frame,
+ Globe,
Loader2,
Maximize2,
+ MessageSquare,
+ Plug,
RefreshCw,
+ Search,
ShieldAlert,
+ SquarePen,
+ Terminal,
Workflow,
+ Wrench,
+ X,
ZoomIn,
ZoomOut,
+ type LucideIcon,
} from "lucide-react";
import { Button } from "@/components/ui/button";
@@ -24,35 +36,102 @@ import { openExternalUrl } from "@/lib/openExternal";
import {
artifactDownloadUrl,
revealArtifact,
+ useArtifactsForOutput,
useOutputsCapabilities,
+ useOutputsList,
+ usePlanForOutput,
+ type ArtifactSummary,
+ type OutputStatus,
+ type OutputSummary,
} from "@/hooks/useOutputs";
import {
- DEFAULT_RUN_SCAN_LIMIT,
+ classifyVisual,
+ missionMapUrl,
+ MISSION_MAP_PATH,
useVisualArtifacts,
- visualId,
- type VisualArtifact,
+ visualUrl,
+ type VisualKind,
} from "@/hooks/useVisualArtifacts";
+import {
+ buildRunGraph,
+ edgePath,
+ NODE_H,
+ NODE_W,
+ type RunGraph,
+ type RunGraphNode,
+} from "@/lib/runGraph";
/**
- * The Visualization section — everything a run DREW, at full size.
+ * The Visualization section — a run drawn as a workflow, not listed as files.
+ *
+ * Every archived run is presented the way a workflow editor would draw it:
+ * the request as the start node, one node per tool call the worker actually
+ * made (with its real success/failure, reconstructed from the archived
+ * transcript by `/api/outputs/{slug}/plan`), the final answer, and the
+ * deliverables on a second track connected to the steps that wrote them.
+ * One glance answers "what did this run do" — the question a flat
+ * newest-first file gallery could never answer.
*
- * 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 still owns no data: runs come from `/api/outputs`, steps from the plan
+ * endpoint, deliverables from the artifact listing. A run archived before
+ * this feature existed — or whose stream never survived — degrades to
+ * start → deliverables, so the archive needs no migration.
*
- * 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.
+ * The server-rendered mission map (`/api/outputs/{slug}/graph`, see
+ * `mission_graph.py`) is this graph's no-JS sibling: same story, baked into
+ * a static page under the strict no-script CSP. It stays one click away
+ * ("open as page") because a page can be shared, printed and opened in a
+ * real browser tab — things a canvas inside the app cannot do.
*
- * 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.
+ * Detachable (`DETACHABLE_VIEWS` in jarvis/ui/desktop_app.py): a run graph is
+ * the thing people put on a second monitor while the mission is still going.
*/
-const ZOOM_STEPS = [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4] as const;
+const ZOOM_STEPS = [0.5, 0.65, 0.8, 1, 1.25, 1.5] as const;
+
+/** Same status colour language as the Outputs cards — one vocabulary. */
+const RUN_DOT: Record<OutputStatus, string> = {
+ success: "bg-emerald-400",
+ error: "bg-destructive",
+ running: "bg-primary animate-pulse",
+ cancelled: "bg-amber-400",
+ unknown: "bg-muted-foreground/50",
+};
+
+const NODE_DOT: Record<string, string> = {
+ done: "bg-emerald-400",
+ failed: "bg-destructive",
+ running: "bg-primary animate-pulse",
+ skipped: "bg-muted-foreground/40",
+};
+
+/** The glyph a step node wears — recognisable tools get their own. */
+function toolIcon(toolName: string | null | undefined): LucideIcon {
+ const name = (toolName ?? "").toLowerCase();
+ if (name.startsWith("mcp__") || name.includes("/")) return Plug;
+ if (["bash", "runcommand", "shell", "exec", "execute", "run_command", "run_shell_command"].includes(name))
+ return Terminal;
+ if (["write", "edit", "multiedit", "notebookedit", "file_write", "write_file", "create_file"].includes(name))
+ return SquarePen;
+ if (["read", "glob"].includes(name)) return FileText;
+ if (name === "grep" || name === "search") return Search;
+ if (name.includes("web") || name.includes("fetch")) return Globe;
+ return Wrench;
+}
+
+function artifactIcon(path: string): LucideIcon {
+ const kind = classifyVisual(path);
+ if (kind === "image" || kind === "vector") return FileImage;
+ if (kind === "page" || kind === "document") return FileCode;
+ return FileText;
+}
+
+function nodeIcon(node: RunGraphNode): LucideIcon {
+ if (node.kind === "start") return MessageSquare;
+ if (node.kind === "result") return Flag;
+ if (node.kind === "artifact") return artifactIcon(node.artifact?.path ?? "");
+ return toolIcon(node.step?.tool_name);
+}
/** Human file size, rounded the way a caption wants it. */
function formatSize(bytes: number): string {
@@ -61,93 +140,102 @@ function formatSize(bytes: number): string {
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();
+ const outputs = useOutputsList();
+ const runs = useMemo(() => outputs.data ?? [], [outputs.data]);
+
+ const [selectedSlug, setSelectedSlug] = useState<string | null>(null);
+ const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
/*
- * 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.
+ * The newest run is the default subject — the graph the user most likely
+ * came for. It is a fallback, not state: a refetch that reorders the list
+ * must never fight an explicit click.
*/
- const [selectedId, setSelectedId] = useState<string | null>(null);
+ const run: OutputSummary | null = useMemo(() => {
+ if (runs.length === 0) return null;
+ return runs.find((r) => r.slug === selectedSlug) ?? runs[0];
+ }, [runs, selectedSlug]);
+
+ const plan = usePlanForOutput(run?.slug ?? null);
+ const artifacts = useArtifactsForOutput(run?.slug ?? null);
/*
- * Another surface asked for something to be put on the stage.
+ * Another surface asked for something to be staged.
*
* 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.
+ * asker is never this section's parent — it is the agent strip in a
+ * different view, unmounted by the time this one renders. A target names a
+ * `visualId` (slug::path) or "latest"; both resolve to a run plus, for a
+ * real file, its artifact node. The mission-map pseudo-artifact resolves to
+ * the run alone — this canvas IS the map. See VisualStageRequest.
*/
const visualStage = useEventStore((s) => s.visualStage);
+ const { visuals } = useVisualArtifacts();
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.
+ if (visualStage.target === "latest") {
+ const newest = visuals[0];
+ if (newest) {
+ setSelectedSlug(newest.slug);
+ setSelectedNodeId(
+ newest.path === MISSION_MAP_PATH ? null : `artifact:${newest.path}`,
+ );
+ }
+ return;
+ }
+ const separator = visualStage.target.indexOf("::");
+ if (separator > 0) {
+ const path = visualStage.target.slice(separator + 2);
+ setSelectedSlug(visualStage.target.slice(0, separator));
+ setSelectedNodeId(path === MISSION_MAP_PATH ? null : `artifact:${path}`);
+ }
+ }, [visualStage, visuals]);
+
+ const graph: RunGraph | null = useMemo(() => {
+ if (run === null) return null;
+ return buildRunGraph({
+ slug: run.slug,
+ utterance: run.utterance,
+ runStatus: run.status,
+ plan: plan.data,
+ files: artifacts.data?.files ?? [],
+ });
+ }, [run, plan.data, artifacts.data]);
+
+ /* A node pinned from another run's graph must not linger as a selection
+ * that matches nothing — clear it once the new graph is known. */
useEffect(() => {
- setZoom("fit");
- setFailed(false);
- }, [selectedKey]);
+ setSelectedNodeId((current) =>
+ current === null || graph?.nodes.some((n) => n.id === current)
+ ? current
+ : null,
+ );
+ }, [graph]);
+ const selectedNode = useMemo(() => {
+ if (graph === null) return null;
+ return graph.nodes.find((n) => n.id === selectedNodeId) ?? null;
+ }, [graph, selectedNodeId]);
+
+ const [zoom, setZoom] = useState<number>(1);
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 index = ZOOM_STEPS.findIndex((s) => Math.abs(s - current) < 0.001);
+ const base = index >= 0 ? index : ZOOM_STEPS.indexOf(1);
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 refetch = useCallback(() => {
+ void outputs.refetch();
+ void plan.refetch();
+ void artifacts.refetch();
+ }, [outputs, plan, artifacts]);
- const zoomable = selected?.kind === "image" || selected?.kind === "vector";
+ const loading = outputs.isLoading || plan.isLoading || artifacts.isLoading;
return (
<div className="flex h-full min-h-0 flex-col">
@@ -156,254 +244,540 @@ export function VisualizationView() {
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 />
+ <div className="flex items-center gap-1.5">
+ {run !== null && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ void openExternalUrl(
+ `${window.location.origin}${missionMapUrl(run.slug)}`,
+ )
+ }
+ title={t("visualization.open_map_page_hint")}
+ data-testid="visualization-open-map"
+ >
+ <Workflow className="mr-1.5 h-3.5 w-3.5" aria-hidden />
+ {t("visualization.open_map_page")}
+ </Button>
)}
- {t("visualization.refresh")}
- </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={refetch}
+ disabled={loading}
+ data-testid="visualization-refresh"
+ >
+ {loading ? (
+ <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>
}
/>
<div className="flex min-h-0 flex-1">
- {/* Gallery rail — every visual found, newest first. */}
+ {/* Run rail — every archived run, newest first. */}
<aside className="flex w-64 shrink-0 flex-col border-r border-border">
+ <p className="border-b border-border px-3 py-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
+ {t("visualization.runs")}
+ </p>
<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);
- const isMap = artifact.kind === "map";
- return (
- <li key={id}>
- <button
- type="button"
- onClick={() => setSelectedId(id)}
- aria-current={id === selectedKey}
+ <ul className="space-y-1 p-2" data-testid="visualization-runs">
+ {runs.map((entry) => (
+ <li key={entry.slug}>
+ <button
+ type="button"
+ onClick={() => {
+ setSelectedSlug(entry.slug);
+ setSelectedNodeId(null);
+ }}
+ aria-current={entry.slug === run?.slug}
+ className={cn(
+ "flex w-full items-start gap-2 rounded-md px-2 py-2 text-left text-xs transition-colors",
+ entry.slug === run?.slug
+ ? "bg-primary/15 text-foreground"
+ : "text-muted-foreground hover:bg-secondary/60 hover:text-foreground",
+ )}
+ >
+ <span
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",
- )}
- >
- {isMap ? (
- <Workflow className="h-3.5 w-3.5 shrink-0 text-primary" aria-hidden />
- ) : (
- <FileImage className="h-3.5 w-3.5 shrink-0" aria-hidden />
+ "mt-1 h-1.5 w-1.5 shrink-0 rounded-full",
+ RUN_DOT[entry.status ?? "unknown"],
)}
- <span className="min-w-0 flex-1">
- <span className="block truncate font-medium text-foreground">
- {isMap ? t("visualization.mission_map") : artifact.name}
- </span>
- <span className="block truncate">{runLabel(artifact)}</span>
+ aria-hidden
+ />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate font-medium text-foreground">
+ {entry.utterance?.trim() || entry.slug}
</span>
- </button>
- </li>
- );
- })}
+ <span className="block truncate">
+ {t("visualization.run_meta").replace(
+ "{0}",
+ String(entry.artifact_count ?? 0),
+ )}
+ </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>
+ {/* Canvas — the selected run as connected nodes along tracks. */}
<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")}
+ {graph === null ? (
+ <EmptyCanvas
+ loading={outputs.isLoading}
+ error={outputs.isError}
+ title={t(
+ outputs.isError
+ ? "visualization.error_title"
+ : "visualization.empty_title",
+ )}
+ body={t(
+ outputs.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"
+ className="min-h-0 flex-1 overflow-auto"
+ data-testid="visualization-canvas"
>
- {failed ? (
- <p className="text-sm text-muted-foreground">
- {t("visualization.render_failed")}
- </p>
- ) : (
- <VisualFrame
- artifact={selected}
- zoom={zoom}
- onError={() => setFailed(true)}
- />
- )}
+ <GraphCanvas
+ graph={graph}
+ zoom={zoom}
+ selectedId={selectedNodeId}
+ onSelect={setSelectedNodeId}
+ />
</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.kind === "map"
- ? t("visualization.mission_map")
- : selected.path}
- </p>
- <p className="truncate text-[11px] text-muted-foreground">
- {selected.kind === "map"
- ? runLabel(selected)
- : `${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>
- )}
-
+ {/* The honesty line: what this graph could and could not read. */}
+ <p className="min-w-0 flex-1 truncate text-[11px] text-muted-foreground">
+ {plan.data && plan.data.plan === null
+ ? t("visualization.no_steps")
+ : graph.droppedSteps > 0
+ ? t("visualization.steps_dropped").replace(
+ "{0}",
+ String(graph.droppedSteps),
+ )
+ : t("visualization.legend")}
+ </p>
<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")}
+ onClick={() => stepZoom(-1)}
+ title={t("visualization.zoom_out")}
+ aria-label={t("visualization.zoom_out")}
>
- <ExternalLink className="mr-1.5 h-3.5 w-3.5" aria-hidden />
- {t("visualization.open_external")}
+ <ZoomOut className="h-3.5 w-3.5" aria-hidden />
+ </Button>
+ <span className="w-12 text-center text-[11px] tabular-nums text-muted-foreground">
+ {`${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(1)}
+ title={t("visualization.zoom_reset")}
+ aria-label={t("visualization.zoom_reset")}
+ >
+ <Maximize2 className="h-3.5 w-3.5" aria-hidden />
</Button>
- {/* The mission map is a server-rendered page, not an archived
- file — there is nothing to download or reveal. */}
- {selected.kind !== "map" && (
- <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. */}
- {selected.kind !== "map" && 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>
+
+ {/* Inspector — what one node did, or what one deliverable looks like. */}
+ {selectedNode !== null && run !== null && (
+ <NodeInspector
+ node={selectedNode}
+ slug={run.slug}
+ onClose={() => setSelectedNodeId(null)}
+ />
+ )}
</div>
</div>
);
}
+/* ------------------------------------------------------------------------- */
+
+function GraphCanvas({
+ graph,
+ zoom,
+ selectedId,
+ onSelect,
+}: {
+ graph: RunGraph;
+ zoom: number;
+ selectedId: string | null;
+ onSelect: (id: string) => void;
+}) {
+ const t = useT();
+ const byId = useMemo(() => new Map(graph.nodes.map((n) => [n.id, n])), [graph]);
+
+ return (
+ <div
+ style={{ width: graph.width * zoom, height: graph.height * zoom }}
+ className="relative min-h-full min-w-full"
+ >
+ <div
+ style={{
+ width: graph.width,
+ height: graph.height,
+ transform: `scale(${zoom})`,
+ transformOrigin: "top left",
+ }}
+ className="relative"
+ >
+ {/* Edge layer under the nodes. Colours come from the theme tokens, so
+ the tracks are signal-yellow on matte black in the dark theme and
+ legible gold on paper in the light one — never a hardcoded hex. */}
+ <svg
+ width={graph.width}
+ height={graph.height}
+ className="absolute inset-0"
+ aria-hidden
+ >
+ {graph.edges.map((edge) => {
+ const from = byId.get(edge.from);
+ const to = byId.get(edge.to);
+ if (!from || !to) return null;
+ return (
+ <path
+ key={edge.id}
+ d={edgePath(from, to)}
+ fill="none"
+ strokeWidth={1.5}
+ className={
+ edge.failed ? "stroke-destructive/70" : "stroke-primary/50"
+ }
+ />
+ );
+ })}
+ </svg>
+
+ {graph.nodes.map((node) => {
+ const Icon = nodeIcon(node);
+ const selected = node.id === selectedId;
+ const title =
+ node.kind === "start"
+ ? t("visualization.node_start")
+ : node.kind === "result"
+ ? t("visualization.node_result")
+ : node.title;
+ const subtitle = node.kind === "start" ? node.title : node.subtitle;
+ return (
+ <button
+ key={node.id}
+ type="button"
+ onClick={() => onSelect(node.id)}
+ aria-current={selected}
+ data-testid={`graph-node-${node.kind}`}
+ style={{ left: node.x, top: node.y, width: NODE_W, height: NODE_H }}
+ className={cn(
+ "absolute flex items-center gap-2.5 rounded-xl border bg-card px-3 text-left shadow-sm transition-colors",
+ selected
+ ? "border-primary ring-1 ring-primary/40"
+ : "border-border hover:border-primary/50",
+ )}
+ >
+ {/* Ports — the connectors that make cards read as graph nodes. */}
+ <span
+ className="absolute -left-[3px] top-1/2 h-1.5 w-1.5 -translate-y-1/2 rounded-full bg-primary/60"
+ aria-hidden
+ />
+ <span
+ className="absolute -right-[3px] top-1/2 h-1.5 w-1.5 -translate-y-1/2 rounded-full bg-primary/60"
+ aria-hidden
+ />
+ <span
+ className={cn(
+ "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",
+ node.kind === "artifact"
+ ? "bg-secondary text-foreground"
+ : "bg-primary/15 text-primary",
+ )}
+ >
+ <Icon className="h-4 w-4" aria-hidden />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-xs font-medium text-foreground">
+ {title}
+ </span>
+ {subtitle && (
+ <span className="block truncate text-[11px] text-muted-foreground">
+ {subtitle}
+ </span>
+ )}
+ </span>
+ {node.status !== "none" && (
+ <span
+ className={cn(
+ "h-1.5 w-1.5 shrink-0 rounded-full",
+ NODE_DOT[node.status],
+ )}
+ title={t(`visualization.status_${node.status}`)}
+ />
+ )}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+/* ------------------------------------------------------------------------- */
+
+function NodeInspector({
+ node,
+ slug,
+ onClose,
+}: {
+ node: RunGraphNode;
+ slug: string;
+ onClose: () => void;
+}) {
+ const t = useT();
+ const pushToast = useEventStore((s) => s.pushToast);
+ const capabilities = useOutputsCapabilities();
+
+ const artifact = node.kind === "artifact" ? (node.artifact ?? null) : null;
+ const visualKind = artifact ? classifyVisual(artifact.path) : null;
+
+ const onReveal = useCallback(async () => {
+ if (!artifact) return;
+ try {
+ await revealArtifact(slug, artifact.path);
+ } catch {
+ pushToast("error", t("visualization.reveal_failed"));
+ }
+ }, [artifact, slug, pushToast, t]);
+
+ return (
+ <aside
+ className="flex w-96 shrink-0 flex-col border-l border-border"
+ data-testid="visualization-inspector"
+ >
+ <div className="flex items-center gap-2 border-b border-border px-3 py-2">
+ <p className="min-w-0 flex-1 truncate text-xs font-medium">
+ {node.kind === "start"
+ ? t("visualization.node_start")
+ : node.kind === "result"
+ ? t("visualization.node_result")
+ : node.title}
+ </p>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={onClose}
+ title={t("visualization.close")}
+ aria-label={t("visualization.close")}
+ >
+ <X className="h-3.5 w-3.5" aria-hidden />
+ </Button>
+ </div>
+
+ <ScrollArea className="min-h-0 flex-1">
+ <div className="space-y-3 p-3">
+ {node.kind === "step" && node.step && (
+ <>
+ <InspectorField label={t("visualization.field_tool")}>
+ {node.step.tool_name ?? "—"}
+ </InspectorField>
+ <InspectorField label={t("visualization.field_detail")}>
+ <code className="block whitespace-pre-wrap break-words text-[11px]">
+ {node.step.name}
+ </code>
+ </InspectorField>
+ {node.step.output && (
+ <InspectorField label={t("visualization.field_output")}>
+ <code className="block whitespace-pre-wrap break-words text-[11px] text-muted-foreground">
+ {node.step.output}
+ </code>
+ </InspectorField>
+ )}
+ {node.step.error && (
+ <InspectorField label={t("visualization.field_error")}>
+ <code className="block whitespace-pre-wrap break-words text-[11px] text-destructive">
+ {node.step.error}
+ </code>
+ </InspectorField>
+ )}
+ <InspectorField label={t("visualization.field_status")}>
+ {t(`visualization.status_${node.status}`)}
+ </InspectorField>
+ </>
+ )}
+
+ {(node.kind === "start" || node.kind === "result") && (
+ <InspectorField
+ label={
+ node.kind === "start"
+ ? t("visualization.field_request")
+ : t("visualization.field_answer")
+ }
+ >
+ <p className="whitespace-pre-wrap break-words text-xs">
+ {(node.kind === "start" ? node.title : node.subtitle) || "—"}
+ </p>
+ </InspectorField>
+ )}
+
+ {artifact && (
+ <>
+ {visualKind !== null && (
+ <ArtifactPreview slug={slug} artifact={artifact} kind={visualKind} />
+ )}
+ <InspectorField label={t("visualization.field_file")}>
+ <code className="block break-words text-[11px]">
+ {artifact.path}
+ </code>
+ </InspectorField>
+ <InspectorField label={t("visualization.field_size")}>
+ {formatSize(artifact.size)}
+ </InspectorField>
+ <div className="flex flex-wrap items-center gap-1 pt-1">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() =>
+ void openExternalUrl(
+ `${window.location.origin}${visualUrl(slug, artifact.path)}`,
+ )
+ }
+ 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(slug, artifact.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()}
+ title={t("visualization.reveal")}
+ >
+ <FolderOpen className="h-3.5 w-3.5" aria-hidden />
+ </Button>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+ </ScrollArea>
+ </aside>
+ );
+}
+
+function InspectorField({
+ label,
+ children,
+}: {
+ label: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div>
+ <p className="mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
+ {label}
+ </p>
+ <div className="text-xs">{children}</div>
+ </div>
+ );
+}
+
/**
- * The picture itself.
+ * The deliverable preview inside the inspector.
*
- * 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.
+ * 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({
+function ArtifactPreview({
+ slug,
artifact,
- zoom,
- onError,
+ kind,
}: {
- artifact: VisualArtifact;
- zoom: number | "fit";
- onError: () => void;
+ slug: string;
+ artifact: ArtifactSummary;
+ kind: VisualKind;
}) {
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;
+ const [failed, setFailed] = useState(false);
+ const url = visualUrl(slug, artifact.path);
+
+ // A new file must not inherit the previous file's failure verdict.
+ useEffect(() => setFailed(false), [url]);
+
+ if (failed) {
+ return (
+ <p className="text-xs text-muted-foreground">
+ {t("visualization.render_failed")}
+ </p>
+ );
+ }
+
+ if (kind === "image" || kind === "vector") {
return (
<img
- src={artifact.url}
- alt={artifact.name}
+ src={url}
+ alt={artifact.path}
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",
- )}
+ onError={() => setFailed(true)}
+ className="max-h-72 w-full rounded-md border border-border bg-background/40 object-contain"
/>
);
}
return (
- <div className="flex h-full w-full min-w-0 flex-col gap-2">
+ <div className="space-y-1.5">
<iframe
- src={artifact.url}
- title={artifact.name}
+ src={url}
+ title={artifact.path}
data-testid="visualization-frame"
- onError={onError}
+ onError={() => setFailed(true)}
// 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"
+ className="h-72 w-full 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 />
@@ -413,7 +787,9 @@ function VisualFrame({
);
}
-function EmptyStage({
+/* ------------------------------------------------------------------------- */
+
+function EmptyCanvas({
loading,
error,
title,
@@ -430,7 +806,10 @@ function EmptyStage({
data-testid="visualization-empty"
>
{loading && !error ? (
- <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
+ <Loader2
+ className="h-5 w-5 animate-spin text-muted-foreground"
+ aria-hidden
+ />
) : (
<Frame className="h-6 w-6 text-muted-foreground" aria-hidden />
)}