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(outputs): serve a mission as an n8n-style node-graph page
rubenluetke10-beep7359e57ff0fe
diff --git a/jarvis/cli_ctl/commands/outputs.py b/jarvis/cli_ctl/commands/outputs.pyindex e09f4c3662..9649c01610 100644--- a/jarvis/cli_ctl/commands/outputs.py+++ b/jarvis/cli_ctl/commands/outputs.py@@ -27,6 +27,15 @@ def files(slug: str = typer.Argument(...)) -> None:invoke.run("GET", f"/api/outputs/{slug}/artifacts")+def graph(slug: str = typer.Argument(...)) -> None:+ """Print a session's mission-map page (self-contained HTML node graph).++ Pipe it to a file to keep or open it: ``jarvis outputs graph <slug> > map.html``.+ """+ invoke.run("GET", f"/api/outputs/{slug}/graph")++@app.command()def openers() -> None:"""List installed editors/apps that can open an artifact."""diff --git a/jarvis/ui/web/mission_graph.py b/jarvis/ui/web/mission_graph.pynew file mode 100644index 0000000000..db5bdd4b20--- /dev/null+++ b/jarvis/ui/web/mission_graph.py@@ -0,0 +1,572 @@+"""Render a mission archive as an n8n-style node-graph HTML page.++The Outputs archive can already *list* what a mission produced, but a flat file+list answers "which files exist", not "what happened". This module turns one+mission's archive into a single self-contained HTML page laid out like a+workflow editor: the mission on the left, its worker steps in the middle, the+deliverables they produced on the right, connected by curved tracks. One glance+answers "what ran, what came out, and how the pieces connect".++Serving constraints shape the whole design:++* The page is served in the app origin under the strict no-script CSP of the+ artifact ``/view`` route (``VIEW_CSP``: ``default-src 'none'``), so there is+ **no JavaScript**. All layout — node positions, canvas size, the bezier+ control points of every track — is computed here in Python and baked into+ the markup. Edges are one absolutely-positioned SVG layer; nodes are HTML+ ``<div>``s on top of it (HTML wraps and ellipsizes text, SVG ``<text>``+ cannot).+* Every dynamic string (utterance, step labels, filenames) is worker- or+ user-authored and is escaped before it reaches the page.+* The palette is the brand theme — matte black + signal yellow — kept in+ lockstep with the desktop app (``frontend/src/index.css`` dark tokens) and+ the video intro (``video/src/intro/theme.ts`` ``COLORS``).++Pure stdlib, no filesystem access: callers (``outputs_routes``) gather the+archive facts and pass plain data in, which keeps this renderer trivially+testable and reusable.+"""++from __future__ import annotations++import html+import posixpath+import re+from collections.abc import Mapping, Sequence+from dataclasses import dataclass++# --- Brand palette -----------------------------------------------------------+# Mirrors video/src/intro/theme.ts COLORS, which mirrors the desktop app's+# frontend/src/index.css dark tokens. Change all three together.+BRAND: Mapping[str, str] = {+ "bg": "#0A0A0A",+ "bg_elevated": "#141414",+ "bg_card": "#181818",+ "primary": "#FFD60A",+ "primary_deep": "#E6BE00",+ "text": "#FAFAFA",+ "text_muted": "#9A9A9A",+ "text_faint": "#6B6B6B",+ "border": "rgba(255,255,255,0.10)",+ "border_strong": "rgba(255,255,255,0.18)",+ "good": "#4ADE80",+ "primary_glow": "rgba(255,214,10,0.35)",+}++# Status → pill/track accent. Keys match OUTPUT_STATUSES in outputs_routes.+_STATUS_ACCENTS: Mapping[str, str] = {+ "success": BRAND["good"],+ "running": BRAND["primary"],+ "error": "#F87171",+ "cancelled": BRAND["text_muted"],+ "unknown": BRAND["text_faint"],+}++_STATUS_LABELS: Mapping[str, str] = {+ "success": "Success",+ "running": "Running",+ "error": "Failed",+ "cancelled": "Cancelled",+ "unknown": "Unknown",+}++# --- Graph model -------------------------------------------------------------+++@dataclass(frozen=True)+class GraphFile:+ """One archived deliverable, relative to its step's ``artifacts/files/``."""++ path: str+ size: int+++@dataclass(frozen=True)+class GraphStep:+ """One worker step (``tasks/<id>/``) and the deliverables it archived.++ ``tool_calls``/``failed_calls`` come from the reconstructed step timeline+ (:mod:`jarvis.ui.web.run_plan`) when a worker transcript exists; both stay+ zero for a run without a readable stream, and the subtitle then falls back+ to the file count alone.+ """++ step_id: str+ label: str+ files: tuple[GraphFile, ...]+ tool_calls: int = 0+ failed_calls: int = 0+++@dataclass(frozen=True)+class MissionGraphData:+ """Everything the renderer needs, already collected by the caller."""++ slug: str+ title: str+ status: str+ summary: str | None+ duration_s: float | None+ steps: tuple[GraphStep, ...]+++# Worktree-style task dir names carry a human label: ``01__refactor-router``.+_STEP_SLUG_RE = re.compile(r"^(?P<num>\d{1,3})__(?P<label>.+)$")+++def _step_label(step_id: str, index: int) -> str:+ """A human name for a task directory.++ ``01__refactor-router`` → "01 · Refactor router" (worktree-style names carry+ their label). Kontrollierer-style names are UUID prefixes with nothing human+ in them, so those become "Step N" — honest and readable beats hex.+ """+ m = _STEP_SLUG_RE.match(step_id)+ if m:+ words = m.group("label").replace("-", " ").replace("_", " ").strip()+ pretty = words[:1].upper() + words[1:] if words else step_id+ return f"{m.group('num')} · {pretty}"+ return f"Step {index + 1}"+++def build_mission_graph(+ slug: str,+ *,+ utterance: str | None,+ status: str,+ summary: str | None,+ duration_s: float | None,+ task_ids: Sequence[str],+ files: Sequence[Mapping[str, object]],+ plan_steps: Sequence[Mapping[str, object]] = (),+) -> MissionGraphData:+ """Assemble the graph model from archive facts.++ *files* entries are the ``/artifacts`` listing shape (``path`` like+ ``tasks/<id>/artifacts/files/<rel>``, plus ``size``). Files are grouped+ under their step; *task_ids* keeps steps visible even when they archived+ nothing — a step that ran and produced no deliverable is a fact worth+ showing, not hiding.++ *plan_steps* is the (optional) reconstructed timeline from+ :func:`jarvis.ui.web.run_plan.build_run_plan` — each entry's ``step_id``+ is ``"<task_id>:<seq>"``, which is aggregated here into per-step tool-call+ and failure counts. Purely additive: no transcript, no counts, same graph.+ """+ calls_by_task: dict[str, int] = {}+ failed_by_task: dict[str, int] = {}+ for plan_step in plan_steps:+ step_id = str(plan_step.get("step_id", ""))+ task_id, _, _seq = step_id.partition(":")+ if not task_id:+ continue+ calls_by_task[task_id] = calls_by_task.get(task_id, 0) + 1+ if plan_step.get("status") == "failed":+ failed_by_task[task_id] = failed_by_task.get(task_id, 0) + 1+ by_step: dict[str, list[GraphFile]] = {task_id: [] for task_id in task_ids}+ for entry in files:+ path = str(entry.get("path", ""))+ parts = path.replace("\\", "/").split("/")+ # Deliverable paths are tasks/<id>/artifacts/files/<rel> — anything+ # else is not archive-shaped and is skipped rather than guessed at.+ if len(parts) < 5 or parts[0] != "tasks" or parts[2] != "artifacts" or parts[3] != "files":+ continue+ step_id = parts[1]+ rel = "/".join(parts[4:])+ size = entry.get("size", 0)+ by_step.setdefault(step_id, []).append(+ GraphFile(path=rel, size=int(size) if isinstance(size, (int, float)) else 0)+ )++ steps = tuple(+ GraphStep(+ step_id=step_id,+ label=_step_label(step_id, index),+ files=tuple(sorted(step_files, key=lambda f: f.path)),+ tool_calls=calls_by_task.get(step_id, 0),+ failed_calls=failed_by_task.get(step_id, 0),+ )+ for index, (step_id, step_files) in enumerate(sorted(by_step.items()))+ )+ return MissionGraphData(+ slug=slug,+ title=(utterance or "").strip() or slug,+ status=status if status in _STATUS_ACCENTS else "unknown",+ summary=(summary or "").strip() or None,+ duration_s=duration_s,+ steps=steps,+ )+++# --- Layout ------------------------------------------------------------------+# Fixed geometry, computed server-side. A column per node kind, left to right:+# mission → steps → deliverables, the n8n reading direction.++_MARGIN = 64+_COL_GAP = 112+_ROW_GAP = 16+_GROUP_GAP = 40++_MISSION_W, _MISSION_H = 272, 116+_STEP_W, _STEP_H = 240, 78+_FILE_W, _FILE_H = 256, 58+_OVERFLOW_H = 42++# Per step, at most this many file nodes are drawn individually; the rest+# collapse into one "+N more" node so a 92-file mission stays one readable+# screen instead of a two-metre column. The cap is stated on the node itself —+# a hidden file must read as "collapsed", never as "not produced".+MAX_FILES_PER_STEP = 6+++@dataclass(frozen=True)+class _Placed:+ """A node with resolved geometry, ready to print."""++ kind: str # mission | step | file | overflow+ x: int+ y: int+ w: int+ h: int+ title: str+ subtitle: str+ badge: str = ""+++def _human_size(size: int) -> str:+ if size < 1024:+ return f"{size} B"+ if size < 1024 * 1024:+ return f"{size / 1024:.0f} KB"+ return f"{size / (1024 * 1024):.1f} MB"+++def _human_duration(seconds: float) -> str:+ if seconds < 60:+ return f"{seconds:.0f} s"+ if seconds < 3600:+ return f"{seconds / 60:.0f} min"+ return f"{seconds / 3600:.1f} h"+++def _step_subtitle(step: GraphStep) -> str:+ """ "12 tool calls · 2 files" — only the parts the archive can actually back."""+ bits: list[str] = []+ if step.tool_calls:+ bits.append(f"{step.tool_calls} tool call{'s' if step.tool_calls != 1 else ''}")+ bits.append(f"{len(step.files)} file{'s' if len(step.files) != 1 else ''}")+ return " · ".join(bits)+++def _file_badge(path: str) -> str:+ ext = posixpath.splitext(path)[1].lstrip(".").upper()+ return ext[:6] if ext else "FILE"+++def _layout(+ data: MissionGraphData,+) -> tuple[list[_Placed], list[tuple[float, float, float, float]], int, int]:+ """Place every node and route every edge.++ Returns ``(nodes, edges, canvas_w, canvas_h)`` where each edge is the+ ``(x1, y1, x2, y2)`` port pair a bezier is drawn between. Steps and their+ file stacks share one vertical band per step, so neither column can+ overlap itself; the mission node centers on the whole span.+ """+ mission_x = _MARGIN+ step_x = mission_x + _MISSION_W + _COL_GAP+ file_x = step_x + _STEP_W + _COL_GAP++ # Height of each step's band: the taller of the step node itself and its+ # visible file stack (capped + optional overflow node).+ bands: list[tuple[GraphStep, list[GraphFile], int, int]] = []+ for step in data.steps:+ visible = list(step.files[:MAX_FILES_PER_STEP])+ hidden = len(step.files) - len(visible)+ stack_h = len(visible) * _FILE_H + max(0, len(visible) - 1) * _ROW_GAP+ if hidden > 0:+ stack_h += (_ROW_GAP if visible else 0) + _OVERFLOW_H+ bands.append((step, visible, hidden, max(_STEP_H, stack_h)))++ total_h = sum(band_h for *_rest, band_h in bands)+ total_h += max(0, len(bands) - 1) * _GROUP_GAP+ total_h = max(total_h, _MISSION_H)++ nodes: list[_Placed] = []+ edges: list[tuple[float, float, float, float]] = []++ mission_y = _MARGIN + (total_h - _MISSION_H) // 2+ file_count = sum(len(step.files) for step in data.steps)+ mission = _Placed(+ kind="mission",+ x=mission_x,+ y=mission_y,+ w=_MISSION_W,+ h=_MISSION_H,+ title=data.title,+ subtitle=f"{len(data.steps)} step{'s' if len(data.steps) != 1 else ''}"+ f" · {file_count} deliverable{'s' if file_count != 1 else ''}",+ badge=_STATUS_LABELS.get(data.status, "Unknown"),+ )+ nodes.append(mission)+ mission_port = (mission_x + _MISSION_W, mission_y + _MISSION_H / 2)++ cursor = _MARGIN+ for step, visible, hidden, band_h in bands:+ step_y = cursor + (band_h - _STEP_H) // 2+ step_node = _Placed(+ kind="step",+ x=step_x,+ y=step_y,+ w=_STEP_W,+ h=_STEP_H,+ title=step.label,+ subtitle=_step_subtitle(step),+ badge=f"{step.failed_calls} failed" if step.failed_calls else "",+ )+ nodes.append(step_node)+ edges.append((*mission_port, step_x, step_y + _STEP_H / 2))+ step_port = (step_x + _STEP_W, step_y + _STEP_H / 2)++ stack_h = len(visible) * _FILE_H + max(0, len(visible) - 1) * _ROW_GAP+ if hidden > 0:+ stack_h += (_ROW_GAP if visible else 0) + _OVERFLOW_H+ file_y = cursor + (band_h - stack_h) // 2 if stack_h else cursor+ for deliverable in visible:+ nodes.append(+ _Placed(+ kind="file",+ x=file_x,+ y=file_y,+ w=_FILE_W,+ h=_FILE_H,+ title=posixpath.basename(deliverable.path) or deliverable.path,+ subtitle=_human_size(deliverable.size),+ badge=_file_badge(deliverable.path),+ )+ )+ edges.append((*step_port, file_x, file_y + _FILE_H / 2))+ file_y += _FILE_H + _ROW_GAP+ if hidden > 0:+ nodes.append(+ _Placed(+ kind="overflow",+ x=file_x,+ y=file_y,+ w=_FILE_W,+ h=_OVERFLOW_H,+ title=f"+{hidden} more file{'s' if hidden != 1 else ''}",+ subtitle="collapsed — see the Outputs list",+ )+ )+ edges.append((*step_port, file_x, file_y + _OVERFLOW_H / 2))+ cursor += band_h + _GROUP_GAP++ has_files = any(step.files for step in data.steps)+ right_edge = (+ file_x + _FILE_W+ if has_files+ else (step_x + _STEP_W if data.steps else mission_x + _MISSION_W)+ )+ canvas_w = right_edge + _MARGIN+ canvas_h = _MARGIN * 2 + total_h+ return nodes, edges, canvas_w, canvas_h+++# --- Rendering ---------------------------------------------------------------++_ICONS: Mapping[str, str] = {+ # Inline SVGs are part of the document, so they render under the no-script+ # CSP where external images would be blocked. 16×16 viewBox, currentColor.+ "mission": (+ '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" '+ 'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">'+ '<path d="M3 14V2.5"/><path d="M3 3h9l-2 2.5L12 8H3"/></svg>'+ ),+ "step": (+ '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" '+ 'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">'+ '<path d="M9 1.5 3.5 9H8l-1 5.5L12.5 7H8l1-5.5Z"/></svg>'+ ),+ "file": (+ '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" '+ 'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">'+ '<path d="M4 1.5h5L13 5.5V14a.5.5 0 0 1-.5.5h-8A.5.5 0 0 1 4 14V1.5Z"/>'+ '<path d="M9 1.5V6h4"/></svg>'+ ),+}+++def _css(data: MissionGraphData) -> str:+ accent = _STATUS_ACCENTS.get(data.status, BRAND["text_faint"])+ # A running mission's tracks flow (pure CSS, allowed by the CSP); a settled+ # mission's tracks hold still — motion means "in progress", nothing else.+ flow = (+ ".edge{stroke-dasharray:7 9;animation:track-flow 1.1s linear infinite}"+ "@keyframes track-flow{to{stroke-dashoffset:-16}}"+ if data.status == "running"+ else ""+ )+ return (+ "*{box-sizing:border-box;margin:0;padding:0}"+ f"body{{background:{BRAND['bg']};color:{BRAND['text']};"+ "font:14px/1.5 -apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;"+ "min-height:100vh}"+ f"header{{display:flex;align-items:center;gap:14px;padding:18px 28px;"+ f"background:{BRAND['bg_elevated']};border-bottom:1px solid {BRAND['border']}}}"+ f".mark{{width:12px;height:12px;border-radius:50%;background:{BRAND['primary']};"+ f"box-shadow:0 0 14px {BRAND['primary_glow']};flex:none}}"+ "h1{font-size:16px;font-weight:600;overflow:hidden;text-overflow:ellipsis;"+ "white-space:nowrap;min-width:0}"+ f".kicker{{font-size:11px;letter-spacing:.14em;text-transform:uppercase;"+ f"color:{BRAND['text_muted']}}}"+ ".head-text{min-width:0;flex:1}"+ f".pill{{flex:none;font-size:11px;font-weight:600;letter-spacing:.08em;"+ f"text-transform:uppercase;padding:4px 12px;border-radius:999px;"+ f"color:{accent};border:1px solid {accent};background:{BRAND['bg_card']}}}"+ f".meta{{padding:12px 28px;color:{BRAND['text_muted']};font-size:12px;"+ f"border-bottom:1px solid {BRAND['border']};overflow:hidden;"+ "text-overflow:ellipsis;white-space:nowrap}"+ ".canvas-wrap{overflow:auto;padding:0}"+ ".canvas{position:relative;"+ f"background-image:radial-gradient(rgba(255,255,255,0.06) 1px,transparent 1px);"+ "background-size:22px 22px}"+ ".edges{position:absolute;inset:0;width:100%;height:100%}"+ f".edge{{fill:none;stroke:{BRAND['primary_deep']};stroke-opacity:.55;stroke-width:2}}"+ f".port{{fill:{BRAND['bg_card']};stroke:{BRAND['primary']};stroke-width:1.5}}"+ f".node{{position:absolute;display:flex;align-items:center;gap:10px;"+ f"padding:10px 14px;border-radius:10px;background:{BRAND['bg_card']};"+ f"border:1px solid {BRAND['border']};"+ "box-shadow:0 4px 16px rgba(0,0,0,0.45)}"+ f".node:hover{{border-color:{BRAND['border_strong']}}}"+ ".icon{flex:none;width:30px;height:30px;border-radius:8px;display:flex;"+ "align-items:center;justify-content:center}"+ ".icon svg{width:16px;height:16px}"+ f".node-mission{{border-color:rgba(255,214,10,0.45);"+ f"box-shadow:0 0 28px rgba(255,214,10,0.10),0 4px 16px rgba(0,0,0,0.45)}}"+ f".node-mission .icon{{background:rgba(255,214,10,0.12);color:{BRAND['primary']}}}"+ f".node-step .icon{{background:rgba(255,255,255,0.06);color:{BRAND['primary']}}}"+ f".node-file .icon{{background:rgba(255,255,255,0.05);color:{BRAND['text_muted']}}}"+ f".node-overflow{{justify-content:center;color:{BRAND['text_muted']};"+ f"border-style:dashed;background:{BRAND['bg_elevated']}}}"+ ".body{min-width:0;flex:1}"+ ".title{font-size:13px;font-weight:600;overflow:hidden;text-overflow:ellipsis;"+ "white-space:nowrap}"+ f".subtitle{{font-size:11px;color:{BRAND['text_muted']};overflow:hidden;"+ "text-overflow:ellipsis;white-space:nowrap}"+ f".badge{{flex:none;font-size:10px;font-weight:700;letter-spacing:.06em;"+ f"padding:2px 7px;border-radius:5px;background:rgba(255,214,10,0.10);"+ f"color:{BRAND['primary']}}}"+ f".node-mission .badge{{color:{accent};background:transparent;"+ f"border:1px solid {accent}}}"+ # A step's badge only ever announces failures — it reads as a warning.+ ".node-step .badge{color:#F87171;background:rgba(248,113,113,0.10)}"+ f"footer{{display:flex;gap:22px;padding:14px 28px;font-size:11px;"+ f"color:{BRAND['text_faint']};border-top:1px solid {BRAND['border']}}}"+ ".legend{display:flex;align-items:center;gap:7px}"+ ".swatch{width:9px;height:9px;border-radius:3px}" + flow+ )+++def _edge_path(x1: float, y1: float, x2: float, y2: float) -> str:+ """The n8n curve: horizontal-out, horizontal-in, one cubic bezier."""+ bend = max(36.0, (x2 - x1) / 2)+ return (+ f"M {x1:.1f} {y1:.1f} "+ f"C {x1 + bend:.1f} {y1:.1f}, {x2 - bend:.1f} {y2:.1f}, {x2:.1f} {y2:.1f}"+ )+++def _render_node(node: _Placed) -> str:+ icon = _ICONS.get("file" if node.kind == "overflow" else node.kind, _ICONS["file"])+ badge = f'<span class="badge">{html.escape(node.badge)}</span>' if node.badge else ""+ if node.kind == "overflow":+ inner = (+ f'<div class="body"><div class="title">{html.escape(node.title)}</div>'+ f'<div class="subtitle">{html.escape(node.subtitle)}</div></div>'+ )+ else:+ kicker = '<div class="kicker">Mission</div>' if node.kind == "mission" else ""+ inner = (+ f'<div class="icon">{icon}</div>'+ f'<div class="body">{kicker}'+ f'<div class="title">{html.escape(node.title)}</div>'+ f'<div class="subtitle">{html.escape(node.subtitle)}</div></div>'+ f"{badge}"+ )+ style = f"left:{node.x}px;top:{node.y}px;width:{node.w}px;height:{node.h}px"+ return f'<div class="node node-{node.kind}" style="{style}">{inner}</div>'+++def render_mission_graph_html(data: MissionGraphData) -> str:+ """Return the complete, self-contained mission-map document."""+ nodes, edges, canvas_w, canvas_h = _layout(data)++ paths = "".join(+ f'<path class="edge" d="{_edge_path(x1, y1, x2, y2)}"/>' for x1, y1, x2, y2 in edges+ )+ # Connection ports drawn over the track ends, the n8n affordance that makes+ # a line read as "plugged in" rather than decoration.+ ports = "".join(+ f'<circle class="port" cx="{x:.1f}" cy="{y:.1f}" r="4"/>'+ for x, y in {(x1, y1) for x1, y1, *_ in edges} | {(x2, y2) for *_ignored, x2, y2 in edges}+ )+ svg = (+ f'<svg class="edges" viewBox="0 0 {canvas_w} {canvas_h}" '+ f'width="{canvas_w}" height="{canvas_h}" aria-hidden="true">{paths}{ports}</svg>'+ )+ node_html = "".join(_render_node(node) for node in nodes)++ status_label = _STATUS_LABELS.get(data.status, "Unknown")+ meta_bits = [f"Session {data.slug}"]+ if data.duration_s is not None:+ meta_bits.append(_human_duration(data.duration_s))+ if data.summary:+ meta_bits.append(data.summary)+ meta = " · ".join(meta_bits)++ empty_note = (+ '<p class="meta">This mission archived no steps yet — the map fills in as work lands.</p>'+ if not data.steps+ else ""+ )++ title = f"{data.title} — Mission map"+ return (+ "<!doctype html>"+ '<html lang="en"><head><meta charset="utf-8">'+ '<meta name="viewport" content="width=device-width,initial-scale=1">'+ f"<title>{html.escape(title)}</title>"+ f"<style>{_css(data)}</style></head><body>"+ '<header><span class="mark"></span>'+ '<div class="head-text"><div class="kicker">Mission map</div>'+ f"<h1>{html.escape(data.title)}</h1></div>"+ f'<span class="pill">{html.escape(status_label)}</span></header>'+ f'<p class="meta">{html.escape(meta)}</p>'+ f"{empty_note}"+ '<div class="canvas-wrap">'+ f'<div class="canvas" style="width:{canvas_w}px;height:{canvas_h}px">'+ f"{svg}{node_html}</div></div>"+ "<footer>"+ + "".join(+ f'<span class="legend"><span class="swatch" '+ f'style="background:{color}"></span>{label}</span>'+ for label, color in (+ ("Mission", BRAND["primary"]),+ ("Step", BRAND["text_muted"]),+ ("Deliverable", BRAND["text_faint"]),+ )+ )+ + "</footer></body></html>"+ )+++__all__ = [+ "BRAND",+ "MAX_FILES_PER_STEP",+ "GraphFile",+ "GraphStep",+ "MissionGraphData",+ "build_mission_graph",+ "render_mission_graph_html",+]diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.pyindex 53c0465839..258d184cbe 100644--- a/jarvis/ui/web/outputs_routes.py+++ b/jarvis/ui/web/outputs_routes.py@@ -35,6 +35,7 @@ from jarvis.missions.kontrollierer.deliverable_paths import (from jarvis.missions.state_machine import MissionState, is_terminalfrom jarvis.platform import detect_platformfrom jarvis.ui.web.artifact_view import VIEW_CSP, render_artifact_html+from jarvis.ui.web.mission_graph import build_mission_graph, render_mission_graph_htmlfrom jarvis.ui.web.run_plan import build_run_planlogger = logging.getLogger(__name__)@@ -685,6 +686,94 @@ async def get_output_plan(slug: str, request: Request) -> dict[str, Any]:return await asyncio.to_thread(build_run_plan, session_dir, utterance=utterance)+def _collect_graph_files(session_dir: Path) -> list[dict[str, Any]]:+ """The deliverable paths + sizes the mission map draws — no previews.++ Same allowlist and listing cap as ``list_output_artifacts``; kept separate+ because the graph never needs file contents, and reading 200 previews for+ a page that shows none of them would be pure disk tax.+ """+ files: list[dict[str, Any]] = []+ try:+ for child in session_dir.rglob("*"):+ if not child.is_file():+ continue+ rel_parts = child.relative_to(session_dir).parts+ if not _is_deliverable_relpath(rel_parts):+ continue+ try:+ stat = child.stat()+ except OSError:+ continue+ files.append({"path": "/".join(rel_parts), "size": stat.st_size})+ if len(files) >= _ARTIFACT_MAX_LISTING:+ break+ except OSError as exc:+ logger.warning("outputs: graph walk failed for %s: %s", session_dir, exc)+ return files++[email protected]("/{slug}/graph")+async def get_output_graph(slug: str, request: Request) -> HTMLResponse:+ """Render the mission archive as an n8n-style node-graph HTML page.++ One self-contained, brand-themed document (mission → steps → deliverables,+ connected by tracks) built from three archive reads: the deliverable walk,+ the reconstructed step timeline (:func:`build_run_plan`, for per-step+ tool-call counts), and — when the dir name carries a mission-id prefix —+ the missions DB for status/summary/duration. All filesystem work runs off+ the event loop; DB enrichment is best-effort exactly like the list view.++ Served under the same no-script CSP as ``/view``: the page carries zero+ JavaScript (layout is computed server-side), so worker-authored strings+ baked into it can never execute in the app origin.+ """+ session_dir = _resolve_output_dir(request, slug)+ parsed = _parse_slug(session_dir.name)++ prefix = _mission_id_prefix_for_dir(session_dir.name)+ lookup = await _mission_status_lookup(request, [prefix] if prefix else [])+ row = lookup.get(prefix) if prefix else None++ status = "unknown"+ summary: str | None = None+ duration_s: float | None = None+ utterance = parsed["utterance"]+ if row is not None:+ status = _STATE_TO_STATUS.get(str(row["state"]), "unknown")+ utterance = utterance or row.get("prompt")+ summary = row.get("terminal_summary")+ # Same wall-clock rule as the list view: a running mission ticks from+ # created_ms to now; a settled one froze at updated_ms.+ running = status == "running"+ if row["created_ms"]:+ end_ms = time.time() * 1000.0 if running else row["updated_ms"]+ if end_ms:+ duration_s = max(0.0, (end_ms - row["created_ms"]) / 1000.0)++ files = await asyncio.to_thread(_collect_graph_files, session_dir)+ task_ids = await asyncio.to_thread(_task_ids_in, session_dir)+ plan = await asyncio.to_thread(build_run_plan, session_dir, utterance=utterance)++ data = build_mission_graph(+ session_dir.name,+ utterance=utterance,+ status=status,+ summary=summary,+ duration_s=duration_s,+ task_ids=task_ids,+ files=files,+ plan_steps=plan.get("steps", []),+ )+ return HTMLResponse(+ render_mission_graph_html(data),+ headers={+ "Content-Security-Policy": VIEW_CSP,+ "X-Content-Type-Options": "nosniff",+ },+ )++# Soft size limits for the artifact preview endpoint — full bytes are# served by `{slug}/files/{path}/raw`; the listing endpoint inlines only a# short preview so the UI sidebar doesn't have to fetch each file.diff --git a/tests/unit/ui/web/test_mission_graph.py b/tests/unit/ui/web/test_mission_graph.pynew file mode 100644index 0000000000..a37a1cfae6--- /dev/null+++ b/tests/unit/ui/web/test_mission_graph.py@@ -0,0 +1,140 @@+"""Unit tests for the mission node-graph page (model, layout honesty, escaping).++The renderer bakes worker- and user-authored strings into a page served in the+app origin, so the escape tests here are security guards, not cosmetics. The+overflow tests guard the honesty rule: a collapsed file must read as+"collapsed", never as "not produced".+"""+from __future__ import annotations++from jarvis.ui.web.mission_graph import (+ BRAND,+ MAX_FILES_PER_STEP,+ build_mission_graph,+ render_mission_graph_html,+)+++def _files(step_id: str, names: list[str]) -> list[dict[str, object]]:+ return [+ {"path": f"tasks/{step_id}/artifacts/files/{name}", "size": 1000 + i}+ for i, name in enumerate(names)+ ]+++def _build(**overrides: object):+ kwargs: dict[str, object] = {+ "utterance": "Build a city guide",+ "status": "success",+ "summary": None,+ "duration_s": 120.0,+ "task_ids": ["019fed06-19e8"],+ "files": _files("019fed06-19e8", ["guide.html", "map.png"]),+ }+ kwargs.update(overrides)+ return build_mission_graph("mission_019fed06-19df", **kwargs) # type: ignore[arg-type]+++# --- Model -------------------------------------------------------------------+++def test_files_group_under_their_step():+ data = _build()+ assert len(data.steps) == 1+ assert [f.path for f in data.steps[0].files] == ["guide.html", "map.png"]+++def test_step_without_files_stays_visible():+ data = _build(task_ids=["019fed06-19e8", "019fed06-ffff"])+ assert {s.step_id for s in data.steps} == {"019fed06-19e8", "019fed06-ffff"}+++def test_worktree_style_step_id_becomes_readable_label():+ data = _build(task_ids=["01__refactor-router"], files=[])+ assert data.steps[0].label == "01 · Refactor router"+++def test_uuid_step_id_becomes_step_number():+ data = _build()+ assert data.steps[0].label == "Step 1"+++def test_non_archive_paths_are_skipped_not_guessed():+ data = _build(files=[{"path": "reflections.md", "size": 10}])+ assert all(not s.files for s in data.steps)+++def test_unknown_status_normalizes_to_unknown():+ assert _build(status="weird").status == "unknown"+++def test_plan_steps_aggregate_tool_calls_and_failures():+ plan_steps = [+ {"step_id": "019fed06-19e8:0", "status": "done"},+ {"step_id": "019fed06-19e8:1", "status": "failed"},+ {"step_id": "019fed06-19e8:2", "status": "done"},+ ]+ data = _build(plan_steps=plan_steps)+ assert data.steps[0].tool_calls == 3+ assert data.steps[0].failed_calls == 1+++# --- Rendering ---------------------------------------------------------------+++def test_page_uses_brand_theme():+ out = render_mission_graph_html(_build())+ assert BRAND["bg"] in out # matte-black ground+ assert BRAND["primary"] in out # signal-yellow accent+++def test_page_has_no_script_anywhere():+ # Served under the no-script CSP — the page must not need JS to render.+ out = render_mission_graph_html(_build())+ assert "<script" not in out.lower()+++def test_nodes_and_edges_render():+ out = render_mission_graph_html(_build())+ assert 'class="node node-mission"' in out+ assert 'class="node node-step"' in out+ assert out.count('class="node node-file"') == 2+ # One track per connection: mission→step plus step→each file.+ assert out.count('<path class="edge"') == 3+++def test_utterance_and_filenames_are_escaped():+ data = _build(+ utterance='<script>alert(1)</script>',+ files=_files("019fed06-19e8", ['<img src=x onerror=alert(1)>.html']),+ )+ out = render_mission_graph_html(data)+ assert "<script>alert(1)</script>" not in out+ assert "<script>" in out+ assert "<img src=x" not in out+++def test_overflow_states_the_hidden_count():+ many = _files("019fed06-19e8", [f"page{i}.md" for i in range(MAX_FILES_PER_STEP + 4)])+ out = render_mission_graph_html(_build(files=many))+ assert out.count('class="node node-file"') == MAX_FILES_PER_STEP+ assert "+4 more files" in out+++def test_empty_mission_renders_with_honest_note():+ out = render_mission_graph_html(_build(task_ids=[], files=[]))+ assert "archived no steps yet" in out+ assert 'class="node node-mission"' in out+++def test_failed_calls_surface_as_step_badge():+ plan_steps = [{"step_id": "019fed06-19e8:0", "status": "failed"}]+ out = render_mission_graph_html(_build(plan_steps=plan_steps))+ assert "1 failed" in out+++def test_running_mission_gets_flowing_tracks_and_settled_does_not():+ running = render_mission_graph_html(_build(status="running"))+ settled = render_mission_graph_html(_build(status="success"))+ assert "track-flow" in running+ assert "track-flow" not in settleddiff --git a/tests/unit/ui/web/test_outputs_routes.py b/tests/unit/ui/web/test_outputs_routes.pyindex dccdfe6e77..8c809a9a4b 100644--- a/tests/unit/ui/web/test_outputs_routes.py+++ b/tests/unit/ui/web/test_outputs_routes.py@@ -1483,3 +1483,42 @@ def test_put_preferred_opener_rejects_unknown(app):client = TestClient(app)r = client.put("/api/outputs/preferred-opener", json={"opener": "../../evil"})assert r.status_code == 400+++# --- Mission graph page (`/{slug}/graph`) ------------------------------------+++async def test_graph_page_renders_branded_node_graph(app, db_conn):+ """The graph route serves a no-script, brand-themed page of the archive."""+ mission_id = "019ed2df-d0fa-7cba-a111-222233334444"+ root = Path(app.state.outputs_root)+ d = _make_mission_dir(root, mission_id)+ _seed(d / "tasks" / "019ed2df-d0fb" / "artifacts" / "files" / "guide.html", "<html>")+ # Scaffolding must never appear on the map (same allowlist as the listing).+ _seed(d / "claude_config" / "settings.json", "{}")+ await _insert_mission(db_conn, mission_id=mission_id, state="APPROVED", prompt="build a guide")++ with TestClient(app) as client:+ r = client.get(f"/api/outputs/{d.name}/graph")+ assert r.status_code == 200+ assert r.headers["content-type"].startswith("text/html")+ # Same no-script CSP as the /view route — the page carries zero JS.+ assert "default-src 'none'" in r.headers["content-security-policy"]+ assert "<script" not in r.text.lower()+ assert "#0A0A0A" in r.text and "#FFD60A" in r.text # brand theme+ assert "guide.html" in r.text+ assert "settings.json" not in r.text+ assert "build a guide" in r.text # DB prompt fills the missing utterance+ assert "Success" in r.text # APPROVED → success pill+++def test_graph_page_unknown_slug_is_404(app):+ with TestClient(app) as client:+ assert client.get("/api/outputs/mission_nope123456/graph").status_code == 404+++def test_graph_page_traversal_slug_is_rejected(app):+ with TestClient(app) as client:+ r = client.get("/api/outputs/..%2F..%2Fetc/graph")+ assert r.status_code in (400, 404)