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(artifacts): pages a strong agent writes, shown full-size — the visualize tool becomes create_artifact
rubenluetke10-beep2c325ff4eec5
diff --git a/docs/adr/0011-router-pure-dispatcher.md b/docs/adr/0011-router-pure-dispatcher.mdindex 308339ce37..6954016b62 100644--- a/docs/adr/0011-router-pure-dispatcher.md+++ b/docs/adr/0011-router-pure-dispatcher.md@@ -1203,3 +1203,61 @@ automation request → skill-creator), `tests/unit/commands/test_registry_parityskeleton, collision suffix)- `tests/unit/ui/web/test_skills_routes.py`, `tests/unit/cli_ctl/test_commands_wave23.py`- `tests/fixtures/skill_routing/golden.yaml` (forensic positive)++## Amendment: `create-artifact` router tool (2026-08-23)++`create-artifact` joins `ROUTER_TOOLS` and replaces the 2026-08-11 `visualize`+tool: the brain can have ONE self-contained page built — a dashboard, a+report, a diagram, a small interactive tool — and shown full-size in the+Artifacts section (`jarvis/plugins/tool/create_artifact.py`).++### Context++`visualize` let the model supply a STRUCTURE (one of five fixed shapes, a+dozen labels) and had Python render the page. That kept a picture cheap and+deterministic, but it is also why every result looked like the same five+cards, and why the section that showed them was a run graph with the page+hidden in a 288 px inspector frame. The maintainer's decision (2026-08-23):+an artifact is a whole page the model writes — the way Claude artifacts work+— and writing one well takes the strongest model the install has and longer+than a voice turn can hold. So the page is written by a mission worker, not+by the router brain.++### Decision++- `create_artifact(title, request, revise?, spoken_ack?)` composes the worker+ brief (`jarvis/artifacts/brief.py`: one HTML file, all assets inline, no+ network, brand palette, light/dark, the user's language; on a revision the+ previous page verbatim) and dispatches it through the mission stack — the+ same `MissionManager.dispatch` → `Kontrollierer.run_mission` path as+ `spawn_worker`, with the same lazy resolvers (AD-OC1) and the same spoken+ failure on every dead end (AU-11). The call returns within the voice budget+ with a spoken promise; completion reaches the user through the mission+ voice listener. Risk `monitor`, like `spawn_worker`; never in a worker set+ (AP-5/AP-14).+- **Ask-only, structurally.** `BrainManager._hide_artifact_tool_without_request`+ removes the tool from every turn that does not ask for an artifact+ (`jarvis/brain/artifact_gate.py`: explicit word — visualisier / Artefakt /+ Dashboard / Infografik — or a build verb next to a page noun; navigation to+ the section and definition questions never open it). Regex only (AP-11).+- The Artifacts section (`VisualizationView`, section id unchanged) shows the+ page full-size from `/api/outputs/{slug}/files/{path}/page`, served with+ `ARTIFACT_PAGE_CSP` (inline scripts allowed, every network path shut) inside+ `sandbox="allow-scripts"` without `allow-same-origin`. Source under "Code",+ the run graph that used to be the section under "Run".+- `jarvis/visuals/{spec,render,store}.py` and the gallery-as-pseudo-run store+ are retired; `jarvis/visuals/brand.py` stays (mission map + brief palette).++### Regression guards++- `tests/unit/brain/test_artifact_gate.py` (vocabulary, navigation beats the+ verb, definition questions, page nouns only next to a verb)+- `tests/unit/brain/test_artifact_tool_hide.py` (placement in the manager,+ fail-open)+- `tests/unit/plugins/tool/test_create_artifact.py` (brief reaches the+ manager verbatim, Kontrollierer runs it, NavigateSidebar, spoken failure on+ no runner / crash, revision from the archive)+- `tests/unit/artifacts/test_brief.py`, `tests/unit/artifacts/test_locate.py`+- `tests/unit/ui/web/test_outputs_routes.py::test_artifact_page_*`+- frontend: `VisualizationView.test.tsx`, `RunGraphPanel.test.tsx`+- `tests/unit/brain/test_routing.py` (`create-artifact` in `ROUTER_TOOLS`)diff --git a/jarvis/artifacts/__init__.py b/jarvis/artifacts/__init__.pynew file mode 100644index 0000000000..82562b4577--- /dev/null+++ b/jarvis/artifacts/__init__.py@@ -0,0 +1,40 @@+"""Artifacts — the self-contained pages Jarvis builds when asked for one.++An artifact is ONE HTML file a person looks at: a dashboard, a report, an+infographic, a small interactive tool. It is authored by a mission worker on+the strongest model the install has (the same sub-agent path ``spawn_worker``+uses), not by the router brain, and it lands in the run archive like every+other deliverable — so the Outputs surfaces, the Downloads mirror and the+Artifacts section all see it without a second store.++Two pieces live here:++* :mod:`~jarvis.artifacts.brief` — the worker's task instruction: what a+ finished artifact is (one file, inline assets, no network, brand look), plus+ the previous version when a revision is asked for.+* :mod:`~jarvis.artifacts.locate` — find an existing artifact in the archive+ by title, so "make the bars red" can start from the page it refers to.++The tool that dispatches the mission is ``jarvis.plugins.tool.create_artifact``;+the gate that decides whether the tool is offered on a turn at all is+``jarvis.brain.artifact_gate`` — ask-only, never ambient.+"""++from __future__ import annotations++from jarvis.artifacts.brief import (+ MAX_PREVIOUS_HTML_CHARS,+ ArtifactBrief,+ artifact_filename,+ build_artifact_brief,+)+from jarvis.artifacts.locate import LocatedArtifact, locate_artifact++__all__ = [+ "MAX_PREVIOUS_HTML_CHARS",+ "ArtifactBrief",+ "LocatedArtifact",+ "artifact_filename",+ "build_artifact_brief",+ "locate_artifact",+]diff --git a/jarvis/artifacts/brief.py b/jarvis/artifacts/brief.pynew file mode 100644index 0000000000..4e0590df1d--- /dev/null+++ b/jarvis/artifacts/brief.py@@ -0,0 +1,222 @@+"""The worker's task instruction for one artifact.++The router brain never writes a page itself: it hands a short request to the+mission stack, and a worker on the strongest model the install has writes the+whole file. This module turns that request into the instruction the worker+reads — the one text that decides whether what comes back is a real artifact+(one self-contained page that renders inside the app's sandbox) or a project+scaffold with a README.++Everything a finished artifact must be is stated HERE, because the worker+shares none of the app's context. The rules are the sandbox's rules: the page+is framed with scripts allowed but every network request blocked, so an+external font, CDN script or remote image is not "slightly slower" — it is a+broken page. Stated once, in the brief, is the only place that can prevent it.++Pure function of its inputs: no clock, no filesystem, no randomness. What the+worker receives for a given request is byte-identical across runs, which is+what lets a golden test pin the contract.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from typing import Final++from jarvis.visuals.brand import BRAND++# How much of a previous version rides along on a revision. The worker rewrites+# the whole file from it, so the cap is generous — but a page that outgrew it+# is summarised by its head and tail rather than blowing the prompt past what a+# worker's context can take.+MAX_PREVIOUS_HTML_CHARS: Final = 160_000++# Title → filename. Kept short: the archive path is already deep+# (run / tasks / id / artifacts / files / name) and Windows callers still meet+# MAX_PATH.+_MAX_FILENAME_STEM: Final = 48+_NON_SLUG_RE: Final = re.compile(r"[^a-z0-9]+")++# The first paragraph of every mission prompt is the standing quality directive+# ``spawn_worker`` also leads with. It is recognised by its phrasing+# ("production-quality") in ``jarvis.missions.stream_evidence.clean_request_body``,+# which strips it so the Outputs rail shows the real ask — so the wording below+# must keep that phrase, and the artifact line must come right after it.+_QUALITY_LEAD: Final = (+ "Deliver a complete, polished, production-quality artifact that fully "+ "satisfies the request below. A skeleton, stub, placeholder or "+ '"content follows" shell is a FAILURE — never ship one. If a detail is '+ "unspecified, pick a rich, sensible default and build the finished page."+)++_LANGUAGE_NAMES: Final[dict[str, str]] = {+ "de": "German",+ "en": "English",+ "es": "Spanish",+}+++@dataclass(frozen=True)+class ArtifactBrief:+ """The mission prompt plus the facts the tool reports back."""++ prompt: str+ """The complete worker instruction — what ``MissionManager.dispatch`` gets."""+ filename: str+ """The one file the worker is told to write, e.g. ``sales-dashboard.html``."""+ title: str+ """The artifact's title as it will appear in the page and the rail."""+ revision: bool+ """True when the brief starts from an existing page."""+++def artifact_filename(title: str) -> str:+ """``"Sales dashboard — Q3"`` → ``"sales-dashboard-q3.html"``."""+ stem = _NON_SLUG_RE.sub("-", (title or "").lower()).strip("-")+ if len(stem) > _MAX_FILENAME_STEM:+ stem = stem[:_MAX_FILENAME_STEM].rstrip("-")+ return f"{stem or 'artifact'}.html"+++def _language_name(code: str) -> str:+ return _LANGUAGE_NAMES.get((code or "").strip().lower(), "the language of the request")+++def _bounded_previous(html: str) -> str:+ """The previous page, whole when it fits, head + tail when it does not."""+ text = html or ""+ if len(text) <= MAX_PREVIOUS_HTML_CHARS:+ return text+ half = MAX_PREVIOUS_HTML_CHARS // 2+ return (+ text[:half]+ + "\n\n<!-- … middle of the previous version omitted for length … -->\n\n"+ + text[-half:]+ )+++def build_artifact_brief(+ request: str,+ *,+ title: str,+ language: str,+ previous_html: str | None = None,+ previous_filename: str | None = None,+) -> ArtifactBrief:+ """Compose the worker instruction for one artifact.++ Inputs:+ request: what the user wants on the page — the content, the data,+ the style wishes — in the user's own words or the brain's faithful+ summary of them. Never empty; the caller validates.+ title: the artifact's title; names the file and the ``<title>``.+ language: the turn's output language code (de / en / es). The page's+ visible text is written in it.+ previous_html: for a revision, the page to start from (the worker+ rewrites the whole file with the change applied).+ previous_filename: the previous page's filename, kept on a revision so+ the new version lands under the same name.+ """+ clean_title = " ".join((title or "").split()) or "Artifact"+ clean_request = (request or "").strip()+ revision = bool(previous_html)+ filename = (+ previous_filename if revision and previous_filename else artifact_filename(clean_title)+ )+ lang_name = _language_name(language)+ lang_code = (language or "").strip().lower() or "en"+ b = BRAND++ sections: list[str] = [+ _QUALITY_LEAD,+ f"Artifact: {clean_title}\n{clean_request}",+ "\n".join(+ [+ "## What to build",+ f"Exactly ONE self-contained HTML file named `{filename}`, at the "+ "root of your working directory. That file IS the whole "+ "deliverable: no second file, no README, no project scaffold, no "+ "build step, no framework install.",+ '- Start with `<!doctype html>`, `<html lang="'+ + lang_code+ + '">`, `<meta charset="utf-8">`, a viewport meta tag and a '+ f"`<title>` that names the artifact: `{clean_title}`.",+ "- ALL CSS and JavaScript inline, inside the file. Nothing "+ "external: no CDN scripts, no web fonts, no remote images or "+ "stylesheets, no fetch/XHR/WebSocket. The page is shown inside a "+ "sandbox that blocks every network request, so one external "+ "reference means a broken page. Draw icons and illustrations as "+ "inline SVG; embed small images as data: URIs.",+ "- JavaScript is allowed and welcome for interactivity — tabs, "+ "filters, sorting, calculators, charts drawn on canvas or SVG. "+ "It must never call alert/confirm/prompt, never open windows, "+ "never navigate away, and must work with no network at all.",+ f"- The visible content is written in {lang_name} — every heading, "+ "label, caption and note. Code identifiers and comments stay English.",+ ]+ ),+ "\n".join(+ [+ "## Design",+ "- Dark brand look by default: page background "+ f"{b['bg']}, cards {b['bg_card']}, text {b['text']}, muted text "+ f"{b['text_muted']}, accent {b['primary']}, borders {b['border']}. "+ "Add an `@media (prefers-color-scheme: light)` block with a "+ "matching light palette (paper background, near-black text, the "+ "same accent) so the page reads well in both modes.",+ "- Calm typography on a system-ui font stack, generous spacing, "+ "12–14 px rounded cards, 1 px borders, no gratuitous animation.",+ "- Responsive: readable from 360 px to 1600 px; wide tables, code "+ "and diagrams scroll inside their own container, never the page "+ "sideways.",+ "- Real content, never filler: put the numbers, facts and data the "+ "request names into the page. When something needed is missing, "+ "make a clearly labelled assumption — never lorem ipsum, never "+ "'TODO'.",+ ]+ ),+ "\n".join(+ [+ "## Done means",+ "- The file opens from disk, with no network, and renders "+ "correctly with no console errors.",+ "- The page shows what was asked for — the title, the content, the "+ "data — and says nothing about how it was built.",+ "- Nothing else was created or changed.",+ ]+ ),+ ]++ if revision:+ sections.append(+ "\n".join(+ [+ "## Starting point",+ "This is a revision of an existing artifact. Rewrite the ENTIRE "+ f"file `{filename}` with the requested change applied. Keep "+ "everything the request did not ask to change — content, "+ "structure, styling — and keep the same filename. The "+ "previous version follows verbatim:",+ "",+ "```html",+ _bounded_previous(previous_html or ""),+ "```",+ ]+ )+ )++ return ArtifactBrief(+ prompt="\n\n".join(sections),+ filename=filename,+ title=clean_title,+ revision=revision,+ )+++__all__ = [+ "MAX_PREVIOUS_HTML_CHARS",+ "ArtifactBrief",+ "artifact_filename",+ "build_artifact_brief",+]diff --git a/jarvis/artifacts/locate.py b/jarvis/artifacts/locate.pynew file mode 100644index 0000000000..d36b9db3f2--- /dev/null+++ b/jarvis/artifacts/locate.py@@ -0,0 +1,140 @@+"""Find an existing artifact in the run archive, for a revision.++"Make the bars red" only makes sense against the page it talks about. The+brain cannot name that page by path — it never sees the archive — so the tool+accepts a TITLE (or "latest") and this module resolves it against the HTML+deliverables of the most recent runs. Bounded on purpose: the scan reads the+newest :data:`MAX_RUNS_SCANNED` run directories and the first few kilobytes of+each page for its ``<title>``; an archive with three hundred runs does not make+a revision request cost three hundred file reads.++Read-only, and honest about misses: ``None`` means "no such artifact among the+recent runs", and the tool turns that into an error the model can act on+(build it fresh, or ask which one).+"""++from __future__ import annotations++import logging+import re+from dataclasses import dataclass+from pathlib import Path++from jarvis.core.paths import repo_root+from jarvis.missions.isolation.worktree import resolve_readable_outputs_roots++log = logging.getLogger(__name__)++#: Newest run directories looked at per archive root.+MAX_RUNS_SCANNED = 40+#: Bytes read from a page to find its ``<title>``.+_TITLE_PROBE_BYTES = 8192+#: A revision brief rides the whole page; anything larger is not an artifact+#: this feature produced and is left alone.+_MAX_ARTIFACT_BYTES = 2_000_000++_TITLE_RE = re.compile(r"<title[^>]*>(.*?)</title>", re.IGNORECASE | re.DOTALL)+_NON_WORD_RE = re.compile(r"[^a-z0-9]+")+_HTML_SUFFIXES = {".html", ".htm"}+++@dataclass(frozen=True)+class LocatedArtifact:+ """One existing page, with what a revision brief needs from it."""++ slug: str+ """Run directory name — the ``/api/outputs/{slug}`` path segment."""+ artifact_path: str+ """Posix path inside the run, as ``/artifacts`` lists it."""+ file: Path+ """Absolute path on disk."""+ title: str+ """The page's ``<title>``, or its filename stem when it has none."""+ html: str+ """The page's full text."""+++def _normalize(text: str) -> str:+ return _NON_WORD_RE.sub(" ", (text or "").lower()).strip()+++def _page_title(file: Path) -> str:+ try:+ with file.open("r", encoding="utf-8", errors="replace") as handle:+ head = handle.read(_TITLE_PROBE_BYTES)+ except OSError:+ return file.stem+ match = _TITLE_RE.search(head)+ if match is None:+ return file.stem+ title = " ".join(match.group(1).split())+ return title or file.stem+++def _candidate_pages(root: Path) -> list[tuple[float, Path, Path]]:+ """``(mtime, run_dir, page)`` for every HTML deliverable of the newest runs."""+ try:+ run_dirs = [entry for entry in root.iterdir() if entry.is_dir()]+ except OSError:+ return []+ # Newest first by directory mtime — the same order the Outputs rail uses.+ run_dirs.sort(key=lambda d: d.stat().st_mtime if d.exists() else 0.0, reverse=True)+ pages: list[tuple[float, Path, Path]] = []+ for run_dir in run_dirs[:MAX_RUNS_SCANNED]:+ try:+ for page in run_dir.glob("tasks/*/artifacts/files/**/*"):+ if page.suffix.lower() not in _HTML_SUFFIXES or not page.is_file():+ continue+ stat = page.stat()+ if stat.st_size > _MAX_ARTIFACT_BYTES:+ continue+ pages.append((stat.st_mtime, run_dir, page))+ except OSError as exc:+ log.debug("artifact scan skipped %s: %s", run_dir, exc)+ return pages+++def locate_artifact(+ query: str, *, outputs_roots: tuple[Path, ...] | None = None+) -> LocatedArtifact | None:+ """The newest recent artifact matching ``query``, or None.++ ``query`` is ``"latest"`` for the most recent page of any title, otherwise+ a title (or part of one) compared case- and punctuation-insensitively+ against each page's ``<title>`` and filename stem.+ """+ roots = (+ outputs_roots if outputs_roots is not None else resolve_readable_outputs_roots(repo_root())+ )+ wanted = _normalize(query)+ if not wanted:+ return None++ pages: list[tuple[float, Path, Path]] = []+ for root in roots:+ if root.is_dir():+ pages.extend(_candidate_pages(root))+ pages.sort(key=lambda item: item[0], reverse=True)++ for _mtime, run_dir, page in pages:+ title = _page_title(page)+ if wanted != "latest":+ haystack = f"{_normalize(title)} {_normalize(page.stem)}"+ if wanted not in haystack:+ continue+ try:+ html = page.read_text(encoding="utf-8", errors="replace")+ except OSError as exc:+ log.debug("artifact unreadable %s: %s", page, exc)+ continue+ return LocatedArtifact(+ slug=run_dir.name,+ artifact_path=page.relative_to(run_dir).as_posix(),+ file=page,+ title=title,+ html=html,+ )+ return None+++__all__ = ["MAX_RUNS_SCANNED", "LocatedArtifact", "locate_artifact"]diff --git a/jarvis/brain/visualize_gate.py b/jarvis/brain/artifact_gate.pysimilarity index 61%rename from jarvis/brain/visualize_gate.pyrename to jarvis/brain/artifact_gate.pyindex 3ad0157646..62cf28b27b 100644--- a/jarvis/brain/visualize_gate.py+++ b/jarvis/brain/artifact_gate.py@@ -1,13 +1,15 @@-"""Explicit-request gate for the ``visualize`` tool (ask-only, never ambient).--Drawing a picture is the one capability a user must be able to switch on with-their own words. An assistant that decides on its own when an answer "would be-clearer as a diagram" produces a stream of pictures nobody asked for, and every-one of them costs a tool call, a rendered artifact on disk, and a jump of the-UI to another section. So the tool is not merely *discouraged* ambiently — it is-withheld from the model's tool set on every turn that did not ask for it (see-``BrainManager._hide_visualize_tool_without_request``), which also keeps its-schema out of the request on the ~99% of turns that are about something else.+"""Explicit-request gate for the ``create_artifact`` tool (ask-only, never ambient).++Building an artifact — a page, a dashboard, a diagram the user looks at — is+the one capability a user must be able to switch on with their own words. An+assistant that decides on its own when an answer "would be clearer as a page"+produces a stream of artifacts nobody asked for, and every one of them costs a+background mission on the strongest model, a file in the archive, and a jump+of the UI to another section. So the tool is not merely *discouraged*+ambiently — it is withheld from the model's tool set on every turn that did+not ask for it (see ``BrainManager._hide_artifact_tool_without_request``),+which also keeps its schema out of the request on the ~99% of turns that are+about something else.Regex-only, provider-agnostic, no model in the detection path (AP-11): the gateruns on every single turn, so an LLM here would tax exactly the turns this@@ -15,18 +17,20 @@ module exists to keep cheap.Three rules, in order:-1. A **navigation** utterance is never a request to draw. "Zeig mir die- Visualisierungen" opens the section that lists what already exists — the+1. A **navigation** utterance is never a request to build. "Zeig mir die+ Artefakte" opens the section that lists what already exists — the``navigate`` tool owns that, and it must not be shadowed by a tool that- would produce a brand-new picture instead of showing the old ones.-2. A **definition question** ("was ist eine Visualisierung?") is answered with+ would produce a brand-new page instead of showing the old ones.+2. A **definition question** ("was ist ein Artefakt?") is answered withwords. The word appearing in a question about the word is not a request.-3. Otherwise: an explicit drawing VERB on its own, or a build/show verb- together with a visual NOUN, is a request.+3. Otherwise: an explicit artifact VERB or NOUN on its own ("visualisier",+ "Artefakt", "Dashboard"), or a build/show verb together with a visual NOUN+ ("mach mir ein Diagramm", "show me that as a page"), is a request.-A false negative is cheap and self-correcting — the user says "visualisier mir-das" and gets it on the next turn. A false positive is the whole problem this-module was written for, so every pattern here is deliberately narrow.+A false negative is cheap and self-correcting — the user says "mach ein+Artefakt draus" and gets it on the next turn. A false positive is the whole+problem this module was written for, so every pattern here is deliberately+narrow.Every literal below is input-matching vocabulary in the user's spoken languages(DE/EN/ES), which the language policy allows on the input surface.@@ -51,7 +55,8 @@ _NAV_ARTICLES = ()_NAV_SECTION_NOUNS = (r"visualisierung(?:s\w*)?(?:en)?|" # i18n-allow: input vocab- r"visualiz(?:ation|aciones|aci[oó]n)s?|visualisations?|visuals"+ r"visualiz(?:ation|aciones|aci[oó]n)s?|visualisations?|visuals|"+ r"artefakte?|artifacts?|artefactos?" # i18n-allow: input vocab)_NAV_SUFFIX = (r"(?:\s*[-–]?\s*"@@ -78,9 +83,10 @@ _DEFINITION_RE = re.compile(re.IGNORECASE,)-# --- 3a. Drawing verbs strong enough on their own -----------------------------# "visualisier mir das", "visualize this", "mach eine Mindmap draus". Each of-# these names the ACT of drawing; no second signal is needed. Stems are matched+# --- 3a. Words strong enough on their own -------------------------------------+# "visualisier mir das", "visualize this", "mach eine Mindmap draus", "ein+# Artefakt bitte", "als Dashboard". Each of these names the ACT of building a+# picture or the artifact itself; no second signal is needed. Stems are matched# so every inflection is covered ("visualisiere", "visualizing", "visualízalo")._EXPLICIT_RE = re.compile(r"\b(?:"@@ -90,7 +96,11 @@ _EXPLICIT_RE = re.compile(r"veranschaulich\w*|skizzier\w*|" # i18n-allow: input vocabr"schaubild|flussdiagramm|ablaufdiagramm|organigramm|" # i18n-allow: input vocabr"mindmap|mind\s+map|flowchart|flow\s+chart|org\s+chart|"- r"esquematiza\w*|diagrama\s+de\s+flujo" # i18n-allow: input vocab+ r"esquematiza\w*|diagrama\s+de\s+flujo|" # i18n-allow: input vocab+ # The artifact by name, and the page shapes that ARE artifacts.+ r"artefakte?s?|artifacts?|artefactos?|" # i18n-allow: input vocab+ r"dashboards?|infografik\w*|infographics?|infograf[ií]as?|" # i18n-allow: input vocab+ r"landing\s*pages?|one-?pagers?"r")\b",re.IGNORECASE,)@@ -120,17 +130,24 @@ _NOUN_RE = re.compile(r"diagram|chart|graphic|timeline|infographic|"r"visually|graphically|as\s+(?:a\s+)?(?:picture|image|drawing)|"r"diagrama|gr[áa]fic[oa]s?|l[íi]nea\s+de\s+tiempo|" # i18n-allow: input vocab- r"visualmente|gr[áa]ficamente" # i18n-allow: input vocab+ r"visualmente|gr[áa]ficamente|" # i18n-allow: input vocab+ # Page shapes — a request only next to a build/show verb ("mach mir eine+ # Seite dazu", "build me a report page"), never on their own: "die Seite+ # war langsam" is conversation.+ r"html(?:-?(?:seite|datei|page|file))?|webseite|websites?|web\s*pages?|" # i18n-allow+ r"p[áa]ginas?(?:\s+web)?|als\s+seite|as\s+a\s+page|" # i18n-allow: input vocab+ r"bericht(?:sseite)?|reports?|informes?|" # i18n-allow: input vocab+ r"übersicht(?:sseite)?|uebersicht|overview\s+page" # i18n-allow: input vocabr")\b",re.IGNORECASE,)-def wants_visualization(text: str) -> bool:- """True when the utterance explicitly asks for a picture to be drawn.+def wants_artifact(text: str) -> bool:+ """True when the utterance explicitly asks for an artifact to be built.- The single decision point for offering the ``visualize`` tool at all. See- the module docstring for the three rules and why each one is narrow.+ The single decision point for offering the ``create_artifact`` tool at+ all. See the module docstring for the three rules and why each is narrow."""t = (text or "").strip()if not t:@@ -144,4 +161,4 @@ def wants_visualization(text: str) -> bool:return bool(_VERB_RE.search(t) and _NOUN_RE.search(t))-__all__ = ["wants_visualization"]+__all__ = ["wants_artifact"]diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex e5dd122a20..c46ca3ca8f 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -77,16 +77,19 @@ ROUTER_TOOLS = frozenset({# never in a worker set (AP-5/AP-14). See ADR-0011 amendment "Navigate tool"."navigate",# On-demand visualisation (2026-08-11): draw what is under discussion as a- # flow / hierarchy / comparison / timeline / bar chart, archive it, and- # open the Visualization section. Router-tier, risk safe, NO spawn — never- # in a worker set (AP-5/AP-14).+ # On-demand artifact (2026-08-23, rebuilt from the 2026-08-11 visualize+ # tool): build ONE self-contained HTML page — dashboard, report, diagram,+ # small tool — through the mission stack on the strongest model, archived+ # as the run's deliverable and shown full-size in the Artifacts section.+ # Router-tier dispatch (risk monitor, like spawn-worker) — never in a+ # worker set (AP-5/AP-14).## ASK-ONLY, and enforced structurally rather than by prompt: the tool is# removed from the tool set on every turn whose utterance does not- # explicitly ask for a picture (BrainManager- # ._hide_visualize_tool_without_request over jarvis/brain/visualize_gate).+ # explicitly ask for an artifact (BrainManager+ # ._hide_artifact_tool_without_request over jarvis/brain/artifact_gate).# Membership here is what makes it REACHABLE; the gate decides WHEN.- "visualize",+ "create-artifact",# Command Registry executor (2026-07-09): run ONE curated app command# (jarvis/commands/registry.py) through the SAME REST endpoint the UI# uses, in-process via ASGI transport. Enum-constrained command_id +@@ -514,11 +517,18 @@ def _load_tools_for_tier(# which the WS forwarder streams to the frontend (event_name# "NavigateSidebar") to switch the active section.inst = cls(bus=bus)- elif ep.name == "visualize":- # Same bus, same event: after archiving the rendered picture the- # tool publishes NavigateSidebar("visualization") so the section- # showing it comes to the front.- inst = cls(bus=bus)+ elif ep.name == "create-artifact":+ # The artifact is written by a mission worker (strongest model),+ # so the tool needs the same lazy mission-stack resolvers as+ # spawn-worker (AD-OC1: the stack bootstraps after the brain).+ # Publishes NavigateSidebar("visualization") on dispatch so the+ # Artifacts section shows the build as it happens.+ inst = cls(+ bus=bus,+ manager=mission_manager,+ manager_resolver=_resolve_mission_manager,+ kontrollierer_resolver=_resolve_kontrollierer,+ )elif ep.name == "whoami":inst = cls(profile=user_profile, people=people)elif ep.name == "awareness-snapshot":diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 203b7dacdc..fe89fe3c41 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -888,11 +888,11 @@ _SPAWN_TOOL_NAMES: frozenset[str] = frozenset({"spawn_worker", "multi_spawn"})# Deliberately NOT listed: ``agentic-ide-status`` (answers "nothing is open"# honestly) and ``agentic-ide-resume`` (the command that OPENS a workspace# by voice — hiding it would strand the feature).-# The on-demand visualisation tool. Offered ONLY on a turn that explicitly asks-# for a picture (see _hide_visualize_tool_without_request): the maintainer's-# rule is that a visualisation is something the user asks for, never something-# the assistant decides an answer deserves.-_VISUALIZE_TOOL_NAME: str = "visualize"+# The on-demand artifact tool. Offered ONLY on a turn that explicitly asks for+# a page/picture (see _hide_artifact_tool_without_request): the maintainer's+# rule is that an artifact is something the user asks for, never something the+# assistant decides an answer deserves.+_ARTIFACT_TOOL_NAME: str = "create_artifact"# Agentic-IDE pane tools that only make sense RELATIVE TO AN OPEN WORKSPACE._AGENTIC_IDE_WORKSPACE_TOOL_NAMES: frozenset[str] = frozenset({@@ -4828,7 +4828,7 @@ class BrainManager:and the cached system prefix survives an ordinary turn.Renders the ATTACHED surface (``self._tools``), not the turn's gated- subset: the per-turn gates (screenshot / visualize / inspect-pointer)+ subset: the per-turn gates (screenshot / create_artifact / inspect-pointer)drop tools on most turns, so following them would rewrite the systemprefix nearly every turn and cost the provider prompt cache far morethan the precision is worth. Hence "aktuell angeschlossen", never@@ -6415,38 +6415,33 @@ class BrainManager:log.debug("agentic-ide workspace tool gate failed", exc_info=True)return tools- def _hide_visualize_tool_without_request(+ def _hide_artifact_tool_without_request(self, tools: dict[str, Tool], user_text: str) -> dict[str, Tool]:- """Drop ``visualize`` from every turn that did not ask for a picture.-- Maintainer mandate (2026-08-11): a visualisation happens when the user- says they want to understand something visually — never because the- assistant judged an answer would look nicer as a diagram. Prompt wording- alone does not hold that line; a tool the model cannot see is a line it- cannot cross, so the enforcement is structural.-- It also pays for itself on the turns it fires: the tool's schema is the- largest of the router's UI tools (five kinds, nested items), and it- would otherwise ride along on every single loop iteration of every- unrelated turn.-- The gate is ``jarvis.brain.visualize_gate.wants_visualization`` — pure- regex, no model in the detection path (AP-11). Defensive: any fault- returns the tools unchanged, so a gate bug can never blind the brain.+ """Drop ``create_artifact`` from every turn that did not ask for one.++ Maintainer mandate (2026-08-11, renewed 2026-08-23 for artifacts): a+ page or picture is built when the user says they want to see+ something — never because the assistant judged an answer would look+ nicer as a dashboard. Prompt wording alone does not hold that line; a+ tool the model cannot see is a line it cannot cross, so the+ enforcement is structural. It also keeps a background mission on the+ strongest model from being started on a whim.++ The gate is ``jarvis.brain.artifact_gate.wants_artifact`` — pure regex,+ no model in the detection path (AP-11). Defensive: any fault returns+ the tools unchanged, so a gate bug can never blind the brain."""- if not isinstance(tools, dict) or _VISUALIZE_TOOL_NAME not in tools:+ if not isinstance(tools, dict) or _ARTIFACT_TOOL_NAME not in tools:return toolstry:- from jarvis.brain.visualize_gate import ( # noqa: PLC0415- wants_visualization,- )+ from jarvis.brain.artifact_gate import wants_artifact # noqa: PLC0415- if wants_visualization(user_text or ""):+ if wants_artifact(user_text or ""):return tools- return {n: tool for n, tool in tools.items() if n != _VISUALIZE_TOOL_NAME}+ return {n: tool for n, tool in tools.items() if n != _ARTIFACT_TOOL_NAME}except Exception: # noqa: BLE001 — gate must never blind the brain- log.debug("visualize request gate failed", exc_info=True)+ log.debug("artifact request gate failed", exc_info=True)return tools@staticmethod@@ -11404,13 +11399,13 @@ class BrainManager:_turn_tools = self._hide_agentic_ide_tools_without_workspace(_turn_tools)- # A picture is drawn when the user asks to SEE something, never- # because an answer might look nicer as a diagram (maintainer- # mandate 2026-08-11). Structural, not prompt-level: on a turn that- # did not ask, the model never sees the tool — and never pays for- # its schema.+ # An artifact is built when the user asks to SEE something, never+ # because an answer might look nicer as a page (maintainer mandate+ # 2026-08-11). Structural, not prompt-level: on a turn that did not+ # ask, the model never sees the tool — and never pays for its schema+ # or starts a background mission.if isinstance(_turn_tools, dict):- _turn_tools = self._hide_visualize_tool_without_request(+ _turn_tools = self._hide_artifact_tool_without_request(_turn_tools, user_text)# A referential follow-up that inherited a currently registereddiff --git a/jarvis/missions/standalone_run.py b/jarvis/missions/standalone_run.pyindex 3eea3cf128..35cfa34c8d 100644--- a/jarvis/missions/standalone_run.py+++ b/jarvis/missions/standalone_run.py@@ -7,11 +7,11 @@ sibling that carries its identity — and listing both produced the "two agentsfor one task" cards reported on 2026-05-26. Hiding the slug directory is theright call for that case.-It is the wrong call for a directory that has no sibling. An on-demand-visualisation (:mod:`jarvis.visuals.store`) is a complete run in one directory:-nothing is diffed, nothing is reviewed, and there is no mission row anywhere.-Under the old rule it would be written successfully and then never appear —-which is indistinguishable, from the user's side, from not being drawn at all.+It is the wrong call for a directory that has no sibling: a complete run in one+directory, nothing diffed, nothing reviewed, no mission row anywhere (the+2026-08-11 on-demand visualisation wrote such runs; the archive still holds+them). Under the old rule it would be written successfully and then never+appear — indistinguishable, from the user's side, from not being drawn at all.So the exception is made explicit rather than inferred. A standalone run dropsthis small JSON file at its root; the list treats a directory carrying it as adiff --git a/jarvis/plugins/tool/create_artifact.py b/jarvis/plugins/tool/create_artifact.pynew file mode 100644index 0000000000..c32f9f0242--- /dev/null+++ b/jarvis/plugins/tool/create_artifact.py@@ -0,0 +1,355 @@+"""``create_artifact`` — build (or revise) one self-contained page, when asked.++An artifact is the thing the user wants to LOOK AT: a dashboard, a report, an+infographic, a small interactive tool — one HTML file, rendered full-size in+the Artifacts section and openable in any browser. Writing such a page well+needs the strongest model the install has and more time than a voice turn can+hold, so this tool never writes the page itself. It composes the brief+(:mod:`jarvis.artifacts.brief`) and hands it to the mission stack — the same+sub-agent path ``spawn_worker`` uses — then returns within the voice budget+with a spoken promise. The worker writes the file into its worktree, the+Kontrollierer archives it as the run's deliverable, and the mission voice+listener reads the completion back; the Artifacts section shows the page the+moment it lands, because it reads the very archive the worker wrote into.++**Ask-only.** The tool is withheld from the model's tool set on any turn that+did not explicitly ask for an artifact; see :mod:`jarvis.brain.artifact_gate`+and ``BrainManager._hide_artifact_tool_without_request``. The gate is the real+enforcement — this description is the second line, for the turns where the+gate opens but the request was about something else.++Router-tier. It is a dispatch (risk ``monitor``, like ``spawn_worker``), so it+never enters a worker tool set (AP-5/AP-14): a worker building an artifact+cannot spawn another worker to build it.+"""++from __future__ import annotations++import asyncio+import logging+from collections.abc import Callable+from typing import Any, Final++from jarvis.artifacts.brief import build_artifact_brief+from jarvis.artifacts.locate import locate_artifact+from jarvis.core.bus import EventBus+from jarvis.core.events import (+ JarvisAgentAnnouncement,+ JarvisAgentBackgroundCompleted,+ NavigateSidebar,+)+from jarvis.core.protocols import ExecutionContext, ToolResult+from jarvis.voice.action_phrases import action_phrase, resolve_ambient_language++log = logging.getLogger(__name__)++#: The section that shows artifacts — the frontend ``SectionId`` the navigate+#: tool's parity test pins.+ARTIFACTS_SECTION: Final = "visualization"++#: Resolved at execute-time, not at __init__-time: the mission stack is+#: bootstrapped AFTER the brain is built (AD-OC1, the same lazy-resolver+#: pattern ``spawn_worker`` uses).+ManagerResolver = Callable[[], Any | None]+KontrolliererResolver = Callable[[], Any | None]++#: The brief carries the user's request verbatim; this caps a runaway model+#: summary, not a real request. Anything longer is still a request — clipped.+_MAX_REQUEST_CHARS: Final = 6_000+_MAX_TITLE_CHARS: Final = 120+++def _turn_language(ctx: Any, args: dict[str, Any]) -> str:+ """de/en/es for the brief and the spoken acknowledgement.++ The turn's resolved output language wins (stamped by the tool-use loop via+ ``resolve_output_language``); the brain's own ``language`` guess is next;+ the ambient answer last. This layer never re-derives a language from the+ utterance (CLAUDE.md §2).+ """+ config = getattr(ctx, "config", None)+ stamped = ""+ if isinstance(config, dict):+ stamped = str(config.get("output_language") or "").strip().lower()+ lang = stamped or str(args.get("language") or "").strip().lower()+ return lang or resolve_ambient_language()+++def _utterance(ctx: Any) -> str:+ """What the user said this turn, when the context carries it."""+ for attribute in ("user_utterance", "user_text", "utterance", "text"):+ value = getattr(ctx, attribute, None)+ if isinstance(value, str) and value.strip():+ return value.strip()+ return ""+++class CreateArtifactTool:+ """Dispatch one artifact build to the mission stack and promise it aloud."""++ name: str = "create_artifact"+ risk_tier: str = "monitor"+ description: str = (+ "Build an ARTIFACT: one self-contained HTML page the user can look at — "+ "a dashboard, report, infographic, diagram, comparison, timeline, chart, "+ "landing page or small interactive tool. A strong background agent "+ "writes the page; it appears in the Artifacts section when done (about "+ "a minute). Use this when the user explicitly asks to SEE something as "+ "a page, picture, diagram or artifact ('visualisier mir das', 'mach mir "+ "ein Dashboard draus', 'build me an artifact', 'show me that as a "+ "timeline'). Never call it to decorate an ordinary answer. To change "+ "an existing artifact ('make the bars red'), pass 'revise' with its "+ "title (or 'latest'). This does NOT open the Artifacts section — that "+ "is 'navigate'. Prefer this over spawn_worker whenever the deliverable "+ "is a page to look at."+ )+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "title": {+ "type": "string",+ "description": (+ "The artifact's title, a few words, in the user's language. "+ "Names the page and the file."+ ),+ },+ "request": {+ "type": "string",+ "description": (+ "Everything the page must contain, self-contained: the "+ "subject, the content points, any numbers or data the user "+ "gave, and style wishes. The agent that builds it sees "+ "nothing else of this conversation, so include what was "+ "discussed. Write it in the user's language."+ ),+ },+ "revise": {+ "type": "string",+ "description": (+ "Only when changing an EXISTING artifact: its title (or part "+ "of it), or 'latest' for the most recent one. 'request' then "+ "describes the change."+ ),+ },+ "language": {+ "type": "string",+ "enum": ["de", "en", "es"],+ "description": "Language the user is speaking (fallback only).",+ },+ "spoken_ack": {+ "type": "string",+ "description": (+ "One short spoken sentence confirming the artifact is being "+ "built in the background, in the user's language. Optional."+ ),+ },+ },+ "required": ["title", "request"],+ }++ def __init__(+ self,+ bus: EventBus,+ *,+ manager: Any | None = None,+ manager_resolver: ManagerResolver | None = None,+ kontrollierer: Any | None = None,+ kontrollierer_resolver: KontrolliererResolver | None = None,+ ) -> None:+ if manager is None and manager_resolver is None:+ raise ValueError("CreateArtifactTool requires 'manager' or 'manager_resolver'")+ self._bus = bus+ self._manager = manager+ self._manager_resolver = manager_resolver+ self._kontrollierer = kontrollierer+ self._kontrollierer_resolver = kontrollierer_resolver++ # -- resolvers ----------------------------------------------------------++ def _resolve_manager(self) -> Any | None:+ if self._manager is not None:+ return self._manager+ if self._manager_resolver is not None:+ return self._manager_resolver()+ return None++ def _resolve_kontrollierer(self) -> Any | None:+ if self._kontrollierer is not None:+ return self._kontrollierer+ if self._kontrollierer_resolver is not None:+ return self._kontrollierer_resolver()+ return None++ # -- execute ------------------------------------------------------------++ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:+ args = args or {}+ title = " ".join(str(args.get("title") or "").split())[:_MAX_TITLE_CHARS]+ request = str(args.get("request") or "").strip()[:_MAX_REQUEST_CHARS]+ revise = " ".join(str(args.get("revise") or "").split())+ language = _turn_language(ctx, args)++ # A rejected call is the model's to fix: the error says exactly what+ # was missing, so the second attempt can be right.+ if not title:+ return ToolResult(success=False, output="", error="'title' must not be empty.")+ if not request:+ return ToolResult(+ success=False,+ output="",+ error="'request' must describe what the page should contain.",+ )++ previous = None+ if revise:+ previous = await asyncio.to_thread(locate_artifact, revise)+ if previous is None:+ return ToolResult(+ success=False,+ output="",+ error=(+ f"No recent artifact matches {revise!r}. Build it fresh "+ "without 'revise', or name the artifact's title more exactly."+ ),+ )++ manager = self._resolve_manager()+ if manager is None:+ # The mission stack is not up yet — the machine's problem, said+ # plainly so the model relays it instead of retrying into a wall.+ return ToolResult(+ success=False,+ output="",+ error=action_phrase("spawn_no_runner", language),+ )++ brief = build_artifact_brief(+ request,+ title=previous.title if previous else title,+ language=language,+ previous_html=previous.html if previous else None,+ previous_filename=previous.file.name if previous else None,+ )+ kontrollierer = self._resolve_kontrollierer()+ utterance = _utterance(ctx) or request+ # The mission dispatch contract is de/en; an "es" turn keeps the German+ # mission readback (the same cap spawn_worker applies).+ mission_language = language if language in ("de", "en") else "de"++ # UI/telemetry announce — the agent strip shows "builds the artifact".+ # Best-effort like every other announce: the build happens either way.+ try:+ await self._bus.publish(+ JarvisAgentAnnouncement(+ trace_id=ctx.trace_id,+ action=("revises the artifact" if brief.revision else "builds the artifact"),+ target=brief.title,+ )+ )+ except Exception as exc: # noqa: BLE001 — see comment above+ log.warning("create_artifact announce failed error=%s", exc)++ # Fire-and-forget: the router is free again within the voice budget;+ # the completion reaches the user through the mission voice listener.+ # The task-name prefix is a live matching key — BrainManager+ # ``_cancel_all_background_tasks`` cancels by it.+ asyncio.create_task(+ self._background_dispatch(+ brief.prompt,+ utterance,+ manager,+ kontrollierer,+ mission_language=mission_language,+ readback_language=language,+ ),+ name=f"jarvis-agent-artifact-{ctx.trace_id.hex[:8]}",+ )++ # Move the UI to the Artifacts section so the "building…" row is seen.+ # Best-effort on purpose: the build exists either way.+ try:+ await self._bus.publish(+ NavigateSidebar(+ section=ARTIFACTS_SECTION,+ source_layer="brain.tool.create_artifact",+ )+ )+ except Exception as exc: # noqa: BLE001 — see comment above+ log.warning("create_artifact navigate failed error=%s", exc)++ ack = (str(args.get("spoken_ack") or "").strip()) or action_phrase(+ "artifact_revising" if brief.revision else "artifact_building",+ language,+ title=brief.title,+ )+ return ToolResult(+ success=True,+ output=ack,+ artifacts=(+ {+ "background_task": True,+ "utterance": utterance,+ "artifact_title": brief.title,+ "artifact_file": brief.filename,+ "revision": brief.revision,+ },+ ),+ )++ async def _background_dispatch(+ self,+ prompt: str,+ utterance: str,+ manager: Any,+ kontrollierer: Any | None,+ *,+ mission_language: str,+ readback_language: str,+ ) -> None:+ """Persist the mission and run it — the two-step contract spawn_worker+ documents (dispatch → PENDING, run_mission → APPROVED/FAILED).++ Every dead end becomes a spoken failure through the same completion+ event a finished mission uses, never a log line alone (AU-11): the+ user already heard a promise.+ """+ try:+ mission_id = await manager.dispatch(+ prompt=prompt,+ language=mission_language,+ source_actor="hauptjarvis",+ )+ if kontrollierer is None:+ log.warning(+ "create_artifact: mission %s dispatched but no Kontrollierer "+ "available — it stays PENDING until the next app start",+ mission_id,+ )+ await self._publish_failure(+ utterance, action_phrase("spawn_no_runner", readback_language)+ )+ return+ await kontrollierer.run_mission(mission_id)+ except asyncio.CancelledError:+ log.info("create_artifact background dispatch cancelled (app shutdown)")+ raise+ except BaseException as exc: # noqa: BLE001 — fire-and-forget task, see docstring+ log.exception("create_artifact background dispatch crashed")+ await self._publish_failure(utterance, f"{type(exc).__name__}: {exc}")++ async def _publish_failure(self, utterance: str, error: str) -> None:+ try:+ await self._bus.publish(+ JarvisAgentBackgroundCompleted(+ success=False,+ utterance=utterance,+ summary="",+ error=error,+ duration_s=0.0,+ )+ )+ except Exception: # noqa: BLE001 — dead bus at shutdown; leave a trace+ log.exception("create_artifact failure publish crashed")+++__all__ = ["ARTIFACTS_SECTION", "CreateArtifactTool"]diff --git a/jarvis/plugins/tool/navigate.py b/jarvis/plugins/tool/navigate.pyindex c780e962f0..9f32de40ad 100644--- a/jarvis/plugins/tool/navigate.py+++ b/jarvis/plugins/tool/navigate.py@@ -147,9 +147,15 @@ _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.+ # The Artifacts section (section id kept as "visualization" — its 2026-08+ # name — because the id crosses the navigate parity test, the detachable+ # view registry and deep links). Spoken forms: the new name first.+ "artifacts": "visualization",+ "artifact": "visualization",+ "artefakte": "visualization", # i18n-allow: input vocab+ "artefakt": "visualization", # i18n-allow: input vocab+ "artefactos": "visualization", # i18n-allow: input vocab+ "artefacto": "visualization", # i18n-allow: input vocab"visualisation": "visualization","visuals": "visualization","charts": "visualization",diff --git a/jarvis/plugins/tool/visualize.py b/jarvis/plugins/tool/visualize.pydeleted file mode 100644index 1580934f83..0000000000--- a/jarvis/plugins/tool/visualize.py+++ /dev/null@@ -1,196 +0,0 @@-"""``visualize`` — draw what was just discussed, when the user asks for it.--Router-tier, risk ``safe``: it writes one HTML file into the run archive the-app already owns and moves the UI to the section that shows it. Nothing leaves-the machine, nothing existing is modified. A direct safe-gated action, never a-spawn — it never enters a worker tool set (AP-5/AP-14).--**Ask-only.** The tool is withheld from the model's tool set entirely on any-turn that did not explicitly ask for a picture; see-:mod:`jarvis.brain.visualize_gate` and-``BrainManager._hide_visualize_tool_without_request``. The gate is the real-enforcement — this description is the second line, for the turns where the gate-opens but the request was actually about something else.--The model supplies the STRUCTURE, never the markup: a title, a shape, and a-handful of short labels. Python owns the drawing-(:mod:`jarvis.visuals.render`). That is what keeps a picture cheap — a dozen-labels instead of a page of hand-written HTML — and what makes it safe to serve-inside the app origin, since nothing model-authored is ever markup.-"""--from __future__ import annotations--import logging-from typing import Any--from jarvis.core.events import NavigateSidebar-from jarvis.core.protocols import ToolResult-from jarvis.visuals.render import render_visual_html-from jarvis.visuals.spec import (- MAX_ITEMS,- VISUAL_KINDS,- VisualSpecError,- parse_spec,-)-from jarvis.visuals.store import store_visual--log = logging.getLogger(__name__)--# What each shape is FOR, in the model's terms. The picture is only useful if-# the shape matches the thought, and "kind" is the one field a model gets wrong-# in a way no validation can catch — so each option says when to pick it.-_KIND_GUIDE = (- "'flow' = ordered steps or a process; "- "'hierarchy' = parts within parts (use 'children'); "- "'comparison' = options side by side; "- "'timeline' = moments in chronological order; "- "'bars' = quantities compared (every item needs a numeric 'value')."-)---class VisualizeTool:- """Render one requested picture into the run archive and show it."""-- name: str = "visualize"- risk_tier: str = "safe"- description: str = (- "Draw the thing under discussion as a picture, and open it in the "- "Visualization section. Use this ONLY when the user explicitly asked to "- "SEE something — 'visualisier mir das', 'zeig mir das bildlich', 'mach "- "ein Diagramm draus', 'draw me a flowchart', 'show me that visually'. "- "Never call it to decorate an ordinary answer, and never on your own "- "initiative: an unrequested picture is a bug. "- "It does NOT open the existing gallery — that is 'navigate' with "- "section 'visualization'. Supply the STRUCTURE only (a title and a few "- "short labels); the page itself is rendered for you, so never write "- "HTML. " + _KIND_GUIDE- )- schema: dict[str, Any] = {- "type": "object",- "properties": {- "title": {- "type": "string",- "description": (- "The picture's heading — what it shows, in a few words. "- "Written in the language the user is speaking."- ),- },- "kind": {- "type": "string",- "enum": list(VISUAL_KINDS),- "description": "Which shape fits the thought. " + _KIND_GUIDE,- },- "items": {- "type": "array",- "minItems": 1,- "maxItems": MAX_ITEMS,- "description": (- f"The content, in order. At most {MAX_ITEMS} — pick the ones "- "that carry the point rather than everything you know."- ),- "items": {- "type": "object",- "properties": {- "label": {- "type": "string",- "description": "Short name of this step/part/option.",- },- "detail": {- "type": "string",- "description": "One short line of explanation. Optional.",- },- "value": {- "type": "number",- "description": "The quantity. Required for kind 'bars'.",- },- "children": {- "type": "array",- "description": "Nested items. Only for kind 'hierarchy'.",- "items": {"type": "object"},- },- },- "required": ["label"],- },- },- "caption": {- "type": "string",- "description": "One closing line under the picture. Optional.",- },- },- "required": ["title", "kind", "items"],- }-- def __init__(self, bus: Any) -> None:- self._bus = bus-- async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:- # A rejected spec is the model's to fix, so the error text is the- # validator's message verbatim — vague ones cost a wasted retry.- try:- spec = parse_spec(args or {}, source_utterance=_utterance(ctx))- except VisualSpecError as exc:- # Reported through the ToolResult's own error field, not a log call.- return ToolResult(success=False, output={"kind": args.get("kind")}, error=str(exc))-- try:- stored = store_visual(- render_visual_html(spec),- title=spec.title,- utterance=spec.source_utterance,- )- except OSError as exc:- # An unwritable archive is the machine's problem, not the model's:- # reported honestly rather than retried into the same wall.- log.warning("visualize_store_failed error=%s", exc)- return ToolResult(- success=False,- output={"title": spec.title},- error=f"The picture could not be saved: {exc}",- )-- # Publishing is best-effort on purpose: the picture EXISTS and is listed- # in the gallery either way, so a bus fault must not turn a successful- # render into a failed tool call the model then retries.- try:- await self._bus.publish(- NavigateSidebar(section="visualization", source_layer="brain.tool.visualize")- )- except Exception as exc: # noqa: BLE001 — see comment above- log.warning("visualize_navigate_failed error=%s", exc)-- return ToolResult(- success=True,- output={- "slug": stored.slug,- "artifact_path": stored.artifact_path,- "kind": spec.kind,- # The model reads this back to the user, so it says what was- # drawn and where it is — not that a file was written.- "summary": (- f"Drew '{spec.title}' as a {spec.kind} with {len(spec.items)} "- "items and opened it in the Visualization section."- ),- },- )---def _utterance(ctx: Any) -> str:- """What the user said this turn, when the context carries it.-- Used for the run label in the archive. Defensive across context shapes: the- label is decoration, and no picture should fail over a missing attribute.- """- for attribute in ("user_text", "utterance", "text"):- value = getattr(ctx, attribute, None)- if isinstance(value, str) and value.strip():- return value- if isinstance(ctx, dict):- for key in ("user_text", "utterance", "text"):- value = ctx.get(key)- if isinstance(value, str) and value.strip():- return value- return ""---__all__ = ["VisualizeTool"]diff --git a/jarvis/ui/web/artifact_view.py b/jarvis/ui/web/artifact_view.pyindex 4bf656d836..cd2483fd2c 100644--- a/jarvis/ui/web/artifact_view.py+++ b/jarvis/ui/web/artifact_view.py@@ -23,6 +23,29 @@ _MARKDOWN_EXT = (".md", ".markdown")# XSS from artifact content rendered in the app origin.VIEW_CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src data:;"+# The artifact-page CSP (``/files/{path}/page`` in outputs_routes): an artifact+# is a self-contained page a worker wrote to be LOOKED AT and used — tabs,+# filters, a chart drawn on canvas — so inline scripts run. What stays shut is+# every way out: no network of any kind (no fetch, no remote script, font,+# image or frame), no forms posting anywhere, no navigation. The frontend+# frames such a page with ``sandbox="allow-scripts"`` and WITHOUT+# ``allow-same-origin``, so the script runs in an opaque origin that cannot+# reach the app's cookies, storage or API — the same model Claude artifacts+# use. ``/view`` and inline downloads keep VIEW_CSP: those are arbitrary+# worker files, not artifacts.+ARTIFACT_PAGE_CSP = (+ "default-src 'none'; "+ "script-src 'unsafe-inline'; "+ "style-src 'unsafe-inline'; "+ "img-src data: blob:; "+ "font-src data:; "+ "media-src data: blob:; "+ "connect-src 'none'; "+ "form-action 'none'; "+ "frame-src 'none'; "+ "base-uri 'none';"+)+# Brand theme (matte black + signal yellow), kept in lockstep with the desktop# app's dark tokens (frontend/src/index.css) and video/src/intro/theme.ts. The# app is dark-first and this page opens from inside it, so it commits to the@@ -87,4 +110,4 @@ def render_artifact_html(filename: str, text: str) -> str:return _shell(filename, f"<pre>{html.escape(text)}</pre>")-__all__ = ["VIEW_CSP", "render_artifact_html"]+__all__ = ["ARTIFACT_PAGE_CSP", "VIEW_CSP", "render_artifact_html"]diff --git a/jarvis/ui/web/frontend/src/components/visualization/RunGraphPanel.test.tsx b/jarvis/ui/web/frontend/src/components/visualization/RunGraphPanel.test.tsxnew file mode 100644index 0000000000..da14cad98b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/visualization/RunGraphPanel.test.tsx@@ -0,0 +1,372 @@+/**+ * The run graph — a run drawn as a workflow, behind the Artifacts section's+ * "Run" tab since 2026-08-23 (it used to BE the section).+ *+ * 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,+ * - a failed step alarms from its card frame, not from a 6px dot alone,+ * - the inspector surfaces the archived timing (`duration_s`) of a step,+ * - zoom (ctrl+wheel, fit) and pan (drag on the background) behave.+ */+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 { RunGraphPanel } from "@/components/visualization/RunGraphPanel";+import type {+ ArtifactSummary,+ OutputSummary,+ PlanResponse,+} from "@/hooks/useOutputs";++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.clearAllMocks();+});++function installFetchMock(+ artifactsBySlug: Record<string, ArtifactSummary[]>,+ plansBySlug: Record<string, PlanResponse> = {},+) {+ 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 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]);+ return {+ ok: true,+ status: 200,+ json: async () => ({ files: artifactsBySlug[slug] ?? [] }),+ };+ }+ return { ok: true, status: 200, json: async () => ({}) };+ });+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++function renderPanel(run: OutputSummary) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },+ });+ return render(+ <QueryClientProvider client={client}>+ <RunGraphPanel run={run} />+ </QueryClientProvider>,+ );+}++function file(path: string, over: Partial<ArtifactSummary> = {}): ArtifactSummary {+ return {+ path,+ size: 2048,+ mtime: 1_700_000_000,+ is_text: false,+ preview: null,+ ...over,+ };+}++const RUN: OutputSummary = {+ slug: "run-new",+ utterance: "Draw the architecture",+ status: "success",+};++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",+ duration_s: 3.2,+ },+ {+ step_id: "t1:1",+ name: "out/diagram.svg",+ tool_name: "Write",+ status: "done",+ writes: ["out/diagram.svg"],+ },+ ],+ final_answer: "Architecture drawn.",+};++describe("RunGraphPanel", () => {+ it("draws the run as request → steps → result plus deliverables", async () => {+ installFetchMock(+ { "run-new": [file("tasks/t1/artifacts/files/out/diagram.svg")] },+ { "run-new": CHART_PLAN },+ );++ renderPanel(RUN);++ 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);+ });++ it("still graphs a pre-feature archive and admits the steps are gone", async () => {+ installFetchMock(+ { "run-old": [file("tasks/t1/artifacts/files/old-chart.png")] },+ // No plan entry -> the endpoint's stub contract {plan: null, steps: []}.+ );++ renderPanel({ slug: "run-old", utterance: "Summarise the logs", status: "unknown" });++ 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("opens the inspector with an image preview when a deliverable is clicked", async () => {+ installFetchMock(+ { "run-new": [file("tasks/t1/artifacts/files/out/diagram.svg")] },+ { "run-new": CHART_PLAN },+ );++ renderPanel(RUN);++ fireEvent.click(await screen.findByTestId("graph-node-artifact"));++ await screen.findByTestId("visualization-inspector");+ const image = await screen.findByTestId("visualization-image");+ expect(image.getAttribute("src")).toContain("diagram.svg");+ });++ it("frames a page deliverable inertly rather than drawing it as an image", async () => {+ installFetchMock({ "run-1": [file("tasks/t1/artifacts/files/report.html")] });++ renderPanel({ slug: "run-1", utterance: "Build a report", status: "success" });++ 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.+ expect(frame.getAttribute("sandbox")).toBe("");+ expect(screen.queryByTestId("visualization-image")).toBeNull();+ });++ it("shows a step's real call and output in the inspector", async () => {+ installFetchMock({ "run-new": [] }, { "run-new": CHART_PLAN });++ renderPanel(RUN);++ 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");+ // The archived timing is shown, not discarded.+ expect(inspector.textContent).toContain("3.2 s");+ });++ it("draws a reasoning step as a dashed thought card, text in the inspector", async () => {+ installFetchMock(+ { "run-think": [] },+ {+ "run-think": {+ plan: { plan_id: "run-think", vision: "Explain", status: "complete" },+ steps: [+ {+ step_id: "t1:0",+ name: "Check the logs first.",+ tool_name: null,+ kind: "reasoning",+ status: "done",+ output: "Check the logs first, then decide.",+ },+ { step_id: "t1:1", name: "tail app.log", tool_name: "Bash", status: "done" },+ ],+ final_answer: "Done.",+ },+ },+ );++ renderPanel({ slug: "run-think", utterance: "Explain the plan", status: "success" });++ const nodes = await screen.findAllByTestId("graph-node-step");+ const thought = nodes.find(+ (n) => n.getAttribute("data-category") === "reasoning",+ );+ expect(thought).toBeTruthy();+ // A thought is not an action — its card frame says so at a glance.+ expect(thought!.className).toContain("border-dashed");++ fireEvent.click(thought!);+ const inspector = await screen.findByTestId("visualization-inspector");+ // The full thought, not tool telemetry that never existed.+ expect(inspector.textContent).toContain("Check the logs first, then decide.");+ expect(inspector.textContent).not.toContain("Tool");+ });++ it("frames a failed step in the alarm colour, not just a dot", async () => {+ installFetchMock(+ { "run-bad": [] },+ {+ "run-bad": {+ plan: { plan_id: "run-bad", vision: "Deploy", status: "failed" },+ steps: [+ {+ step_id: "t1:0",+ name: "npm run deploy",+ tool_name: "Bash",+ status: "failed",+ error: "exit 1",+ },+ ],+ },+ },+ );++ renderPanel({ slug: "run-bad", utterance: "Deploy the site", status: "error" });++ const node = await screen.findByTestId("graph-node-step");+ expect(node.className).toContain("border-destructive");+ });++ it("offers a fit-to-view zoom next to the step buttons", async () => {+ installFetchMock({ "run-new": [] }, { "run-new": CHART_PLAN });++ renderPanel(RUN);++ // jsdom has no layout (clientWidth 0) — the fit guard must keep the+ // click a harmless no-op rather than zooming to nonsense.+ fireEvent.click(await screen.findByTestId("visualization-zoom-fit"));+ expect(screen.getByText("100%")).toBeTruthy();+ });++ it("zooms with ctrl+wheel and leaves plain scrolling alone", async () => {+ installFetchMock({ "run-new": [] }, { "run-new": CHART_PLAN });++ renderPanel(RUN);++ const canvas = await screen.findByTestId("visualization-canvas");+ // A bare wheel is scrolling, not zooming — it must stay untouched.+ fireEvent.wheel(canvas, { deltaY: -100 });+ expect(screen.getByText("100%")).toBeTruthy();+ // Ctrl+wheel (also how browsers deliver a trackpad pinch) zooms in.+ fireEvent.wheel(canvas, { deltaY: -100, ctrlKey: true });+ expect(screen.getByText("122%")).toBeTruthy();+ });++ it("pans the canvas with a pointer drag on the background", async () => {+ installFetchMock({ "run-new": [] }, { "run-new": CHART_PLAN });++ renderPanel(RUN);++ const canvas = await screen.findByTestId("visualization-canvas");+ // jsdom has no PointerEvent constructor — a MouseEvent under the pointer+ // event's name carries the coordinates the pan handlers read.+ fireEvent(+ canvas,+ new MouseEvent("pointerdown", { bubbles: true, clientX: 100, clientY: 90 }),+ );+ fireEvent(+ canvas,+ new MouseEvent("pointermove", { bubbles: true, clientX: 60, clientY: 70 }),+ );+ expect(canvas.scrollLeft).toBe(40);+ expect(canvas.scrollTop).toBe(20);++ // Releasing ends the pan: further movement no longer scrolls.+ fireEvent(canvas, new MouseEvent("pointerup", { bubbles: true }));+ fireEvent(+ canvas,+ new MouseEvent("pointermove", { bubbles: true, clientX: 0, clientY: 0 }),+ );+ expect(canvas.scrollLeft).toBe(40);+ });++ it("points every edge with an arrowhead, alarm-coloured after a failure", async () => {+ installFetchMock(+ { "run-new": [] },+ {+ "run-new": {+ plan: { plan_id: "run-new", vision: "Deploy it", status: "failed" },+ steps: [+ {+ step_id: "t1:0",+ name: "npm run deploy",+ tool_name: "Bash",+ status: "failed",+ error: "exit 1",+ },+ ],+ },+ },+ );++ renderPanel({ slug: "run-new", utterance: "Deploy it", status: "error" });++ await screen.findByTestId("graph-node-step");+ const edges = screen.getAllByTestId("graph-edge");+ expect(edges.length).toBeGreaterThan(0);+ // Since the track wraps, an edge can run back to the left — only a+ // pointed end keeps the flow readable, on every single edge.+ for (const edge of edges) {+ expect(edge.getAttribute("marker-end")).toMatch(/url\(#viz-arrow/);+ }+ // The edge into the failed step wears the alarm arrow, not the brand one.+ expect(+ edges.some(+ (e) => e.getAttribute("marker-end") === "url(#viz-arrow-failed)",+ ),+ ).toBe(true);+ });++ it("keeps a press on a node a click, never a pan", async () => {+ installFetchMock({ "run-new": [] }, { "run-new": CHART_PLAN });++ renderPanel(RUN);++ const canvas = await screen.findByTestId("visualization-canvas");+ const node = await screen.findByTestId("graph-node-start");+ fireEvent(+ node,+ new MouseEvent("pointerdown", { bubbles: true, clientX: 100, clientY: 90 }),+ );+ fireEvent(+ canvas,+ new MouseEvent("pointermove", { bubbles: true, clientX: 60, clientY: 70 }),+ );+ // The press began on a card, so the canvas never grabbed it…+ expect(canvas.scrollLeft).toBe(0);+ // …and the click still opens the inspector.+ fireEvent.click(node);+ await screen.findByTestId("visualization-inspector");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/visualization/RunGraphPanel.tsx b/jarvis/ui/web/frontend/src/components/visualization/RunGraphPanel.tsxnew file mode 100644index 0000000000..ca304d300b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/visualization/RunGraphPanel.tsx@@ -0,0 +1,927 @@+import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import {+ Download,+ ExternalLink,+ FolderOpen,+ Frame,+ Loader2,+ Maximize2,+ ShieldAlert,+ X,+ ZoomIn,+ ZoomOut,+} from "lucide-react";++import { Button } from "@/components/ui/button";+import { ScrollArea } from "@/components/ui/scroll-area";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";+import { openExternalUrl } from "@/lib/openExternal";+import {+ artifactDownloadUrl,+ revealArtifact,+ useArtifactsForOutput,+ useOutputsCapabilities,+ usePlanForOutput,+ type ArtifactSummary,+ type OutputSummary,+} from "@/hooks/useOutputs";+import { classifyVisual, visualUrl, type VisualKind } from "@/hooks/useVisualArtifacts";+import {+ buildRunGraph,+ edgePath,+ NODE_H,+ NODE_W,+ type RunGraph,+ type RunGraphNode,+} from "@/lib/runGraph";+import {+ categoryColor,+ categoryTint,+ NODE_CATEGORIES,+ nodeCategory,+ nodeGlyph,+} from "@/lib/nodeSpec";++/**+ * A run drawn as a workflow — the n8n-style node graph.+ *+ * 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".+ *+ * Until 2026-08-23 this WAS the Visualization section. Artifacts — the+ * pages a run produces — became the section's subject, and the graph moved+ * behind its "Run" tab: still one click away for whoever asks how a page+ * came to be, no longer in front of the page itself.+ *+ * It owns no data: steps come 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.+ */++/*+ * Zoom: the buttons snap to these steps, the wheel (Ctrl/⌘ + scroll, and the+ * trackpad pinch that browsers report the same way) moves continuously, and+ * "fit" produces whatever ratio the graph needs — so the step logic finds the+ * NEAREST step in the pressed direction rather than requiring an exact match.+ */+const ZOOM_STEPS = [0.25, 0.35, 0.5, 0.65, 0.8, 1, 1.25, 1.5] as const;+const MIN_ZOOM = ZOOM_STEPS[0];+const MAX_ZOOM = ZOOM_STEPS[ZOOM_STEPS.length - 1];++const clampZoom = (value: number): number =>+ Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, value));++const NODE_DOT: Record<string, string> = {+ done: "bg-emerald-400",+ failed: "bg-destructive",+ running: "bg-primary animate-pulse",+ skipped: "bg-muted-foreground/40",+};++/** 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`;+}++/** Human duration for a step — sub-second precision only where it matters. */+function formatDuration(seconds: number): string {+ if (seconds < 10) return `${seconds.toFixed(1)} s`;+ if (seconds < 60) return `${Math.round(seconds)} s`;+ const minutes = Math.floor(seconds / 60);+ const rest = Math.round(seconds % 60);+ return `${minutes} min ${rest} s`;+}++export function RunGraphPanel({ run }: { run: OutputSummary }) {+ const t = useT();+ const plan = usePlanForOutput(run.slug);+ const artifacts = useArtifactsForOutput(run.slug);+ const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);++ 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(() => {+ 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);+ /* Once the user has zoomed or panned by hand, the automatic fit keeps its+ * hands off until another run is selected — an explicit choice must never+ * be fought. */+ const userZoomed = useRef(false);+ const [canvasEl, setCanvasEl] = useState<HTMLDivElement | null>(null);++ /*+ * Anchored zoom: every zoom keeps ONE canvas point where it is on screen —+ * the cursor for the wheel, the viewport centre for the buttons. Without an+ * anchor the scale pivots on the canvas origin and the node being looked at+ * slides out of view. The anchor is recorded in content coordinates and the+ * scroll correction lands right after the rescaled canvas hits the DOM,+ * before paint — no one-frame jump.+ */+ const zoomRef = useRef(1);+ const zoomAnchor = useRef<{+ px: number;+ py: number;+ cx: number;+ cy: number;+ } | null>(null);++ useLayoutEffect(() => {+ zoomRef.current = zoom;+ const pending = zoomAnchor.current;+ if (pending === null || canvasEl === null) return;+ zoomAnchor.current = null;+ canvasEl.scrollLeft = pending.px * zoom - pending.cx;+ canvasEl.scrollTop = pending.py * zoom - pending.cy;+ }, [zoom, canvasEl]);++ /** Zoom to `next`, keeping the given viewport point (default: centre) put. */+ const zoomTo = useCallback(+ (next: number, at?: { cx: number; cy: number }) => {+ const clamped = clampZoom(next);+ const current = zoomRef.current;+ if (canvasEl !== null && clamped !== current) {+ const cx = at?.cx ?? canvasEl.clientWidth / 2;+ const cy = at?.cy ?? canvasEl.clientHeight / 2;+ zoomAnchor.current = {+ px: (canvasEl.scrollLeft + cx) / current,+ py: (canvasEl.scrollTop + cy) / current,+ cx,+ cy,+ };+ }+ setZoom(clamped);+ },+ [canvasEl],+ );++ const stepZoom = useCallback(+ (direction: 1 | -1) => {+ userZoomed.current = true;+ const current = zoomRef.current;+ const next =+ direction > 0+ ? (ZOOM_STEPS.find((s) => s > current + 0.001) ?? MAX_ZOOM)+ : ([...ZOOM_STEPS].reverse().find((s) => s < current - 0.001) ??+ Math.min(current, MIN_ZOOM));+ zoomTo(next);+ },+ [zoomTo],+ );++ /* Scale the whole story into the visible canvas — never above 100%, so a+ * two-node run stays a pair of cards instead of a pair of billboards. The+ * guard skips hidden/unmeasured hosts (detached warm-up, jsdom). */+ const fitZoom = useCallback(() => {+ if (canvasEl === null || graph === null) return;+ const { clientWidth, clientHeight } = canvasEl;+ if (clientWidth < 80 || clientHeight < 80) return;+ const scale = Math.min(+ (clientWidth - 16) / graph.width,+ (clientHeight - 16) / graph.height,+ 1,+ );+ // Fit means "show the whole story": the viewport returns to the origin,+ // by plain assignment (no pending anchor — fit IS the anchor decision).+ zoomAnchor.current = null;+ canvasEl.scrollLeft = 0;+ canvasEl.scrollTop = 0;+ setZoom(clampZoom(scale));+ }, [canvasEl, graph]);++ useEffect(() => {+ userZoomed.current = false;+ }, [run?.slug]);++ /* Auto-fit whenever the graph's extents change — the first paint, the plan+ * arriving a beat after the run list, and a live run growing new steps. */+ useEffect(() => {+ if (!userZoomed.current) fitZoom();+ }, [fitZoom, graph?.width, graph?.height]);++ /* Ctrl/⌘ + wheel zooms (that's also how browsers deliver a trackpad pinch).+ * Attached natively because React registers wheel listeners passively, and+ * a passive listener cannot preventDefault the browser's own page zoom. */+ useEffect(() => {+ if (canvasEl === null) return;+ const onWheel = (event: WheelEvent) => {+ if (!event.ctrlKey && !event.metaKey) return;+ event.preventDefault();+ userZoomed.current = true;+ const rect = canvasEl.getBoundingClientRect();+ zoomTo(zoomRef.current * Math.exp(-event.deltaY * 0.002), {+ cx: event.clientX - rect.left,+ cy: event.clientY - rect.top,+ });+ };+ canvasEl.addEventListener("wheel", onWheel, { passive: false });+ return () => canvasEl.removeEventListener("wheel", onWheel);+ }, [canvasEl, zoomTo]);++ /*+ * Drag-to-pan. The scroll container follows a held primary/middle button on+ * canvas background; a press on a node stays a click. Pointer capture keeps+ * a fast drag alive outside the canvas (guarded: jsdom has no capture API).+ */+ const [panning, setPanning] = useState(false);+ const panState = useRef<{+ pointerId: number;+ originX: number;+ originY: number;+ scrollLeft: number;+ scrollTop: number;+ } | null>(null);++ const onPanStart = useCallback(+ (event: React.PointerEvent<HTMLDivElement>) => {+ if (canvasEl === null) return;+ if (event.button !== 0 && event.button !== 1) return;+ if ((event.target as Element).closest("button") !== null) return;+ // Middle button would otherwise start the browser's own autoscroll.+ if (event.button === 1) event.preventDefault();+ panState.current = {+ pointerId: event.pointerId,+ originX: event.clientX,+ originY: event.clientY,+ scrollLeft: canvasEl.scrollLeft,+ scrollTop: canvasEl.scrollTop,+ };+ setPanning(true);+ // Capture keeps a fast drag alive outside the canvas. Guarded twice:+ // jsdom neither constructs PointerEvents (pointerId undefined) nor+ // accepts capture for a pointer it never saw.+ if (typeof event.pointerId === "number")+ canvasEl.setPointerCapture?.(event.pointerId);+ },+ [canvasEl],+ );++ const onPanMove = useCallback(+ (event: React.PointerEvent<HTMLDivElement>) => {+ const pan = panState.current;+ if (pan === null || canvasEl === null) return;+ const dx = event.clientX - pan.originX;+ const dy = event.clientY - pan.originY;+ // A real drag (not a sloppy click) is a viewport choice like a manual+ // zoom: the auto-fit stops following a live run's growth.+ if (Math.abs(dx) + Math.abs(dy) > 4) userZoomed.current = true;+ canvasEl.scrollLeft = pan.scrollLeft - dx;+ canvasEl.scrollTop = pan.scrollTop - dy;+ },+ [canvasEl],+ );++ const onPanEnd = useCallback(() => {+ const pan = panState.current;+ if (pan === null) return;+ panState.current = null;+ setPanning(false);+ if (typeof pan.pointerId === "number")+ canvasEl?.releasePointerCapture?.(pan.pointerId);+ }, [canvasEl]);++ return (+ <div className="flex min-h-0 flex-1" data-testid="run-graph-panel">+ <section className="flex min-h-0 min-w-0 flex-1 flex-col">+ {graph === null ? (+ <EmptyCanvas loading={plan.isLoading || artifacts.isLoading} />+ ) : (+ <>+ <div+ ref={setCanvasEl}+ className={cn(+ "min-h-0 flex-1 overflow-auto",+ panning ? "cursor-grabbing" : "cursor-grab",+ )}+ data-testid="visualization-canvas"+ onPointerDown={onPanStart}+ onPointerMove={onPanMove}+ onPointerUp={onPanEnd}+ onPointerCancel={onPanEnd}+ >+ <GraphCanvas+ graph={graph}+ zoom={zoom}+ selectedId={selectedNodeId}+ onSelect={setSelectedNodeId}+ />+ </div>++ <footer className="flex shrink-0 items-center gap-3 border-t border-border px-4 py-2">+ {/* 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={() => stepZoom(-1)}+ title={t("visualization.zoom_out")}+ aria-label={t("visualization.zoom_out")}+ >+ <ZoomOut className="h-3.5 w-3.5" aria-hidden />+ </Button>+ <button+ type="button"+ onClick={() => {+ userZoomed.current = true;+ zoomTo(1);+ }}+ title={t("visualization.zoom_reset")}+ aria-label={t("visualization.zoom_reset")}+ className="w-12 text-center text-[11px] tabular-nums text-muted-foreground transition-colors hover:text-foreground"+ >+ {`${Math.round(zoom * 100)}%`}+ </button>+ <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={() => {+ // An explicit fit re-arms the auto-fit: a live run that+ // grows new steps keeps fitting until zoomed by hand.+ userZoomed.current = false;+ fitZoom();+ }}+ title={t("visualization.zoom_fit")}+ aria-label={t("visualization.zoom_fit")}+ data-testid="visualization-zoom-fit"+ >+ <Maximize2 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 && (+ <NodeInspector+ node={selectedNode}+ slug={run.slug}+ onClose={() => setSelectedNodeId(null)}+ />+ )}+ </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+ >+ {/* Arrowheads. Since the track wraps, an edge can run back to the+ left — only a pointed end keeps the flow readable. markerUnits+ defaults to strokeWidth, so a highlighted edge's arrow grows+ with its stroke for free. refX=8 puts the tip exactly on the+ path end — the target card's port, drawn on the layer above. */}+ <defs>+ <marker+ id="viz-arrow"+ viewBox="0 0 8 8"+ refX="8"+ refY="4"+ markerWidth="5.5"+ markerHeight="5.5"+ orient="auto"+ >+ <path d="M 0 0 L 8 4 L 0 8 Z" className="fill-primary/70" />+ </marker>+ <marker+ id="viz-arrow-failed"+ viewBox="0 0 8 8"+ refX="8"+ refY="4"+ markerWidth="5.5"+ markerHeight="5.5"+ orient="auto"+ >+ <path d="M 0 0 L 8 4 L 0 8 Z" className="fill-destructive/80" />+ </marker>+ </defs>+ {graph.edges.map((edge) => {+ const from = byId.get(edge.from);+ const to = byId.get(edge.to);+ if (!from || !to) return null;+ /* The selected node's own edges brighten, so "what fed this and+ * what came of it" is answered by the picture, not by tracing. */+ const active =+ selectedId !== null &&+ (edge.from === selectedId || edge.to === selectedId);+ return (+ <path+ key={edge.id}+ data-testid="graph-edge"+ d={edgePath(from, to)}+ fill="none"+ strokeWidth={active ? 2.5 : 1.5}+ markerEnd={`url(#${edge.failed ? "viz-arrow-failed" : "viz-arrow"})`}+ className={+ edge.failed+ ? active+ ? "stroke-destructive"+ : "stroke-destructive/70"+ : active+ ? "stroke-primary"+ : "stroke-primary/50"+ }+ />+ );+ })}+ </svg>++ {graph.nodes.map((node) => {+ const category = nodeCategory(node);+ const Icon = nodeGlyph(node);+ const hue = categoryColor(category);+ const selected = node.id === selectedId;+ const reasoning = category === "reasoning";+ /* Two calm lines per card. A reasoning card is titled as what it+ * IS, with the thought as its detail line — a raw sentence as a+ * bold headline reads like a rendering accident. */+ const title =+ node.kind === "start"+ ? t("visualization.node_start")+ : node.kind === "result"+ ? t("visualization.node_result")+ : reasoning+ ? t("visualization.cat_reasoning")+ : node.title;+ const subtitle =+ node.kind === "start"+ ? node.title+ : reasoning+ ? node.title+ : node.subtitle;+ /* Port dots come from the graph model (edge-derived), so a dot is+ * always a real attachment point — a start node has no input, a+ * deliverable no output, exactly like a workflow editor's nodes. */+ const port =+ "absolute h-1.5 w-1.5 rounded-full border border-background bg-primary/70";+ return (+ <button+ key={node.id}+ type="button"+ onClick={() => onSelect(node.id)}+ aria-current={selected}+ data-testid={`graph-node-${node.kind}`}+ data-category={category}+ 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",+ /* A thought is not an action: reasoning cards wear a dashed+ * frame, the visual grammar of "internal, produced nothing". */+ reasoning && "border-dashed",+ /* A failed or running step announces itself from the card+ * frame — a 6px dot alone is not a glanceable alarm. */+ selected+ ? "border-primary ring-1 ring-primary/40"+ : node.status === "failed"+ ? "border-destructive/70 hover:border-destructive"+ : node.status === "running"+ ? "border-primary/60 hover:border-primary"+ : "border-border hover:border-primary/50",+ )}+ >+ {node.ports.left && (+ <span+ className={cn(port, "-left-[3px] top-1/2 -translate-y-1/2")}+ aria-hidden+ />+ )}+ {node.ports.right &&+ (category === "agent" ? (+ /* A spawn node branches — its output port doubles, the way+ * n8n's if node wears one connector per outcome. */+ <>+ <span+ className={cn(port, "-right-[3px] top-1/2 -translate-y-[7px]")}+ aria-hidden+ />+ <span+ className={cn(port, "-right-[3px] top-1/2 translate-y-[1px]")}+ aria-hidden+ />+ </>+ ) : (+ <span+ className={cn(port, "-right-[3px] top-1/2 -translate-y-1/2")}+ aria-hidden+ />+ ))}+ {node.ports.top && (+ <span+ className={cn(port, "-top-[3px] left-1/2 -translate-x-1/2")}+ aria-hidden+ />+ )}+ {node.ports.bottom && (+ <span+ className={cn(port, "-bottom-[3px] left-1/2 -translate-x-1/2")}+ aria-hidden+ />+ )}+ {/* The category speaks through the icon alone — its hue and+ glyph — never through an extra text line. The label survives+ as the tile's tooltip for whoever hovers to ask. */}+ <span+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg"+ style={{ color: hue, backgroundColor: categoryTint(category, 0.12) }}+ title={t(NODE_CATEGORIES[category].labelKey)}+ >+ <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" && !reasoning && (+ <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">+ {/* A reasoning step is a thought, not a call: it gets the thought+ text and nothing pretending to be tool telemetry. */}+ {node.kind === "step" && node.step?.kind === "reasoning" && (+ <InspectorField label={t("visualization.field_thought")}>+ <p className="whitespace-pre-wrap break-words text-xs">+ {node.step.output || node.step.name}+ </p>+ </InspectorField>+ )}++ {node.kind === "step" && node.step && node.step.kind !== "reasoning" && (+ <>+ <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>+ {typeof node.step.duration_s === "number" &&+ node.step.duration_s > 0 && (+ <InspectorField label={t("visualization.field_duration")}>+ {formatDuration(node.step.duration_s)}+ </InspectorField>+ )}+ {/* One attempt is the norm — only a retry is worth a line. */}+ {(node.step.attempts ?? 1) > 1 && (+ <InspectorField label={t("visualization.field_attempts")}>+ {String(node.step.attempts)}+ </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 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.+ */+function ArtifactPreview({+ slug,+ artifact,+ kind,+}: {+ slug: string;+ artifact: ArtifactSummary;+ kind: VisualKind;+}) {+ const t = useT();+ 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={url}+ alt={artifact.path}+ data-testid="visualization-image"+ onError={() => setFailed(true)}+ className="max-h-72 w-full rounded-md border border-border bg-background/40 object-contain"+ />+ );+ }++ return (+ <div className="space-y-1.5">+ <iframe+ src={url}+ title={artifact.path}+ data-testid="visualization-frame"+ 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="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 />+ {t("visualization.sandbox_note")}+ </p>+ </div>+ );+}++/* ------------------------------------------------------------------------- */++function EmptyCanvas({ loading }: { loading: boolean }) {+ const t = useT();+ 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 ? (+ <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="max-w-sm text-xs text-muted-foreground">+ {t("visualization.no_steps")}+ </p>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts b/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.tsindex 42ecae4160..ab4c4d8249 100644--- a/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts+++ b/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts@@ -1,13 +1,12 @@/**- * The visual artifacts a run left behind — the data behind the Visualization- * section.+ * The artifacts a run left behind — the data behind the Artifacts 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.+ * about pages and 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@@ -21,11 +20,12 @@ import {useOutputsList,type ArtifactSummary,type ArtifactsResponse,+ type OutputStatus,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" | "map";+export type VisualKind = "image" | "vector" | "page" | "document";/*** Extension → kind. Deliberately narrow: everything here must render inside the@@ -62,14 +62,22 @@ export interface VisualArtifact {slug: string;/** What the user asked for, when the run recorded it. */utterance?: string;+ /** The run's status — a page from a run that failed its review still shows. */+ status?: OutputStatus;/** Artifact path relative to the run directory. */path: string;- /** Last path segment — what the tile is labelled with. */+ /** Last path segment — the fallback label. */name: string;+ /**+ * What the rail calls it: a page's own `<title>` when the listing's preview+ * carries one, otherwise the filename. The title is what the user asked for+ * in their words ("Umsatz-Dashboard"), the filename is its slug.+ */+ title: string;kind: VisualKind;size: number;mtime: number;- /** Ready-to-use `src` for an `<img>`/`<iframe>` (served inline). */+ /** Ready-to-use `src` for an `<img>`/`<iframe>` (served inline, no scripts). */url: string;}@@ -94,50 +102,61 @@ export function visualUrl(slug: string, path: string): string {)}/download?disposition=inline`;}+/**+ * The ARTIFACT PAGE url of an HTML deliverable: served with scripts allowed+ * and every network path shut (`ARTIFACT_PAGE_CSP`, outputs_routes.py). The+ * stage frames it with `sandbox="allow-scripts"` and no same-origin, so the+ * page's own JavaScript runs — a dashboard filters, a chart draws — inside an+ * opaque origin that cannot reach the app. Non-HTML files keep `visualUrl`.+ */+export function artifactPageUrl(slug: string, path: string): string {+ return `/api/outputs/${encodeURIComponent(slug)}/files/${encodeArtifactPath(path)}/page`;+}+/** 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}`;}-/**- * The synthetic path of a run's mission map. Real deliverable paths always- * start with `tasks/`, so this can never collide with a listed file.- */-export const MISSION_MAP_PATH = "::mission-map::";-/** The server-rendered node-graph page for one run (no JS, brand-themed). */export function missionMapUrl(slug: string): string {return `/api/outputs/${encodeURIComponent(slug)}/graph`;}+const TITLE_RE = /<title[^>]*>([\s\S]*?)<\/title>/i;++/** A page's `<title>` from the listing's text preview, or null. */+export function pageTitleFromPreview(preview: string | null | undefined): string | null {+ if (!preview) return null;+ const match = TITLE_RE.exec(preview);+ if (!match) return null;+ const title = match[1].replace(/\s+/g, " ").trim();+ return title.length > 0 ? decodeEntities(title) : null;+}++/** The handful of entities a `<title>` realistically carries. */+function decodeEntities(text: string): string {+ return text+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, '"')+ .replace(/'|'/g, "'");+}+function toVisuals(run: OutputSummary, files: ArtifactSummary[]): VisualArtifact[] {- // Every successfully listed run leads with its mission map — the n8n-style- // node graph of what ran and what came out. It shares the run's newest- // mtime, and the stable sort below keeps it AHEAD of that file, so opening- // the section stages the newest run's map: the overview first, then its- // pictures. A run whose deliverables are all text still gets a visual this- // way, which is precisely when "what happened" needs drawing the most.- const newest = files.reduce((max, file) => Math.max(max, file.mtime), 0);- const visuals: VisualArtifact[] = [- {- slug: run.slug,- utterance: run.utterance,- path: MISSION_MAP_PATH,- name: "Mission map", // display label is localized in the view- kind: "map",- size: 0,- mtime: newest,- url: missionMapUrl(run.slug),- },- ];+ const visuals: VisualArtifact[] = [];for (const file of files) {const kind = classifyVisual(file.path);if (kind === null) continue;+ const name = file.path.split("/").pop() ?? file.path;visuals.push({slug: run.slug,utterance: run.utterance,+ status: run.status,path: file.path,- name: file.path.split("/").pop() ?? file.path,+ name,+ title: (kind === "page" ? pageTitleFromPreview(file.preview) : null) ?? name,kind,size: file.size,mtime: file.mtime,@@ -189,10 +208,13 @@ export function useVisualArtifacts(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,+ // No poll for finished runs: a gallery that re-listed ten run+ // directories every few seconds would keep a disk busy for pages that+ // never change. A RUNNING run is the exception — its artifact is the+ // thing the user is waiting for, so that one listing follows the build+ // and the page appears the moment the worker archives it.+ staleTime: run.status === "running" ? 0 : 30_000,+ refetchInterval: run.status === "running" ? 4_000 : false,})),combine: (results) => {const visuals = results.flatMap((result, index) =>diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 93636c0817..12b7b2b1e4 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -80,7 +80,7 @@"tasks": "Aufgaben","sessions": "Transkription","run_inspector": "Run Inspector",- "visualization": "Visualisierung",+ "visualization": "Artefakte","clis": "CLIs","cli_test_hub": "CLI Test Hub","clis_hub": "CLIs & CLI Test Hub",@@ -4452,13 +4452,23 @@"hide_original": "Original ausblenden"},"visualization": {- "title": "Visualisierung",- "subtitle": "Jeder Durchlauf als Workflow gezeichnet: was lief, was er tat, was dabei herauskam",+ "title": "Artefakte",+ "subtitle": "Die Seiten und Bilder, die deine Durchläufe erzeugt haben — in voller Größe, Quelltext und Durchlauf einen Tab entfernt","refresh": "Aktualisieren",- "runs": "Durchläufe",- "run_meta": "{0} Ergebnisdateien",- "empty_title": "Noch nichts zu sehen",- "empty_body": "Sobald ein Durchlauf archiviert ist, erscheint er hier als Graph: die Anfrage, jeder Werkzeug-Schritt und die erzeugten Dateien.",+ "rail": "Artefakte",+ "building": "Wird gebaut …",+ "building_title": "„{0}“ wird gebaut",+ "building_body": "Ein Hintergrund-Agent schreibt die Seite gerade. Sie erscheint hier, sobald sie fertig ist — meist innerhalb von ein bis zwei Minuten.",+ "older_not_scanned": "Hier werden nur die neuesten {0} Durchläufe durchsucht — das ganze Archiv findest du unter Ausgaben.",+ "tab_preview": "Vorschau",+ "tab_code": "Code",+ "tab_run": "Durchlauf",+ "stage_tabs": "Ansicht dieses Artefakts",+ "open_external_hint": "Öffnet dieses Artefakt im Browser — ganzes Fenster, teilbar, druckbar.",+ "page_sandbox_note": "Läuft in einer Sandbox: die Skripte der Seite funktionieren, das Netzwerk ist aus.",+ "source_failed": "Der Quelltext dieses Artefakts konnte nicht gelesen werden.",+ "empty_title": "Noch keine Artefakte",+ "empty_body": "Bitte um eins — „visualisier mir das“, „mach ein Dashboard daraus“, „bau mir ein Artefakt“ — und die Seite erscheint hier, sobald der Agent sie geschrieben hat.","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: der Durchlauf Schritt für Schritt — Gedanken, Aktionen, Sub-Agenten, Ergebnis. Untere Spur: die Dateien, die er hinterließ. Klick auf einen Knoten, um ihn zu inspizieren.",@@ -4502,12 +4512,12 @@"zoom_out": "Verkleinern","zoom_reset": "Zoom auf 100% zurücksetzen","zoom_fit": "Ganzen Durchlauf einpassen",- "open_external": "Öffnen",+ "open_external": "Im Browser ö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 als Graph, was die letzten Durchläufe getan und erzeugt haben."+ "open_from_agent": "Artefakte",+ "open_from_agent_hint": "Zeigt die Seiten und Bilder, die die letzten Durchläufe erzeugt haben."},"marketplace_origin": {"badge": "Marketplace",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex cfa39b4d57..ec6f9202b1 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -80,7 +80,7 @@"tasks": "Tasks","sessions": "Transcription","run_inspector": "Run Inspector",- "visualization": "Visualization",+ "visualization": "Artifacts","clis": "CLIs","cli_test_hub": "CLI Test Hub","clis_hub": "CLIs & CLI Test Hub",@@ -4452,13 +4452,23 @@"hide_original": "Hide the original"},"visualization": {- "title": "Visualization",- "subtitle": "Every run drawn as a workflow: what ran, what it did, what came out",+ "title": "Artifacts",+ "subtitle": "The pages and pictures your runs produced — full-size, with the source and the run one tab away","refresh": "Refresh",- "runs": "Runs",- "run_meta": "{0} deliverables",- "empty_title": "Nothing to show yet",- "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.",+ "rail": "Artifacts",+ "building": "Building…",+ "building_title": "Building “{0}”",+ "building_body": "A background agent is writing the page. It appears here the moment it is done — usually within a minute or two.",+ "older_not_scanned": "Only the newest {0} runs are scanned here — open Outputs for the full archive.",+ "tab_preview": "Preview",+ "tab_code": "Code",+ "tab_run": "Run",+ "stage_tabs": "How to view this artifact",+ "open_external_hint": "Open this artifact in your browser — full window, shareable, printable.",+ "page_sandbox_note": "Runs in a sandbox: the page's own scripts work, the network is off.",+ "source_failed": "The source of this artifact could not be read.",+ "empty_title": "No artifacts yet",+ "empty_body": "Ask for one — “visualize this”, “make a dashboard of it”, “build me an artifact” — and the page appears here as soon as the agent has written it.","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: the run step by step — thoughts, actions, sub-agents, result. Bottom track: the files it left behind. Click a node to inspect it.",@@ -4502,12 +4512,12 @@"zoom_out": "Zoom out","zoom_reset": "Reset zoom to 100%","zoom_fit": "Fit the whole run into view",- "open_external": "Open",+ "open_external": "Open in browser","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 what the latest runs did and produced, as a graph."+ "open_from_agent": "Artifacts",+ "open_from_agent_hint": "Show the pages and pictures the latest runs produced."},"marketplace_origin": {"badge": "Marketplace",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 543c870ad4..39ec27223b 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -80,7 +80,7 @@"tasks": "Tareas","sessions": "Transcripción","run_inspector": "Run Inspector",- "visualization": "Visualización",+ "visualization": "Artefactos","clis": "CLIs","cli_test_hub": "CLI Test Hub","clis_hub": "CLIs & CLI Test Hub",@@ -4452,13 +4452,23 @@"hide_original": "Ocultar el original"},"visualization": {- "title": "Visualización",- "subtitle": "Cada ejecución dibujada como un flujo: qué corrió, qué hizo y qué produjo",+ "title": "Artefactos",+ "subtitle": "Las páginas e imágenes que produjeron tus ejecuciones — a tamaño completo, con el código y la ejecución a una pestaña de distancia","refresh": "Actualizar",- "runs": "Ejecuciones",- "run_meta": "{0} archivos producidos",- "empty_title": "Todavía no hay nada que mostrar",- "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.",+ "rail": "Artefactos",+ "building": "Creando…",+ "building_title": "Creando «{0}»",+ "building_body": "Un agente en segundo plano está escribiendo la página. Aparecerá aquí en cuanto termine — normalmente en uno o dos minutos.",+ "older_not_scanned": "Aquí solo se revisan las {0} ejecuciones más recientes — abre Salidas para ver todo el archivo.",+ "tab_preview": "Vista previa",+ "tab_code": "Código",+ "tab_run": "Ejecución",+ "stage_tabs": "Cómo ver este artefacto",+ "open_external_hint": "Abre este artefacto en el navegador — ventana completa, se puede compartir e imprimir.",+ "page_sandbox_note": "Se ejecuta en un entorno aislado: los scripts de la página funcionan, la red está desactivada.",+ "source_failed": "No se pudo leer el código de este artefacto.",+ "empty_title": "Todavía no hay artefactos",+ "empty_body": "Pide uno — «visualízame esto», «haz un panel con ello», «créame un artefacto» — y la página aparecerá aquí en cuanto el agente la haya escrito.","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: la ejecución paso a paso — pensamientos, acciones, subagentes, resultado. Pista inferior: los archivos que dejó. Haz clic en un nodo para inspeccionarlo.",@@ -4502,12 +4512,12 @@"zoom_out": "Alejar","zoom_reset": "Restablecer el zoom al 100%","zoom_fit": "Ajustar toda la ejecución a la vista",- "open_external": "Abrir",+ "open_external": "Abrir en el navegador","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 como grafo lo que hicieron y produjeron las últimas ejecuciones."+ "open_from_agent": "Artefactos",+ "open_from_agent_hint": "Muestra las páginas e imágenes que produjeron las últimas ejecuciones."},"marketplace_origin": {"badge": "Marketplace",diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsxindex 979f667016..91d6c22344 100644--- a/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx@@ -1,26 +1,30 @@/**- * The Visualization section — the run graph it draws, what it admits, and- * what a node click reveals.+ * The Artifacts section — every page and picture a run produced, full-size.** 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`),- * - a failed step alarms from its card frame, not from a 6px dot alone,- * - the inspector surfaces the archived timing (`duration_s`) of a step.+ * - the newest artifact is on stage when the section opens; the rail lists+ * every artifact newest-first and labels a page by its own <title>,+ * - a PAGE is framed from `/page` with `sandbox="allow-scripts"` and no+ * same-origin (its scripts run, the app stays out of reach); an image goes+ * through <img>; a PDF through an empty sandbox,+ * - "Code" shows the page's source, "Run" the node graph of the run that made+ * it — the graph is one tab away, never in front of the page,+ * - a `create_artifact` mission still running shows as a "building…" row and+ * stage, recognised by the brief's "Artifact:" lead line,+ * - `?run=<slug>` pre-selects that run's artifact; a click wins over newest,+ * - only files the WebView can draw are offered (`classifyVisual`).*/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 { VisualizationView, parseArtifactUtterance } from "@/views/VisualizationView";+import {+ classifyVisual,+ pageTitleFromPreview,+ visualUrl,+} from "@/hooks/useVisualArtifacts";import type {ArtifactSummary,OutputSummary,@@ -43,6 +47,7 @@ function installFetchMock(runs: OutputSummary[],artifactsBySlug: Record<string, ArtifactSummary[]>,plansBySlug: Record<string, PlanResponse> = {},+ rawBySlug: Record<string, string> = {},) {const fetchMock = vi.fn(async (input: RequestInfo | URL) => {const url = String(input);@@ -62,6 +67,20 @@ function installFetchMock(json: async () => plansBySlug[slug] ?? { plan: null, steps: [] },};}+ const raw = /\/api\/outputs\/([^/]+)\/files\/.+\/raw/.exec(url);+ if (raw) {+ const slug = decodeURIComponent(raw[1]);+ return {+ ok: true,+ status: 200,+ json: async () => ({+ path: "x",+ size: 1,+ text: rawBySlug[slug] ?? "",+ truncated: false,+ }),+ };+ }const artifacts = /\/api\/outputs\/([^/]+)\/artifacts/.exec(url);if (artifacts) {const slug = decodeURIComponent(artifacts[1]);@@ -102,232 +121,201 @@ 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",- duration_s: 3.2,- },- {- step_id: "t1:1",- name: "out/diagram.svg",- tool_name: "Write",- status: "done",- writes: ["out/diagram.svg"],- },- ],- final_answer: "Architecture drawn.",+const DASH_HTML =+ "<!doctype html><html><head><title>Umsatz-Dashboard</title></head>" ++ "<body><script>document.title='x'</script></body></html>";++const ARTIFACT_UTTERANCE =+ "Artifact: Umsatz-Dashboard\nUmsatz pro Monat 2026 als Balken.\n\n## What to build\n…";++const DASH_RUN: OutputSummary = {+ slug: "mission_dash",+ utterance: ARTIFACT_UTTERANCE,+ status: "success",};+const DASH_FILE = file("tasks/t1/artifacts/files/umsatz-dashboard.html", {+ is_text: true,+ preview: DASH_HTML,+ mtime: 1_700_000_900,+});+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("a/b/chart.PNG")).toBe("image");+ expect(classifyVisual("x.svg")).toBe("vector");expect(classifyVisual("report.html")).toBe("page");- expect(classifyVisual("paper.pdf")).toBe("document");+ expect(classifyVisual("deck.pdf")).toBe("document");});it("rejects everything else, however data-shaped", () => {- // 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();- }+ expect(classifyVisual("data.json")).toBeNull();+ expect(classifyVisual("notes.md")).toBeNull();+ expect(classifyVisual("archive.zip")).toBeNull();+ expect(classifyVisual("noext")).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("draws the newest run as request → steps → result plus deliverables", 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 },+ expect(visualUrl("run-1", "tasks/t/artifacts/files/chart#2.png")).toContain(+ "chart%232.png",);-- renderView();-- 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();});+});- 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: []}.- );-- 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/);+describe("pageTitleFromPreview", () => {+ it("reads a page's own title and decodes the common entities", () => {+ expect(pageTitleFromPreview(DASH_HTML)).toBe("Umsatz-Dashboard");+ expect(pageTitleFromPreview("<title> A & B\n </title>")).toBe("A & B");+ expect(pageTitleFromPreview("<html><body>no title</body></html>")).toBeNull();+ expect(pageTitleFromPreview(null)).toBeNull();});+});- 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();-- fireEvent.click(await screen.findByTestId("graph-node-artifact"));-- await screen.findByTestId("visualization-inspector");- const image = await screen.findByTestId("visualization-image");- expect(image.getAttribute("src")).toContain("diagram.svg");+describe("parseArtifactUtterance", () => {+ it("recognises the brief's lead line and returns title + request", () => {+ expect(parseArtifactUtterance(ARTIFACT_UTTERANCE)).toEqual({+ title: "Umsatz-Dashboard",+ request: "Umsatz pro Monat 2026 als Balken.",+ });+ expect(parseArtifactUtterance("Build a flask app")).toBeNull();+ expect(parseArtifactUtterance(undefined)).toBeNull();});+});- 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")] },- );+describe("VisualizationView", () => {+ it("stages the newest artifact full-size, labelled by its page title", async () => {+ installFetchMock([DASH_RUN], { mission_dash: [DASH_FILE] });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.- expect(frame.getAttribute("sandbox")).toBe("");- expect(screen.queryByTestId("visualization-image")).toBeNull();+ // The artifact-page route: scripts allowed server-side …+ expect(frame.getAttribute("src")).toContain("/files/tasks/t1/artifacts/files/umsatz-dashboard.html/page");+ // … and client-side the page runs in an opaque origin — scripts yes,+ // same-origin never.+ expect(frame.getAttribute("sandbox")).toBe("allow-scripts");+ expect(screen.getByTestId("visualization-title").textContent).toBe("Umsatz-Dashboard");+ // The rail row carries the same title, not the filename.+ const rows = screen.getAllByTestId("visualization-artifact-row");+ expect(rows).toHaveLength(1);+ expect(rows[0].textContent).toContain("Umsatz-Dashboard");+ expect(rows[0].textContent).toContain("Umsatz pro Monat 2026 als Balken.");+ // The run graph is a tab away, not on stage.+ expect(screen.queryByTestId("graph-node-start")).toBeNull();});- it("shows a step's real call and output in the inspector", async () => {+ it("lists every artifact newest-first and switches on click", async () => {installFetchMock(- [{ slug: "run-new", utterance: "Draw the architecture", status: "success" }],- { "run-new": [] },- { "run-new": CHART_PLAN },+ [+ { slug: "run-a", utterance: "Draw the architecture", status: "success" },+ { slug: "run-b", utterance: "Summarise", status: "success" },+ ],+ {+ "run-a": [file("tasks/t1/artifacts/files/diagram.svg", { mtime: 1_700_000_500 })],+ "run-b": [file("tasks/t1/artifacts/files/old-chart.png", { mtime: 1_700_000_100 })],+ },);renderView();- 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");- // The archived timing is shown, not discarded.- expect(inspector.textContent).toContain("3.2 s");+ const rows = await screen.findAllByTestId("visualization-artifact-row");+ expect(rows.map((r) => r.textContent)).toEqual([+ expect.stringContaining("diagram.svg"),+ expect.stringContaining("old-chart.png"),+ ]);+ // Newest on stage first …+ expect((await screen.findByTestId("visualization-image")).getAttribute("src")).toContain(+ "diagram.svg",+ );+ // … a click moves to the older one.+ fireEvent.click(rows[1]);+ await waitFor(() =>+ expect(screen.getByTestId("visualization-image").getAttribute("src")).toContain(+ "old-chart.png",+ ),+ );});- it("draws a reasoning step as a dashed thought card, text in the inspector", async () => {+ it("shows the source under Code and the run graph under Run", async () => {installFetchMock(- [{ slug: "run-think", utterance: "Explain the plan", status: "success" }],- { "run-think": [] },+ [DASH_RUN],+ { mission_dash: [DASH_FILE] },{- "run-think": {- plan: { plan_id: "run-think", vision: "Explain", status: "complete" },+ mission_dash: {+ plan: { plan_id: "mission_dash", vision: "Build it", status: "complete" },steps: [- {- step_id: "t1:0",- name: "Check the logs first.",- tool_name: null,- kind: "reasoning",- status: "done",- output: "Check the logs first, then decide.",- },- { step_id: "t1:1", name: "tail app.log", tool_name: "Bash", status: "done" },+ { step_id: "t1:0", name: "umsatz-dashboard.html", tool_name: "Write", status: "done" },],final_answer: "Done.",},},+ { mission_dash: DASH_HTML },);renderView();+ await screen.findByTestId("visualization-frame");- const nodes = await screen.findAllByTestId("graph-node-step");- const thought = nodes.find(- (n) => n.getAttribute("data-category") === "reasoning",- );- expect(thought).toBeTruthy();- // A thought is not an action — its card frame says so at a glance.- expect(thought!.className).toContain("border-dashed");-- fireEvent.click(thought!);- const inspector = await screen.findByTestId("visualization-inspector");- // The full thought, not tool telemetry that never existed.- expect(inspector.textContent).toContain("Check the logs first, then decide.");- expect(inspector.textContent).not.toContain("Tool");+ fireEvent.click(screen.getByTestId("visualization-tab-code"));+ const source = await screen.findByTestId("visualization-source");+ expect(source.textContent).toContain("<title>Umsatz-Dashboard</title>");+ expect(screen.queryByTestId("visualization-frame")).toBeNull();++ fireEvent.click(screen.getByTestId("visualization-tab-run"));+ await screen.findByTestId("graph-node-start");+ await screen.findByTestId("graph-node-step");+ // The no-JS mission map stays one click away from the graph.+ expect(screen.getByTestId("visualization-open-map")).toBeTruthy();++ fireEvent.click(screen.getByTestId("visualization-tab-preview"));+ await screen.findByTestId("visualization-frame");});- it("frames a failed step in the alarm colour, not just a dot", async () => {+ it("frames a PDF in an empty sandbox and draws an image through <img>", async () => {installFetchMock(- [{ slug: "run-bad", utterance: "Deploy the site", status: "error" }],- { "run-bad": [] },+ [{ slug: "run-1", utterance: "Export", status: "success" }],{- "run-bad": {- plan: { plan_id: "run-bad", vision: "Deploy", status: "failed" },- steps: [- {- step_id: "t1:0",- name: "npm run deploy",- tool_name: "Bash",- status: "failed",- error: "exit 1",- },- ],- },+ "run-1": [+ file("tasks/t1/artifacts/files/deck.pdf", { mtime: 1_700_000_200 }),+ file("tasks/t1/artifacts/files/cover.png", { mtime: 1_700_000_100 }),+ ],},);renderView();- const node = await screen.findByTestId("graph-node-step");- expect(node.className).toContain("border-destructive");- });-- it("offers a fit-to-view zoom next to the step buttons", 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("sandbox")).toBe("");+ expect(frame.getAttribute("src")).toContain("deck.pdf");+ // No Code tab for a PDF — there is no source to show.+ expect(screen.queryByTestId("visualization-tab-code")).toBeNull();- // jsdom has no layout (clientWidth 0) — the fit guard must keep the- // click a harmless no-op rather than zooming to nonsense.- fireEvent.click(await screen.findByTestId("visualization-zoom-fit"));- expect(screen.getByText("100%")).toBeTruthy();+ fireEvent.click(screen.getAllByTestId("visualization-artifact-row")[1]);+ const image = await screen.findByTestId("visualization-image");+ expect(image.getAttribute("src")).toContain("cover.png");});- it("keeps the server-rendered mission map one click away", async () => {+ it("shows a running artifact build as a row and a stage until the page lands", async () => {installFetchMock(- [{ slug: "run-new", utterance: "Draw the architecture", status: "success" }],- { "run-new": [] },- { "run-new": CHART_PLAN },+ [+ { slug: "mission_building", utterance: ARTIFACT_UTTERANCE, status: "running" },+ { slug: "mission_other", utterance: "Refactor the parser", status: "running" },+ DASH_RUN,+ ],+ { mission_building: [], mission_other: [], mission_dash: [DASH_FILE] },);renderView();- // The no-JS sibling of this canvas — shareable, printable, CSP-inert.- await screen.findByTestId("visualization-open-map");+ // Only the artifact build shows as building — an unrelated running+ // mission is not posing as a page in the making.+ const building = await screen.findAllByTestId("visualization-building-row");+ expect(building).toHaveLength(1);+ expect(building[0].textContent).toContain("Umsatz-Dashboard");+ // With nothing picked, the newest build is what the stage shows.+ await screen.findByTestId("visualization-building");+ // The finished artifact is still in the rail, one click away.+ fireEvent.click(screen.getByTestId("visualization-artifact-row"));+ await screen.findByTestId("visualization-frame");});it("pre-selects the run named by ?run= in the URL", async () => {@@ -336,142 +324,34 @@ describe("VisualizationView", () => {{ slug: "run-new", utterance: "Draw the architecture", status: "success" },{ slug: "run-old", utterance: "Summarise the logs", status: "success" },],- { "run-new": [], "run-old": [] },- { "run-new": CHART_PLAN },+ {+ "run-new": [file("tasks/t1/artifacts/files/new.svg", { mtime: 1_700_000_900 })],+ "run-old": [file("tasks/t1/artifacts/files/old.png", { mtime: 1_700_000_100 })],+ },);window.history.replaceState(null, "", "/?view=visualization&run=run-old");try {renderView();// The deep-linked run wins over the newest-first default.- const start = await screen.findByTestId("graph-node-start");- expect(start.textContent).toContain("Summarise the logs");+ const image = await screen.findByTestId("visualization-image");+ expect(image.getAttribute("src")).toContain("old.png");} finally {window.history.replaceState(null, "", "/");}});- it("says so when there are no runs at all", async () => {- installFetchMock([], {});-- renderView();-- await screen.findByTestId("visualization-empty");- expect(screen.queryByTestId("visualization-canvas")).toBeNull();- });-- it("zooms with ctrl+wheel and leaves plain scrolling alone", async () => {- installFetchMock(- [{ slug: "run-new", utterance: "Draw the architecture", status: "success" }],- { "run-new": [] },- { "run-new": CHART_PLAN },- );-- renderView();-- const canvas = await screen.findByTestId("visualization-canvas");- // A bare wheel is scrolling, not zooming — it must stay untouched.- fireEvent.wheel(canvas, { deltaY: -100 });- expect(screen.getByText("100%")).toBeTruthy();- // Ctrl+wheel (also how browsers deliver a trackpad pinch) zooms in.- fireEvent.wheel(canvas, { deltaY: -100, ctrlKey: true });- expect(screen.getByText("122%")).toBeTruthy();- });-- it("pans the canvas with a pointer drag on the background", async () => {+ it("says so when there are no artifacts at all", async () => {installFetchMock(- [{ slug: "run-new", utterance: "Draw the architecture", status: "success" }],- { "run-new": [] },- { "run-new": CHART_PLAN },+ [{ slug: "run-text", utterance: "Write notes", status: "success" }],+ { "run-text": [file("tasks/t1/artifacts/files/notes.md", { is_text: true })] },);renderView();- const canvas = await screen.findByTestId("visualization-canvas");- // jsdom has no PointerEvent constructor — a MouseEvent under the pointer- // event's name carries the coordinates the pan handlers read.- fireEvent(- canvas,- new MouseEvent("pointerdown", { bubbles: true, clientX: 100, clientY: 90 }),- );- fireEvent(- canvas,- new MouseEvent("pointermove", { bubbles: true, clientX: 60, clientY: 70 }),- );- expect(canvas.scrollLeft).toBe(40);- expect(canvas.scrollTop).toBe(20);-- // Releasing ends the pan: further movement no longer scrolls.- fireEvent(canvas, new MouseEvent("pointerup", { bubbles: true }));- fireEvent(- canvas,- new MouseEvent("pointermove", { bubbles: true, clientX: 0, clientY: 0 }),- );- expect(canvas.scrollLeft).toBe(40);- });-- it("points every edge with an arrowhead, alarm-coloured after a failure", async () => {- installFetchMock(- [{ slug: "run-new", utterance: "Deploy it", status: "error" }],- { "run-new": [] },- {- "run-new": {- plan: { plan_id: "run-new", vision: "Deploy it", status: "failed" },- steps: [- {- step_id: "t1:0",- name: "npm run deploy",- tool_name: "Bash",- status: "failed",- error: "exit 1",- },- ],- },- },- );-- renderView();-- await screen.findByTestId("graph-node-step");- const edges = screen.getAllByTestId("graph-edge");- expect(edges.length).toBeGreaterThan(0);- // Since the track wraps, an edge can run back to the left — only a- // pointed end keeps the flow readable, on every single edge.- for (const edge of edges) {- expect(edge.getAttribute("marker-end")).toMatch(/url\(#viz-arrow/);- }- // The edge into the failed step wears the alarm arrow, not the brand one.- expect(- edges.some(- (e) => e.getAttribute("marker-end") === "url(#viz-arrow-failed)",- ),- ).toBe(true);- });-- it("keeps a press on a node a click, never a pan", async () => {- installFetchMock(- [{ slug: "run-new", utterance: "Draw the architecture", status: "success" }],- { "run-new": [] },- { "run-new": CHART_PLAN },- );-- renderView();-- const canvas = await screen.findByTestId("visualization-canvas");- const node = await screen.findByTestId("graph-node-start");- fireEvent(- node,- new MouseEvent("pointerdown", { bubbles: true, clientX: 100, clientY: 90 }),- );- fireEvent(- canvas,- new MouseEvent("pointermove", { bubbles: true, clientX: 60, clientY: 70 }),- );- // The press began on a card, so the canvas never grabbed it…- expect(canvas.scrollLeft).toBe(0);- // …and the click still opens the inspector.- fireEvent.click(node);- await screen.findByTestId("visualization-inspector");+ await screen.findByTestId("visualization-empty");+ expect(screen.queryByTestId("visualization-frame")).toBeNull();+ expect(screen.queryAllByTestId("visualization-artifact-row")).toHaveLength(0);});});@@ -492,7 +372,7 @@ describe("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.+ // what must not happen over a rendered page.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.tsxindex f059f65293..9b7bae3df2 100644--- a/jarvis/ui/web/frontend/src/views/VisualizationView.tsx+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.tsx@@ -1,28 +1,23 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {- useCallback,- useEffect,- useLayoutEffect,- useMemo,- useRef,- useState,-} from "react";-import {+ Code2,Download,ExternalLink,+ Eye,+ FileImage,+ FileText,FolderOpen,Frame,+ Globe,Loader2,- Maximize2,RefreshCw,- ShieldAlert,+ ShieldCheck,Workflow,- X,- ZoomIn,- ZoomOut,} from "lucide-react";import { Button } from "@/components/ui/button";import { ScrollArea } from "@/components/ui/scroll-area";+import { RunGraphPanel } from "@/components/visualization/RunGraphPanel";import { ViewHeader } from "@/views/ChatsView";import { useT } from "@/i18n";import { cn } from "@/lib/utils";@@ -31,78 +26,42 @@ import { openExternalUrl } from "@/lib/openExternal";import {artifactDownloadUrl,revealArtifact,- useArtifactsForOutput,+ useArtifactFile,useOutputsCapabilities,useOutputsList,- usePlanForOutput,- type ArtifactSummary,type OutputStatus,type OutputSummary,} from "@/hooks/useOutputs";import {- classifyVisual,+ artifactPageUrl,missionMapUrl,- MISSION_MAP_PATH,useVisualArtifacts,- visualUrl,+ visualId,+ type VisualArtifact,type VisualKind,} from "@/hooks/useVisualArtifacts";-import {- buildRunGraph,- edgePath,- NODE_H,- NODE_W,- type RunGraph,- type RunGraphNode,-} from "@/lib/runGraph";-import {- categoryColor,- categoryTint,- NODE_CATEGORIES,- nodeCategory,- nodeGlyph,-} from "@/lib/nodeSpec";/**- * 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 Artifacts section — every page and picture a run produced, full-size.*- * 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.+ * An artifact is the thing the user asked to LOOK AT: the dashboard, the+ * report, the diagram a background agent wrote as one self-contained HTML+ * file (`create_artifact`), or any image/PDF a worker left behind. It is+ * shown the way Claude shows an artifact: the page fills the stage, its own+ * scripts run inside a sandbox, the source is one tab away, and "how did+ * this come to be" — the n8n-style run graph that used to BE this section —+ * sits behind a third tab instead of in front of the page.*- * 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.+ * It owns no data: runs come from `/api/outputs`, files from the artifact+ * listing (`useVisualArtifacts`), a page's source from `/raw`. A run that is+ * still building its artifact shows as a "building…" row the rail follows+ * until the page lands — the list for a running run polls, nothing else does.*- * 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.+ * Detachable (`DETACHABLE_VIEWS` in jarvis/ui/desktop_app.py): an artifact is+ * the thing people put on a second monitor.*/-/*- * Zoom: the buttons snap to these steps, the wheel (Ctrl/⌘ + scroll, and the- * trackpad pinch that browsers report the same way) moves continuously, and- * "fit" produces whatever ratio the graph needs — so the step logic finds the- * NEAREST step in the pressed direction rather than requiring an exact match.- */-const ZOOM_STEPS = [0.25, 0.35, 0.5, 0.65, 0.8, 1, 1.25, 1.5] as const;-const MIN_ZOOM = ZOOM_STEPS[0];-const MAX_ZOOM = ZOOM_STEPS[ZOOM_STEPS.length - 1];--const clampZoom = (value: number): number =>- Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, value));--/** Same status colour language as the Outputs cards — one vocabulary. */+/** What a row's status dot means — the Outputs vocabulary, one language. */const RUN_DOT: Record<OutputStatus, string> = {success: "bg-emerald-400",error: "bg-destructive",@@ -111,18 +70,42 @@ const RUN_DOT: Record<OutputStatus, string> = {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",+const KIND_ICON: Record<VisualKind, typeof Globe> = {+ page: Globe,+ image: FileImage,+ vector: FileImage,+ document: FileText,};-/** The rail row's timestamp — what tells two same-ask runs apart. */-function formatRunDate(entry: OutputSummary): string {- const ts = entry.completed_at ?? entry.started_at;- if (!ts) return "";- return new Date(ts * 1000).toLocaleString(undefined, {+type StageMode = "preview" | "code" | "run";++/** The rail's pick: an artifact (`path`) or a whole run still building (`null`). */+interface Selection {+ slug: string;+ path: string | null;+}++/**+ * A `create_artifact` mission's prompt leads with `Artifact: <title>` and the+ * user's request right after (jarvis/artifacts/brief.py). The Outputs list+ * already strips the quality lead, so the run's `utterance` starts with that+ * line — which is how a running build is recognised and labelled here.+ */+export function parseArtifactUtterance(+ utterance: string | undefined,+): { title: string; request: string } | null {+ const text = (utterance ?? "").trim();+ const match = /^Artifact:[ \t]*([^\n]+)/.exec(text);+ if (!match) return null;+ const rest = text.slice(match[0].length).trim();+ const request = rest.split(/\n\s*\n/)[0]?.trim() ?? "";+ return { title: match[1].trim(), request };+}++/** The rail row's timestamp — what tells two same-named artifacts apart. */+function formatWhen(seconds: number): string {+ if (!seconds) return "";+ return new Date(seconds * 1000).toLocaleString(undefined, {month: "short",day: "numeric",hour: "2-digit",@@ -130,290 +113,107 @@ function formatRunDate(entry: OutputSummary): string {});}-/** 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`;}-/** Human duration for a step — sub-second precision only where it matters. */-function formatDuration(seconds: number): string {- if (seconds < 10) return `${seconds.toFixed(1)} s`;- if (seconds < 60) return `${Math.round(seconds)} s`;- const minutes = Math.floor(seconds / 60);- const rest = Math.round(seconds % 60);- return `${minutes} min ${rest} s`;-}-export function VisualizationView() {const t = useT();const outputs = useOutputsList();const runs = useMemo(() => outputs.data ?? [], [outputs.data]);-- /* A `?run=<slug>` in the URL pre-selects that run — what makes a detached- * window or a pasted link open on the run it talks about, instead of- * whatever happens to be newest. Read once at mount; clicks own it after. */- const [selectedSlug, setSelectedSlug] = useState<string | null>(- () => new URLSearchParams(window.location.search).get("run"),+ const gallery = useVisualArtifacts();+ const visuals = gallery.visuals;++ /* Runs still writing their artifact — recognised by the brief's lead line,+ * so an unrelated running mission does not pose as a page in the making. */+ const building = useMemo(+ () =>+ runs.filter(+ (run) => run.status === "running" && parseArtifactUtterance(run.utterance) !== null,+ ),+ [runs],);- const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);- /*- * 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 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);+ /* A `?run=<slug>` in the URL pre-selects that run's newest artifact — what+ * makes a detached window or a pasted link open on the page it talks about.+ * Read once at mount; clicks own it after. */+ const [selection, setSelection] = useState<Selection | null>(() => {+ const slug = new URLSearchParams(window.location.search).get("run");+ return slug ? { slug, path: null } : null;+ });+ /* Once the user picked a row, the newest artifact landing must not steal the+ * stage — an explicit choice is never fought. A pick of a BUILDING run is the+ * exception it resolves itself: its page replaces the spinner when it lands. */+ const userPicked = useRef(selection !== null);/*- * 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, 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.+ * Another surface asked for something to be staged ("show visuals" on the+ * agent strip, the `create_artifact` tool via NavigateSidebar). A target+ * names a `visualId` (slug::path) or "latest"; see VisualStageRequest.*/const visualStage = useEventStore((s) => s.visualStage);- const { visuals } = useVisualArtifacts();useEffect(() => {if (visualStage === null) return;if (visualStage.target === "latest") {- const newest = visuals[0];- if (newest) {- setSelectedSlug(newest.slug);- setSelectedNodeId(- newest.path === MISSION_MAP_PATH ? null : `artifact:${newest.path}`,- );- }+ userPicked.current = false;+ setSelection(null);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(() => {- 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);- /* Once the user has zoomed or panned by hand, the automatic fit keeps its- * hands off until another run is selected — an explicit choice must never- * be fought. */- const userZoomed = useRef(false);- const [canvasEl, setCanvasEl] = useState<HTMLDivElement | null>(null);-- /*- * Anchored zoom: every zoom keeps ONE canvas point where it is on screen —- * the cursor for the wheel, the viewport centre for the buttons. Without an- * anchor the scale pivots on the canvas origin and the node being looked at- * slides out of view. The anchor is recorded in content coordinates and the- * scroll correction lands right after the rescaled canvas hits the DOM,- * before paint — no one-frame jump.- */- const zoomRef = useRef(1);- const zoomAnchor = useRef<{- px: number;- py: number;- cx: number;- cy: number;- } | null>(null);-- useLayoutEffect(() => {- zoomRef.current = zoom;- const pending = zoomAnchor.current;- if (pending === null || canvasEl === null) return;- zoomAnchor.current = null;- canvasEl.scrollLeft = pending.px * zoom - pending.cx;- canvasEl.scrollTop = pending.py * zoom - pending.cy;- }, [zoom, canvasEl]);-- /** Zoom to `next`, keeping the given viewport point (default: centre) put. */- const zoomTo = useCallback(- (next: number, at?: { cx: number; cy: number }) => {- const clamped = clampZoom(next);- const current = zoomRef.current;- if (canvasEl !== null && clamped !== current) {- const cx = at?.cx ?? canvasEl.clientWidth / 2;- const cy = at?.cy ?? canvasEl.clientHeight / 2;- zoomAnchor.current = {- px: (canvasEl.scrollLeft + cx) / current,- py: (canvasEl.scrollTop + cy) / current,- cx,- cy,- };- }- setZoom(clamped);- },- [canvasEl],- );-- const stepZoom = useCallback(- (direction: 1 | -1) => {- userZoomed.current = true;- const current = zoomRef.current;- const next =- direction > 0- ? (ZOOM_STEPS.find((s) => s > current + 0.001) ?? MAX_ZOOM)- : ([...ZOOM_STEPS].reverse().find((s) => s < current - 0.001) ??- Math.min(current, MIN_ZOOM));- zoomTo(next);- },- [zoomTo],- );-- /* Scale the whole story into the visible canvas — never above 100%, so a- * two-node run stays a pair of cards instead of a pair of billboards. The- * guard skips hidden/unmeasured hosts (detached warm-up, jsdom). */- const fitZoom = useCallback(() => {- if (canvasEl === null || graph === null) return;- const { clientWidth, clientHeight } = canvasEl;- if (clientWidth < 80 || clientHeight < 80) return;- const scale = Math.min(- (clientWidth - 16) / graph.width,- (clientHeight - 16) / graph.height,- 1,- );- // Fit means "show the whole story": the viewport returns to the origin,- // by plain assignment (no pending anchor — fit IS the anchor decision).- zoomAnchor.current = null;- canvasEl.scrollLeft = 0;- canvasEl.scrollTop = 0;- setZoom(clampZoom(scale));- }, [canvasEl, graph]);-- useEffect(() => {- userZoomed.current = false;- }, [run?.slug]);-- /* Auto-fit whenever the graph's extents change — the first paint, the plan- * arriving a beat after the run list, and a live run growing new steps. */- useEffect(() => {- if (!userZoomed.current) fitZoom();- }, [fitZoom, graph?.width, graph?.height]);-- /* Ctrl/⌘ + wheel zooms (that's also how browsers deliver a trackpad pinch).- * Attached natively because React registers wheel listeners passively, and- * a passive listener cannot preventDefault the browser's own page zoom. */- useEffect(() => {- if (canvasEl === null) return;- const onWheel = (event: WheelEvent) => {- if (!event.ctrlKey && !event.metaKey) return;- event.preventDefault();- userZoomed.current = true;- const rect = canvasEl.getBoundingClientRect();- zoomTo(zoomRef.current * Math.exp(-event.deltaY * 0.002), {- cx: event.clientX - rect.left,- cy: event.clientY - rect.top,+ userPicked.current = true;+ setSelection({+ slug: visualStage.target.slice(0, separator),+ path: visualStage.target.slice(separator + 2),});- };- canvasEl.addEventListener("wheel", onWheel, { passive: false });- return () => canvasEl.removeEventListener("wheel", onWheel);- }, [canvasEl, zoomTo]);+ }+ }, [visualStage]);/*- * Drag-to-pan. The scroll container follows a held primary/middle button on- * canvas background; a press on a node stays a click. Pointer capture keeps- * a fast drag alive outside the canvas (guarded: jsdom has no capture API).+ * What the stage shows. In order: the row the user picked (an artifact, or+ * a run's newest artifact once it has one); while nothing was picked, the+ * newest build in progress; otherwise the newest artifact there is.*/- const [panning, setPanning] = useState(false);- const panState = useRef<{- pointerId: number;- originX: number;- originY: number;- scrollLeft: number;- scrollTop: number;- } | null>(null);-- const onPanStart = useCallback(- (event: React.PointerEvent<HTMLDivElement>) => {- if (canvasEl === null) return;- if (event.button !== 0 && event.button !== 1) return;- if ((event.target as Element).closest("button") !== null) return;- // Middle button would otherwise start the browser's own autoscroll.- if (event.button === 1) event.preventDefault();- panState.current = {- pointerId: event.pointerId,- originX: event.clientX,- originY: event.clientY,- scrollLeft: canvasEl.scrollLeft,- scrollTop: canvasEl.scrollTop,- };- setPanning(true);- // Capture keeps a fast drag alive outside the canvas. Guarded twice:- // jsdom neither constructs PointerEvents (pointerId undefined) nor- // accepts capture for a pointer it never saw.- if (typeof event.pointerId === "number")- canvasEl.setPointerCapture?.(event.pointerId);- },- [canvasEl],- );+ const currentBuild: OutputSummary | null = useMemo(() => {+ if (selection !== null) {+ if (selection.path !== null) return null;+ const hasPage = visuals.some((v) => v.slug === selection.slug);+ return hasPage ? null : (building.find((r) => r.slug === selection.slug) ?? null);+ }+ return building[0] ?? null;+ }, [selection, visuals, building]);++ const current: VisualArtifact | null = useMemo(() => {+ if (currentBuild !== null) return null;+ if (selection !== null) {+ const picked =+ selection.path !== null+ ? visuals.find((v) => v.slug === selection.slug && v.path === selection.path)+ : visuals.find((v) => v.slug === selection.slug);+ if (picked) return picked;+ if (userPicked.current) return visuals[0] ?? null;+ }+ return visuals[0] ?? null;+ }, [currentBuild, selection, visuals]);- const onPanMove = useCallback(- (event: React.PointerEvent<HTMLDivElement>) => {- const pan = panState.current;- if (pan === null || canvasEl === null) return;- const dx = event.clientX - pan.originX;- const dy = event.clientY - pan.originY;- // A real drag (not a sloppy click) is a viewport choice like a manual- // zoom: the auto-fit stops following a live run's growth.- if (Math.abs(dx) + Math.abs(dy) > 4) userZoomed.current = true;- canvasEl.scrollLeft = pan.scrollLeft - dx;- canvasEl.scrollTop = pan.scrollTop - dy;- },- [canvasEl],+ const currentRun: OutputSummary | null = useMemo(+ () => (current ? (runs.find((r) => r.slug === current.slug) ?? null) : null),+ [current, runs],);- const onPanEnd = useCallback(() => {- const pan = panState.current;- if (pan === null) return;- panState.current = null;- setPanning(false);- if (typeof pan.pointerId === "number")- canvasEl?.releasePointerCapture?.(pan.pointerId);- }, [canvasEl]);+ const [mode, setMode] = useState<StageMode>("preview");+ const currentId = current ? visualId(current) : null;+ // A new artifact opens on its page, whatever tab the previous one was on.+ useEffect(() => setMode("preview"), [currentId]);const refetch = useCallback(() => {void outputs.refetch();- void plan.refetch();- void artifacts.refetch();- }, [outputs, plan, artifacts]);+ gallery.refetch();+ }, [outputs, gallery]);- const loading = outputs.isLoading || plan.isLoading || artifacts.isLoading;+ const loading = outputs.isLoading || gallery.isLoading;return (<div className="flex h-full min-h-0 flex-col">@@ -422,206 +222,160 @@ export function VisualizationView() {title={t("visualization.title")}subtitle={t("visualization.subtitle")}right={- <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>+ <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 />)}- <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>+ {t("visualization.refresh")}+ </Button>}/><div className="flex min-h-0 flex-1">- {/* Run rail — every archived run, newest first. */}- <aside className="flex w-64 shrink-0 flex-col border-r border-border">+ {/* Rail — builds in progress first, then every artifact, newest first. */}+ <aside className="flex w-72 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")}+ {t("visualization.rail")}+ {visuals.length > 0 && (+ <span className="ml-1.5 normal-case tracking-normal text-muted-foreground/70">+ · {visuals.length}+ </span>+ )}</p><ScrollArea className="min-h-0 flex-1">- <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+ <ul className="space-y-1 p-2" data-testid="visualization-artifacts">+ {building.map((run) => {+ const parsed = parseArtifactUtterance(run.utterance);+ const active = currentBuild?.slug === run.slug;+ return (+ <li key={`build:${run.slug}`}>+ <button+ type="button"+ onClick={() => {+ userPicked.current = true;+ setSelection({ slug: run.slug, path: null });+ }}+ aria-current={active}+ data-testid="visualization-building-row"className={cn(- "mt-1 h-1.5 w-1.5 shrink-0 rounded-full",- RUN_DOT[entry.status ?? "unknown"],+ "flex w-full items-start gap-2 rounded-md px-2 py-2 text-left text-xs transition-colors",+ active+ ? "bg-primary/15 text-foreground"+ : "text-muted-foreground hover:bg-secondary/60 hover:text-foreground",)}- aria-hidden- />- <span className="min-w-0 flex-1">- <span className="block truncate font-medium text-foreground">- {entry.utterance?.trim() || entry.slug}+ >+ <Loader2+ className="mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin text-primary"+ aria-hidden+ />+ <span className="min-w-0 flex-1">+ <span className="block truncate font-medium text-foreground">+ {parsed?.title || t("visualization.building")}+ </span>+ <span className="block truncate">{t("visualization.building")}</span></span>- <span className="block truncate">- {[- formatRunDate(entry),- t("visualization.run_meta").replace(- "{0}",- String(entry.artifact_count ?? 0),- ),- ]- .filter(Boolean)- .join(" · ")}+ </button>+ </li>+ );+ })}+ {visuals.map((visual) => {+ const Icon = KIND_ICON[visual.kind];+ const active = current !== null && visualId(current) === visualId(visual);+ const parsed = parseArtifactUtterance(visual.utterance);+ return (+ <li key={visualId(visual)}>+ <button+ type="button"+ onClick={() => {+ userPicked.current = true;+ setSelection({ slug: visual.slug, path: visual.path });+ }}+ aria-current={active}+ data-testid="visualization-artifact-row"+ data-kind={visual.kind}+ className={cn(+ "flex w-full items-start gap-2 rounded-md px-2 py-2 text-left text-xs transition-colors",+ active+ ? "bg-primary/15 text-foreground"+ : "text-muted-foreground hover:bg-secondary/60 hover:text-foreground",+ )}+ >+ <span className="relative mt-0.5 shrink-0">+ <Icon className="h-3.5 w-3.5" aria-hidden />+ <span+ className={cn(+ "absolute -right-0.5 -top-0.5 h-1.5 w-1.5 rounded-full",+ RUN_DOT[visual.status ?? "unknown"],+ )}+ aria-hidden+ /></span>- </span>- </button>- </li>- ))}+ <span className="min-w-0 flex-1">+ <span className="block truncate font-medium text-foreground">+ {visual.title}+ </span>+ <span className="block truncate">+ {[+ formatWhen(visual.mtime),+ parsed?.request || visual.utterance?.trim() || visual.name,+ ]+ .filter(Boolean)+ .join(" · ")}+ </span>+ </span>+ </button>+ </li>+ );+ })}</ul>+ {gallery.skippedRuns > 0 && (+ <p className="px-3 pb-3 text-[11px] text-muted-foreground/70">+ {t("visualization.older_not_scanned").replace(+ "{0}",+ String(gallery.scannedRuns),+ )}+ </p>+ )}</ScrollArea></aside>- {/* Canvas — the selected run as connected nodes along tracks. */}+ {/* Stage — the artifact itself, full-size. */}<section className="flex min-h-0 min-w-0 flex-1 flex-col">- {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",- )}+ {currentBuild !== null ? (+ <BuildingStage run={currentBuild} />+ ) : current === null ? (+ <EmptyStage+ loading={loading}+ error={outputs.isError || gallery.isError}/>) : (<>- <div- ref={setCanvasEl}- className={cn(- "min-h-0 flex-1 overflow-auto",- panning ? "cursor-grabbing" : "cursor-grab",+ <ArtifactToolbar+ visual={current}+ mode={mode}+ onMode={setMode}+ runAvailable={currentRun !== null}+ />+ <div className="min-h-0 flex-1" data-testid="visualization-stage">+ {mode === "preview" && <ArtifactStage visual={current} />}+ {mode === "code" && (+ <ArtifactSource slug={current.slug} path={current.path} />+ )}+ {mode === "run" && currentRun !== null && (+ <RunGraphPanel key={currentRun.slug} run={currentRun} />)}- data-testid="visualization-canvas"- onPointerDown={onPanStart}- onPointerMove={onPanMove}- onPointerUp={onPanEnd}- onPointerCancel={onPanEnd}- >- <GraphCanvas- graph={graph}- zoom={zoom}- selectedId={selectedNodeId}- onSelect={setSelectedNodeId}- /></div>-- <footer className="flex shrink-0 items-center gap-3 border-t border-border px-4 py-2">- {/* 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={() => stepZoom(-1)}- title={t("visualization.zoom_out")}- aria-label={t("visualization.zoom_out")}- >- <ZoomOut className="h-3.5 w-3.5" aria-hidden />- </Button>- <button- type="button"- onClick={() => {- userZoomed.current = true;- zoomTo(1);- }}- title={t("visualization.zoom_reset")}- aria-label={t("visualization.zoom_reset")}- className="w-12 text-center text-[11px] tabular-nums text-muted-foreground transition-colors hover:text-foreground"- >- {`${Math.round(zoom * 100)}%`}- </button>- <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={() => {- // An explicit fit re-arms the auto-fit: a live run that- // grows new steps keeps fitting until zoomed by hand.- userZoomed.current = false;- fitZoom();- }}- title={t("visualization.zoom_fit")}- aria-label={t("visualization.zoom_fit")}- data-testid="visualization-zoom-fit"- >- <Maximize2 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>);@@ -629,519 +383,294 @@ export function VisualizationView() {/* ------------------------------------------------------------------------- */-function GraphCanvas({- graph,- zoom,- selectedId,- onSelect,+function ArtifactToolbar({+ visual,+ mode,+ onMode,+ runAvailable,}: {- graph: RunGraph;- zoom: number;- selectedId: string | null;- onSelect: (id: string) => void;+ visual: VisualArtifact;+ mode: StageMode;+ onMode: (mode: StageMode) => void;+ runAvailable: boolean;}) {const t = useT();- const byId = useMemo(() => new Map(graph.nodes.map((n) => [n.id, n])), [graph]);+ const pushToast = useEventStore((s) => s.pushToast);+ const capabilities = useOutputsCapabilities();+ const parsed = parseArtifactUtterance(visual.utterance);++ const onReveal = useCallback(async () => {+ try {+ await revealArtifact(visual.slug, visual.path);+ } catch {+ pushToast("error", t("visualization.reveal_failed"));+ }+ }, [visual, pushToast, t]);++ const externalUrl =+ visual.kind === "page"+ ? artifactPageUrl(visual.slug, visual.path)+ : visual.url;++ const tabs: Array<{ id: StageMode; label: string; Icon: typeof Eye; show: boolean }> = [+ { id: "preview", label: t("visualization.tab_preview"), Icon: Eye, show: true },+ { id: "code", label: t("visualization.tab_code"), Icon: Code2, show: visual.kind === "page" || visual.kind === "vector" },+ { id: "run", label: t("visualization.tab_run"), Icon: Workflow, show: runAvailable },+ ];return (- <div- style={{ width: graph.width * zoom, height: graph.height * zoom }}- className="relative min-h-full min-w-full"- >+ <div className="flex shrink-0 items-center gap-3 border-b border-border px-4 py-2">+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm font-medium" data-testid="visualization-title">+ {visual.title}+ </p>+ <p className="truncate text-[11px] text-muted-foreground">+ {[+ formatWhen(visual.mtime),+ formatSize(visual.size),+ parsed?.request || visual.utterance?.trim() || visual.name,+ ]+ .filter(Boolean)+ .join(" · ")}+ </p>+ </div>+<div- style={{- width: graph.width,- height: graph.height,- transform: `scale(${zoom})`,- transformOrigin: "top left",- }}- className="relative"+ role="tablist"+ aria-label={t("visualization.stage_tabs")}+ className="flex shrink-0 items-center rounded-md border border-border bg-secondary/40 p-0.5">- {/* 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- >- {/* Arrowheads. Since the track wraps, an edge can run back to the- left — only a pointed end keeps the flow readable. markerUnits- defaults to strokeWidth, so a highlighted edge's arrow grows- with its stroke for free. refX=8 puts the tip exactly on the- path end — the target card's port, drawn on the layer above. */}- <defs>- <marker- id="viz-arrow"- viewBox="0 0 8 8"- refX="8"- refY="4"- markerWidth="5.5"- markerHeight="5.5"- orient="auto"- >- <path d="M 0 0 L 8 4 L 0 8 Z" className="fill-primary/70" />- </marker>- <marker- id="viz-arrow-failed"- viewBox="0 0 8 8"- refX="8"- refY="4"- markerWidth="5.5"- markerHeight="5.5"- orient="auto"- >- <path d="M 0 0 L 8 4 L 0 8 Z" className="fill-destructive/80" />- </marker>- </defs>- {graph.edges.map((edge) => {- const from = byId.get(edge.from);- const to = byId.get(edge.to);- if (!from || !to) return null;- /* The selected node's own edges brighten, so "what fed this and- * what came of it" is answered by the picture, not by tracing. */- const active =- selectedId !== null &&- (edge.from === selectedId || edge.to === selectedId);- return (- <path- key={edge.id}- data-testid="graph-edge"- d={edgePath(from, to)}- fill="none"- strokeWidth={active ? 2.5 : 1.5}- markerEnd={`url(#${edge.failed ? "viz-arrow-failed" : "viz-arrow"})`}- className={- edge.failed- ? active- ? "stroke-destructive"- : "stroke-destructive/70"- : active- ? "stroke-primary"- : "stroke-primary/50"- }- />- );- })}- </svg>-- {graph.nodes.map((node) => {- const category = nodeCategory(node);- const Icon = nodeGlyph(node);- const hue = categoryColor(category);- const selected = node.id === selectedId;- const reasoning = category === "reasoning";- /* Two calm lines per card. A reasoning card is titled as what it- * IS, with the thought as its detail line — a raw sentence as a- * bold headline reads like a rendering accident. */- const title =- node.kind === "start"- ? t("visualization.node_start")- : node.kind === "result"- ? t("visualization.node_result")- : reasoning- ? t("visualization.cat_reasoning")- : node.title;- const subtitle =- node.kind === "start"- ? node.title- : reasoning- ? node.title- : node.subtitle;- /* Port dots come from the graph model (edge-derived), so a dot is- * always a real attachment point — a start node has no input, a- * deliverable no output, exactly like a workflow editor's nodes. */- const port =- "absolute h-1.5 w-1.5 rounded-full border border-background bg-primary/70";- return (+ {tabs+ .filter((tab) => tab.show)+ .map(({ id, label, Icon }) => (<button- key={node.id}+ key={id}type="button"- onClick={() => onSelect(node.id)}- aria-current={selected}- data-testid={`graph-node-${node.kind}`}- data-category={category}- style={{ left: node.x, top: node.y, width: NODE_W, height: NODE_H }}+ role="tab"+ aria-selected={mode === id}+ onClick={() => onMode(id)}+ data-testid={`visualization-tab-${id}`}className={cn(- "absolute flex items-center gap-2.5 rounded-xl border bg-card px-3 text-left shadow-sm transition-colors",- /* A thought is not an action: reasoning cards wear a dashed- * frame, the visual grammar of "internal, produced nothing". */- reasoning && "border-dashed",- /* A failed or running step announces itself from the card- * frame — a 6px dot alone is not a glanceable alarm. */- selected- ? "border-primary ring-1 ring-primary/40"- : node.status === "failed"- ? "border-destructive/70 hover:border-destructive"- : node.status === "running"- ? "border-primary/60 hover:border-primary"- : "border-border hover:border-primary/50",+ "inline-flex items-center gap-1.5 rounded px-2 py-1 text-[11px] font-medium transition-colors",+ mode === id+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground",)}>- {node.ports.left && (- <span- className={cn(port, "-left-[3px] top-1/2 -translate-y-1/2")}- aria-hidden- />- )}- {node.ports.right &&- (category === "agent" ? (- /* A spawn node branches — its output port doubles, the way- * n8n's if node wears one connector per outcome. */- <>- <span- className={cn(port, "-right-[3px] top-1/2 -translate-y-[7px]")}- aria-hidden- />- <span- className={cn(port, "-right-[3px] top-1/2 translate-y-[1px]")}- aria-hidden- />- </>- ) : (- <span- className={cn(port, "-right-[3px] top-1/2 -translate-y-1/2")}- aria-hidden- />- ))}- {node.ports.top && (- <span- className={cn(port, "-top-[3px] left-1/2 -translate-x-1/2")}- aria-hidden- />- )}- {node.ports.bottom && (- <span- className={cn(port, "-bottom-[3px] left-1/2 -translate-x-1/2")}- aria-hidden- />- )}- {/* The category speaks through the icon alone — its hue and- glyph — never through an extra text line. The label survives- as the tile's tooltip for whoever hovers to ask. */}- <span- className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg"- style={{ color: hue, backgroundColor: categoryTint(category, 0.12) }}- title={t(NODE_CATEGORIES[category].labelKey)}- >- <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" && !reasoning && (- <span- className={cn(- "h-1.5 w-1.5 shrink-0 rounded-full",- NODE_DOT[node.status],- )}- title={t(`visualization.status_${node.status}`)}- />- )}+ <Icon className="h-3.5 w-3.5" aria-hidden />+ {label}</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>+ <div className="flex shrink-0 items-center gap-1">+ {mode === "run" && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() =>+ void openExternalUrl(`${window.location.origin}${missionMapUrl(visual.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>+ )}<Buttonvariant="ghost"size="sm"- onClick={onClose}- title={t("visualization.close")}- aria-label={t("visualization.close")}+ onClick={() => void openExternalUrl(`${window.location.origin}${externalUrl}`)}+ title={t("visualization.open_external_hint")}+ data-testid="visualization-open-external">- <X className="h-3.5 w-3.5" aria-hidden />+ <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(visual.slug, visual.path)}+ download+ title={t("visualization.download")}+ aria-label={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")}+ aria-label={t("visualization.reveal")}+ >+ <FolderOpen 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">- {/* A reasoning step is a thought, not a call: it gets the thought- text and nothing pretending to be tool telemetry. */}- {node.kind === "step" && node.step?.kind === "reasoning" && (- <InspectorField label={t("visualization.field_thought")}>- <p className="whitespace-pre-wrap break-words text-xs">- {node.step.output || node.step.name}- </p>- </InspectorField>- )}-- {node.kind === "step" && node.step && node.step.kind !== "reasoning" && (- <>- <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>- {typeof node.step.duration_s === "number" &&- node.step.duration_s > 0 && (- <InspectorField label={t("visualization.field_duration")}>- {formatDuration(node.step.duration_s)}- </InspectorField>- )}- {/* One attempt is the norm — only a retry is worth a line. */}- {(node.step.attempts ?? 1) > 1 && (- <InspectorField label={t("visualization.field_attempts")}>- {String(node.step.attempts)}- </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 deliverable preview inside the inspector.+ * The artifact on stage, full-size.*- * 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.+ * A PAGE is framed from `/page` — served with scripts allowed and every+ * network path shut — inside `sandbox="allow-scripts"` WITHOUT+ * `allow-same-origin`: its JavaScript runs in an opaque origin that cannot+ * reach the app's cookies, storage or API (the Claude-artifact model). Raster+ * and vector go through `<img>`, which executes nothing. A PDF renders in the+ * browser's own viewer inside an empty sandbox.*/-function ArtifactPreview({- slug,- artifact,- kind,-}: {- slug: string;- artifact: ArtifactSummary;- kind: VisualKind;-}) {+function ArtifactStage({ visual }: { visual: VisualArtifact }) {const t = useT();const [failed, setFailed] = useState(false);- const url = visualUrl(slug, artifact.path);-+ const id = visualId(visual);// A new file must not inherit the previous file's failure verdict.- useEffect(() => setFailed(false), [url]);+ useEffect(() => setFailed(false), [id]);if (failed) {return (- <p className="text-xs text-muted-foreground">- {t("visualization.render_failed")}- </p>+ <div className="flex h-full items-center justify-center p-8 text-center">+ <p className="max-w-sm text-xs text-muted-foreground">+ {t("visualization.render_failed")}+ </p>+ </div>);}- if (kind === "image" || kind === "vector") {+ if (visual.kind === "image" || visual.kind === "vector") {return (- <img- src={url}- alt={artifact.path}- data-testid="visualization-image"- onError={() => setFailed(true)}- className="max-h-72 w-full rounded-md border border-border bg-background/40 object-contain"- />+ <div className="flex h-full items-center justify-center overflow-auto p-6">+ <img+ src={visual.url}+ alt={visual.title}+ data-testid="visualization-image"+ onError={() => setFailed(true)}+ className="max-h-full max-w-full rounded-md border border-border bg-background/40 object-contain"+ />+ </div>+ );+ }++ if (visual.kind === "page") {+ return (+ <div className="flex h-full flex-col">+ <iframe+ key={id}+ src={artifactPageUrl(visual.slug, visual.path)}+ title={visual.title}+ data-testid="visualization-frame"+ onError={() => setFailed(true)}+ // allow-scripts WITHOUT allow-same-origin: the page's JS runs in an+ // opaque origin. No forms, no popups, no navigation of the app.+ sandbox="allow-scripts"+ className="min-h-0 w-full flex-1 border-0 bg-background"+ />+ <p className="flex shrink-0 items-center gap-1.5 border-t border-border px-4 py-1.5 text-[11px] text-muted-foreground">+ <ShieldCheck className="h-3 w-3 shrink-0" aria-hidden />+ {t("visualization.page_sandbox_note")}+ </p>+ </div>);}return (- <div className="space-y-1.5">+ <div className="flex h-full flex-col"><iframe- src={url}- title={artifact.path}+ key={id}+ src={visual.url}+ title={visual.title}data-testid="visualization-frame"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.+ // Empty sandbox: the browser's own PDF viewer is not the document's+ // script context, so the file still renders.sandbox=""- className="h-72 w-full rounded-md border border-border bg-white"+ className="min-h-0 w-full flex-1 border-0 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 />+ <p className="flex shrink-0 items-center gap-1.5 border-t border-border px-4 py-1.5 text-[11px] text-muted-foreground">+ <ShieldCheck className="h-3 w-3 shrink-0" aria-hidden />{t("visualization.sandbox_note")}</p></div>);}+/** The page's source, read through `/raw` — what "Code" shows. */+function ArtifactSource({ slug, path }: { slug: string; path: string }) {+ const t = useT();+ const file = useArtifactFile(slug, path);+ if (file.isLoading) {+ return (+ <div className="flex h-full items-center justify-center">+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" aria-hidden />+ </div>+ );+ }+ if (file.isError || !file.data) {+ return (+ <div className="flex h-full items-center justify-center p-8 text-center">+ <p className="text-xs text-muted-foreground">{t("visualization.source_failed")}</p>+ </div>+ );+ }+ return (+ <pre+ className="h-full overflow-auto whitespace-pre-wrap break-words p-4 font-mono text-[11px] leading-relaxed text-foreground/90"+ data-testid="visualization-source"+ >+ {file.data.text}+ {file.data.truncated ? `\n…` : ""}+ </pre>+ );+}+/* ------------------------------------------------------------------------- */-function EmptyCanvas({- loading,- error,- title,- body,-}: {- loading: boolean;- error: boolean;- title: string;- body: string;-}) {+function BuildingStage({ run }: { run: OutputSummary }) {+ const t = useT();+ const parsed = parseArtifactUtterance(run.utterance);+ return (+ <div+ className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-8 text-center"+ data-testid="visualization-building"+ >+ <Loader2 className="h-6 w-6 animate-spin text-primary" aria-hidden />+ <p className="text-sm font-medium">+ {t("visualization.building_title").replace("{0}", parsed?.title ?? "")}+ </p>+ <p className="max-w-sm text-xs text-muted-foreground">{t("visualization.building_body")}</p>+ {parsed?.request && (+ <p className="max-w-md truncate text-[11px] text-muted-foreground/70">{parsed.request}</p>+ )}+ </div>+ );+}++function EmptyStage({ loading, error }: { loading: boolean; error: boolean }) {+ const t = useT();return (<divclassName="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- />+ <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>+ <p className="text-sm font-medium">+ {t(error ? "visualization.error_title" : "visualization.empty_title")}+ </p>+ <p className="max-w-sm text-xs text-muted-foreground">+ {t(error ? "visualization.error_body" : "visualization.empty_body")}+ </p></div>);}diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.pyindex 55d9a12d96..6ae60bc9a7 100644--- a/jarvis/ui/web/outputs_routes.py+++ b/jarvis/ui/web/outputs_routes.py@@ -37,7 +37,7 @@ from jarvis.missions.standalone_run import read_marker as read_standalone_markerfrom jarvis.missions.state_machine import MissionState, is_terminalfrom jarvis.missions.stream_evidence import clean_request_bodyfrom jarvis.platform import detect_platform-from jarvis.ui.web.artifact_view import VIEW_CSP, render_artifact_html+from jarvis.ui.web.artifact_view import ARTIFACT_PAGE_CSP, VIEW_CSP, render_artifact_htmlfrom jarvis.ui.web.mission_graph import build_mission_graph, render_mission_graph_htmlfrom jarvis.ui.web.run_plan import build_run_plan@@ -1070,6 +1070,36 @@ async def download_output_artifact()[email protected]("/{slug}/files/{path:path}/page")+async def serve_artifact_page(slug: str, path: str, request: Request) -> FileResponse:+ """Serve an HTML deliverable as an ARTIFACT PAGE — scripts allowed, network shut.++ The Artifacts section frames the file from here inside an iframe with+ ``sandbox="allow-scripts"`` (no ``allow-same-origin``): the page's own+ JavaScript runs, so a dashboard filters and a chart draws, while the+ opaque origin plus :data:`ARTIFACT_PAGE_CSP` keep it from reaching the+ app, the network or the user's files. Only ``.html``/``.htm`` are served+ this way; everything else keeps the inline-download path and its+ no-script policy.+ """+ target = _resolve_artifact_target(request, slug, path)+ if target.suffix.lower() not in (".html", ".htm"):+ raise HTTPException(status_code=415, detail="only an HTML deliverable is an artifact page")+ return FileResponse(+ target,+ media_type="text/html",+ filename=target.name,+ content_disposition_type="inline",+ headers={+ "X-Content-Type-Options": "nosniff",+ "Content-Security-Policy": ARTIFACT_PAGE_CSP,+ # A page is edited by revision, not cached across versions: the+ # same filename can hold a newer page a minute later.+ "Cache-Control": "no-store",+ },+ )++@router.get("/{slug}/files/{path:path}/view")async def view_output_artifact(slug: str, path: str, request: Request) -> HTMLResponse:"""Render a text/markdown artifact as a standalone styled HTML page.diff --git a/jarvis/visuals/__init__.py b/jarvis/visuals/__init__.pyindex 3990921f9f..2b6ff6478d 100644--- a/jarvis/visuals/__init__.py+++ b/jarvis/visuals/__init__.py@@ -1,33 +1,14 @@-"""On-demand visualisations — the pictures a user explicitly asked for.+"""The brand palette shared by every server-rendered page.-Three small pieces, deliberately separable:--* :mod:`~jarvis.visuals.spec` — the shape a caller has to supply, and the- validation that turns loose model-authored JSON into it.-* :mod:`~jarvis.visuals.render` — spec in, one self-contained HTML page out.- Pure function, no filesystem, no network: trivially testable.-* :mod:`~jarvis.visuals.store` — where that page is written so the existing- Outputs/Visualization surfaces find it without a new REST route.--The gate that decides whether any of this runs at all lives elsewhere, in-:mod:`jarvis.brain.visualize_gate` — rendering is only ever reached on a turn-that asked for a picture in so many words.+Once the home of the on-demand visualisation renderer (spec → HTML, five fixed+shapes). That was retired on 2026-08-23 in favour of artifacts — whole pages a+mission worker writes on the strongest model (:mod:`jarvis.artifacts`). What+stays is the one thing both the mission map and the artifact brief still need:+the palette."""from __future__ import annotationsfrom jarvis.visuals.brand import BRAND-from jarvis.visuals.render import render_visual_html-from jarvis.visuals.spec import VisualItem, VisualSpec, VisualSpecError, parse_spec-from jarvis.visuals.store import StoredVisual, store_visual-__all__ = [- "BRAND",- "StoredVisual",- "VisualItem",- "VisualSpec",- "VisualSpecError",- "parse_spec",- "render_visual_html",- "store_visual",-]+__all__ = ["BRAND"]diff --git a/jarvis/visuals/render.py b/jarvis/visuals/render.pydeleted file mode 100644index d73447a577..0000000000--- a/jarvis/visuals/render.py+++ /dev/null@@ -1,275 +0,0 @@-"""Turn a :class:`~jarvis.visuals.spec.VisualSpec` into one self-contained page.--The serving constraints are the same ones that shape ``mission_graph``, and-they are strict enough to be worth restating: the page is delivered inside the-app origin under ``VIEW_CSP`` (``default-src 'none'; style-src 'unsafe-inline';-img-src data:``). No JavaScript, no fonts, no images, nothing fetched. Whatever-the page does, it does with markup and CSS that ship inside it.--Where ``mission_graph`` answers that with Python-computed absolute positions —-it draws curved connector tracks, which need real coordinates — this renderer-uses ordinary flow layout: flex rows, indented lists, a grid. The reason is the-input. A mission map has a fixed shape the renderer knows in advance; these-pictures carry model-authored labels of unpredictable length in five different-shapes. Text that reflows survives that; text baked into computed boxes does-not, and there is no JavaScript here to measure and correct it afterwards.--Every dynamic string is model-authored and escaped on the way in.--Pure function of its input: no clock, no filesystem, no randomness — the same-spec renders byte-identically, which is what makes the golden tests possible.-"""--from __future__ import annotations--import html-from collections.abc import Iterable--from jarvis.visuals.brand import BRAND-from jarvis.visuals.spec import VisualItem, VisualSpec--# The widest a bar can be drawn, and the sliver a zero keeps so that "none" is-# still visibly a row rather than a missing one.-_BAR_MAX_PCT = 100.0-_BAR_MIN_PCT = 1.5---def _e(text: str) -> str:- return html.escape(text or "", quote=True)---def _format_number(value: float) -> str:- """A number as a person would write it: no trailing ``.0``, thousands split."""- if value == int(value) and abs(value) < 1e15:- return f"{int(value):,}"- rounded = round(value, 2)- return f"{rounded:,}".rstrip("0").rstrip(".")---def _detail(item: VisualItem) -> str:- return f'<p class="detail">{_e(item.detail)}</p>' if item.detail else ""---# --- The five shapes ------------------------------------------------------------def _render_flow(items: Iterable[VisualItem]) -> str:- """Ordered steps, each followed by an arrow into the next.-- The arrow is its own flex child rather than a ``::after`` on the card, so- that when the row wraps the arrow wraps with it instead of pointing off the- end of a line.- """- parts: list[str] = []- for index, item in enumerate(items):- if index:- parts.append('<div class="arrow" aria-hidden="true">→</div>')- parts.append(- '<div class="card step">'- f'<div class="num">{index + 1}</div>'- f'<div class="card-text"><p class="label">{_e(item.label)}</p>'- f"{_detail(item)}</div>"- "</div>"- )- return f'<div class="flow">{"".join(parts)}</div>'---def _render_hierarchy(items: Iterable[VisualItem], *, depth: int = 0) -> str:- """Parts within parts. The left rule and the tick are drawn by CSS borders.-- Recursive, and bounded by the spec's depth cap rather than by anything- here — validation already refused anything deeper.- """- rows: list[str] = []- for item in items:- children = (- _render_hierarchy(item.children, depth=depth + 1) if item.children else ""- )- rows.append(- '<li class="branch">'- '<div class="card node">'- f'<div class="card-text"><p class="label">{_e(item.label)}</p>'- f"{_detail(item)}</div>"- "</div>"- f"{children}"- "</li>"- )- klass = "tree root" if depth == 0 else "tree"- return f'<ul class="{klass}">{"".join(rows)}</ul>'---def _render_comparison(items: Iterable[VisualItem]) -> str:- """Options side by side. Auto-fit grid, so two read as two and six as six."""- cards = "".join(- '<div class="card option">'- f'<p class="label">{_e(item.label)}</p>'- f"{_detail(item)}"- + (- f'<p class="figure">{_e(_format_number(item.value))}</p>'- if item.value is not None- else ""- )- + "</div>"- for item in items- )- return f'<div class="grid">{cards}</div>'---def _render_timeline(items: Iterable[VisualItem]) -> str:- """Moments in order down a spine. The spine is a border on the list."""- rows = "".join(- '<li class="moment">'- f'<div class="card-text"><p class="label">{_e(item.label)}</p>'- f"{_detail(item)}</div>"- "</li>"- for item in items- )- return f'<ul class="timeline">{rows}</ul>'---def _render_bars(items: list[VisualItem]) -> str:- """Quantities against each other.-- The scale starts at zero — or at the lowest negative value, when there is- one — because a bar chart whose axis starts somewhere convenient overstates- every difference on it. Widths are the one thing computed in Python here;- there is no JavaScript to do it in the page.- """- values = [item.value for item in items if item.value is not None]- baseline = min([0.0, *values]) if values else 0.0- top = max(values) if values else 0.0- span = top - baseline-- rows: list[str] = []- for item in items:- if item.value is None:- width, figure = 0.0, "—"- else:- share = 1.0 if span <= 0 else (item.value - baseline) / span- width = max(_BAR_MIN_PCT, share * _BAR_MAX_PCT)- figure = _format_number(item.value)- rows.append(- '<li class="bar-row">'- f'<div class="bar-label"><span class="label">{_e(item.label)}</span>'- f"{_detail(item)}</div>"- '<div class="bar-track">'- f'<div class="bar-fill" style="width:{width:.1f}%"></div></div>'- f'<div class="bar-figure">{_e(figure)}</div>'- "</li>"- )- return f'<ul class="bars">{"".join(rows)}</ul>'---# One branch per entry in VISUAL_KINDS. A parity test pins the two together, so-# adding a kind without a renderer fails the suite instead of the user's turn.-_RENDERERS = {- "flow": lambda items: _render_flow(items),- "hierarchy": lambda items: _render_hierarchy(items),- "comparison": lambda items: _render_comparison(items),- "timeline": lambda items: _render_timeline(items),- "bars": lambda items: _render_bars(list(items)),-}---def _css() -> str:- b = BRAND- return (- "*{box-sizing:border-box}"- "body{margin:0;padding:38px 34px 46px;background:" + b["bg"] + ";"- "color:" + b["text"] + ";font:15px/1.55 'Segoe UI',system-ui,-apple-system,"- "'Helvetica Neue',Arial,sans-serif;-webkit-font-smoothing:antialiased}"- # header- "header{display:flex;align-items:center;gap:14px;margin-bottom:6px}"- ".mark{width:12px;height:12px;border-radius:3px;flex:none;"- "background:" + b["primary"] + ";box-shadow:0 0 16px " + b["primary_glow"] + "}"- ".kicker{font-size:11px;letter-spacing:.16em;text-transform:uppercase;"- "color:" + b["primary"] + ";font-weight:600}"- "h1{margin:2px 0 0;font-size:26px;line-height:1.25;font-weight:650;"- "letter-spacing:-.01em}"- ".meta{margin:14px 0 30px;color:" + b["text_muted"] + ";font-size:13px}"- # shared card- ".card{background:" + b["bg_card"] + ";border:1px solid " + b["border"] + ";"- "border-radius:14px;padding:14px 16px}"- ".label{margin:0;font-weight:600;font-size:15px;color:" + b["text"] + "}"- ".detail{margin:5px 0 0;font-size:13px;line-height:1.5;"- "color:" + b["text_muted"] + "}"- # flow- ".flow{display:flex;flex-wrap:wrap;align-items:stretch;gap:10px}"- ".flow .step{display:flex;gap:12px;align-items:flex-start;"- "flex:1 1 210px;min-width:180px;max-width:340px}"- ".num{flex:none;width:24px;height:24px;border-radius:8px;"- "background:" + b["primary"] + ";color:" + b["bg"] + ";font-size:12px;"- "font-weight:700;display:flex;align-items:center;justify-content:center}"- ".arrow{flex:none;align-self:center;color:" + b["primary_deep"] + ";"- "font-size:19px;line-height:1;padding:0 2px}"- # hierarchy- ".tree{list-style:none;margin:0;padding:0}"- ".tree .tree{margin:8px 0 2px 14px;padding-left:18px;"- "border-left:1px solid " + b["border_strong"] + "}"- ".branch{position:relative;margin:0 0 10px}"- ".tree .tree .branch::before{content:'';position:absolute;left:-18px;"- "top:22px;width:14px;height:1px;background:" + b["border_strong"] + "}"- ".node{border-left:2px solid " + b["primary_deep"] + "}"- # comparison- ".grid{display:grid;gap:12px;"- "grid-template-columns:repeat(auto-fit,minmax(210px,1fr))}"- ".figure{margin:10px 0 0;font-size:22px;font-weight:700;"- "color:" + b["primary"] + ";letter-spacing:-.01em}"- # timeline- ".timeline{list-style:none;margin:0;padding:0 0 0 26px;"- "border-left:2px solid " + b["border_strong"] + "}"- ".moment{position:relative;padding:0 0 22px}"- ".moment:last-child{padding-bottom:0}"- ".moment::before{content:'';position:absolute;left:-33px;top:4px;"- "width:11px;height:11px;border-radius:50%;background:" + b["primary"] + ";"- "border:2px solid " + b["bg"] + ";box-shadow:0 0 10px " + b["primary_glow"] + "}"- # bars- ".bars{list-style:none;margin:0;padding:0}"- ".bar-row{display:grid;grid-template-columns:minmax(120px,26%) 1fr auto;"- "gap:14px;align-items:center;padding:9px 0}"- ".bar-label .detail{margin-top:2px}"- ".bar-track{background:" + b["bg_elevated"] + ";border-radius:7px;height:26px;"- "border:1px solid " + b["border"] + ";overflow:hidden}"- ".bar-fill{height:100%;border-radius:6px;background:linear-gradient(90deg,"- + b["primary_deep"]- + ","- + b["primary"]- + ")}"- ".bar-figure{font-variant-numeric:tabular-nums;font-weight:650;"- "color:" + b["primary"] + ";min-width:56px;text-align:right}"- # footer- "footer{margin-top:32px;padding-top:16px;font-size:12px;"- "color:" + b["text_faint"] + ";border-top:1px solid " + b["border"] + "}"- # A narrow window (the detached Visualization window can be narrow)- # collapses the bar grid rather than squeezing three columns into it.- "@media (max-width:560px){.bar-row{grid-template-columns:1fr auto;}"- ".bar-track{grid-column:1/-1}}"- )---def render_visual_html(spec: VisualSpec) -> str:- """Return the complete, self-contained page for ``spec``."""- body = _RENDERERS[spec.kind](spec.items)- caption = f"<footer>{_e(spec.caption)}</footer>" if spec.caption else ""- meta = (- f'<p class="meta">{_e(spec.source_utterance)}</p>'- if spec.source_utterance- else ""- )- return (- "<!doctype html>"- '<html lang="en"><head><meta charset="utf-8">'- '<meta name="viewport" content="width=device-width,initial-scale=1">'- f"<title>{_e(spec.title)}</title>"- f"<style>{_css()}</style></head><body>"- '<header><span class="mark"></span>'- '<div><div class="kicker">Visualisation</div>'- f"<h1>{_e(spec.title)}</h1></div></header>"- f"{meta}"- f"{body}"- f"{caption}"- "</body></html>"- )---__all__ = ["render_visual_html"]diff --git a/jarvis/visuals/spec.py b/jarvis/visuals/spec.pydeleted file mode 100644index 6eceb10ab1..0000000000--- a/jarvis/visuals/spec.py+++ /dev/null@@ -1,240 +0,0 @@-"""What a caller has to supply for a picture, and how loose input becomes it.--The model supplies the STRUCTURE (five steps, three options, a tree of parts);-Python owns the drawing. That split is the whole reason this feature is cheap:-asking a model to emit HTML means hundreds of output tokens per picture, a-different layout every time, and a page nobody validated before serving it.-Asking for a dozen short labels costs a fraction of that, renders identically-on every run, and can be checked before a single byte reaches disk.--So this module is deliberately strict. Every limit below is a real defence:--* the item/child/depth caps bound both the output tokens a model can spend and- the size of the page — a "visualise the whole codebase" answer degrades to a- refusal with a reason, never to a 4 MB document;-* the text caps stop one runaway label from destroying a layout that has no- JavaScript to reflow it;-* unknown kinds are rejected by name so the model's next attempt can be right,- rather than silently falling back to a shape the user did not ask for.--:class:`VisualSpecError` carries a message written FOR the model — it is handed-back as the tool error, and a precise one turns a failed call into a corrected-retry instead of an apology to the user.-"""--from __future__ import annotations--from collections.abc import Mapping, Sequence-from dataclasses import dataclass, field-from typing import Any, Final--# --- The five shapes ------------------------------------------------------# One entry per branch in `render._render_body`; a parity test pins the three-# lists (this tuple, the tool schema enum, the renderer branches) together.-VISUAL_KINDS: Final[tuple[str, ...]] = (- "flow", # ordered steps, one arrow to the next- "hierarchy", # parts within parts, indented- "comparison", # options side by side- "timeline", # moments in order, down a spine- "bars", # quantities against each other-)--# Structure caps. See the module docstring for what each one defends.-MAX_ITEMS: Final = 12-MAX_CHILDREN: Final = 8-MAX_DEPTH: Final = 3-# Text caps. Generous enough for a real label, tight enough that no single-# string can break a JavaScript-free layout.-MAX_TITLE_CHARS: Final = 120-MAX_LABEL_CHARS: Final = 80-MAX_DETAIL_CHARS: Final = 220-MAX_CAPTION_CHARS: Final = 300---class VisualSpecError(ValueError):- """Rejected input, with a message the model can act on.-- A ``ValueError`` subclass so a caller that only catches ``ValueError``- still behaves, and a named type so the tool can tell "your spec was wrong"- (retryable) apart from "the disk was full" (not).- """---@dataclass(frozen=True)-class VisualItem:- """One box, row, bar or moment.-- ``value`` is read only by ``bars`` and ``children`` only by ``hierarchy``;- both are accepted (and ignored) elsewhere rather than rejected, because a- model that supplies one field too many has still described the picture- correctly, and failing that call would cost a whole retry for nothing.- """-- label: str- detail: str = ""- value: float | None = None- children: tuple[VisualItem, ...] = ()---@dataclass(frozen=True)-class VisualSpec:- """A complete, validated description of one picture."""-- title: str- kind: str- items: tuple[VisualItem, ...]- caption: str = ""- # What the user actually said, kept for the archive's run label. Never- # drawn on the page: the title is the model's summary of the request and- # reads better; the raw utterance is metadata, not a heading.- source_utterance: str = field(default="", compare=False)---def _clean_text(value: Any, *, limit: int, what: str, required: bool = False) -> str:- """Collapse whitespace, enforce the cap, reject the empty required case.-- Truncation over rejection for over-long text: the model described the right- picture and simply wrote too much, so a clipped label still produces the- page the user asked for. A MISSING label is different — that is a hole in- the structure, and the model has to fix it.- """- if value is None:- text = ""- elif isinstance(value, str):- text = " ".join(value.split())- elif isinstance(value, (int, float, bool)):- text = str(value)- else:- raise VisualSpecError(f"{what} must be text, got {type(value).__name__}.")- if required and not text:- raise VisualSpecError(f"{what} must not be empty.")- if len(text) > limit:- text = text[: limit - 1].rstrip() + "…"- return text---def _parse_value(raw: Any, *, where: str) -> float | None:- """A bar length, or None when the item carries no quantity."""- if raw is None or raw == "":- return None- try:- number = float(raw)- except (TypeError, ValueError):- raise VisualSpecError(- f"{where}: 'value' must be a number (or omitted), got {raw!r}."- ) from None- if number != number or number in (float("inf"), float("-inf")): # NaN/inf- raise VisualSpecError(f"{where}: 'value' must be a finite number.")- return number---def _parse_items(- raw: Any,- *,- where: str,- depth: int,- limit: int,-) -> tuple[VisualItem, ...]:- """Validate one level of the item list, recursing into ``children``."""- if isinstance(raw, Mapping) or isinstance(raw, (str, bytes)):- raise VisualSpecError(f"{where} must be a list of items.")- if not isinstance(raw, Sequence):- raise VisualSpecError(f"{where} must be a list of items.")- if not raw:- raise VisualSpecError(f"{where} must contain at least one item.")- if len(raw) > limit:- raise VisualSpecError(- f"{where} has {len(raw)} items; at most {limit} fit on one page. "- f"Group them or draw the most important {limit}."- )-- items: list[VisualItem] = []- for index, entry in enumerate(raw):- spot = f"{where}[{index}]"- # A bare string is a perfectly clear item ("Build", "Test", "Ship") and- # is the cheapest thing a model can emit, so it is accepted as shorthand.- if isinstance(entry, str):- label = _clean_text(entry, limit=MAX_LABEL_CHARS, what=spot, required=True)- items.append(VisualItem(label=label))- continue- if not isinstance(entry, Mapping):- raise VisualSpecError(f"{spot} must be an object with a 'label', or a plain string.")-- children: tuple[VisualItem, ...] = ()- raw_children = entry.get("children")- if raw_children:- if depth >= MAX_DEPTH:- raise VisualSpecError(- f"{spot}: nesting is capped at {MAX_DEPTH} levels — "- f"flatten the deeper parts into their parent's detail."- )- children = _parse_items(- raw_children, where=f"{spot}.children", depth=depth + 1, limit=MAX_CHILDREN- )-- items.append(- VisualItem(- label=_clean_text(- entry.get("label"), limit=MAX_LABEL_CHARS, what=f"{spot}.label", required=True- ),- detail=_clean_text(- entry.get("detail"), limit=MAX_DETAIL_CHARS, what=f"{spot}.detail"- ),- value=_parse_value(entry.get("value"), where=spot),- children=children,- )- )- return tuple(items)---def parse_spec(payload: Mapping[str, Any], *, source_utterance: str = "") -> VisualSpec:- """Validate model-supplied arguments into a :class:`VisualSpec`.-- Raises:- VisualSpecError: with a message aimed at the model, never at the user.- """- if not isinstance(payload, Mapping):- raise VisualSpecError("The visualisation arguments must be an object.")-- kind = str(payload.get("kind") or "").strip().lower()- if kind not in VISUAL_KINDS:- raise VisualSpecError(- f"Unknown kind {kind or '(missing)'!r}. Pick one of: {', '.join(VISUAL_KINDS)}."- )-- spec = VisualSpec(- title=_clean_text(- payload.get("title"), limit=MAX_TITLE_CHARS, what="'title'", required=True- ),- kind=kind,- items=_parse_items(payload.get("items"), where="'items'", depth=1, limit=MAX_ITEMS),- caption=_clean_text(payload.get("caption"), limit=MAX_CAPTION_CHARS, what="'caption'"),- source_utterance=" ".join((source_utterance or "").split()),- )-- # A bar chart with no numbers is a bullet list wearing a costume: every bar- # would be full width and the picture would say nothing. Caught here rather- # than papered over in the renderer, so the model can supply the numbers.- if kind == "bars" and not any(item.value is not None for item in spec.items):- raise VisualSpecError(- "kind 'bars' needs a numeric 'value' on at least one item — "- "without numbers there is nothing to compare. Use 'comparison' for "- "options that have no quantity."- )- return spec---__all__ = [- "MAX_CAPTION_CHARS",- "MAX_CHILDREN",- "MAX_DEPTH",- "MAX_DETAIL_CHARS",- "MAX_ITEMS",- "MAX_LABEL_CHARS",- "MAX_TITLE_CHARS",- "VISUAL_KINDS",- "VisualItem",- "VisualSpec",- "VisualSpecError",- "parse_spec",-]diff --git a/jarvis/visuals/store.py b/jarvis/visuals/store.pydeleted file mode 100644index e2154d5f4b..0000000000--- a/jarvis/visuals/store.py+++ /dev/null@@ -1,132 +0,0 @@-"""Write a rendered visualisation where the app already looks for pictures.--The Visualization section deliberately owns no storage: it reads the run-archive through ``/api/outputs`` and shows the files a window can draw (see-``useVisualArtifacts.ts``). Giving on-demand pictures their own directory and-their own REST route would mean a second archive, a second listing, a second-retention story — and the gallery would still not show them.--So a picture is archived as what it is: a small run that produced one-deliverable. That means matching two conventions exactly, both enforced by the-read side rather than by anything here:--* the run directory name is ``<ts>__<utterance>__<short-hex>``, the shape- ``outputs_routes._SLUG_RE`` parses to recover the timestamp and the label- under the tile;-* the file sits at ``tasks/<id>/artifacts/files/<name>``, the only subtree- ``outputs_routes`` will list or serve — anything else is invisible by design,- not by accident.--There is no git work here, unlike a worker mission: nothing is diffed and-nothing is reviewed, so a plain directory is the whole requirement.-"""--from __future__ import annotations--import logging-import os-import re-import time-import uuid-from dataclasses import dataclass-from pathlib import Path--from jarvis.core.paths import repo_root-from jarvis.missions.isolation.worktree import resolve_outputs_root-from jarvis.missions.standalone_run import write_marker--log = logging.getLogger(__name__)--# The task directory every on-demand picture lands in. Worktree-style-# ``NN__label`` so the mission map renders it as "01 · Visualization" instead-# of the anonymous "Step 1" it falls back to for hex names.-TASK_DIR_NAME = "01__visualization"--# Windows still enforces MAX_PATH for many callers, and the archive path is-# already deep (run / tasks / id / artifacts / files / name). Both parts are-# clipped well short of it — the label is decoration, the hex keeps it unique.-_MAX_SLUG_LABEL = 48-_MAX_FILENAME_STEM = 40--_NON_SLUG_RE = re.compile(r"[^a-z0-9]+")---@dataclass(frozen=True)-class StoredVisual:- """Where the picture ended up, in the terms the read surfaces use."""-- slug: str- """Run directory name — the ``/api/outputs/{slug}`` path segment."""- artifact_path: str- """Posix path inside the run, as ``/artifacts`` lists it."""- file: Path- """Absolute path on disk, for "show in folder" and for tests."""---def _slugify(value: str, *, limit: int) -> str:- out = _NON_SLUG_RE.sub("-", (value or "").lower()).strip("-")- if len(out) > limit:- out = out[:limit].rstrip("-")- return out or "visualization"---def _outputs_root() -> Path:- """The archive root, resolved the same way every other write path does.-- ``resolve_outputs_root`` already honours ``JARVIS_ISOLATION_ROOT`` and- ``JARVIS_DATA_DIR``, so a headless or non-root install writes where the- rest of the app writes — no separate environment contract for pictures.- """- return resolve_outputs_root(repo_root())---def store_visual(- html: str,- *,- title: str,- utterance: str = "",- outputs_root: Path | None = None,-) -> StoredVisual:- """Archive one rendered page and return where it landed.-- Inputs:- html: the complete document from ``render_visual_html``.- title: the picture's title — the filename stem and the fallback label.- utterance: what the user asked, used for the run label under the tile.- outputs_root: override for the archive root (tests).-- Raises:- OSError: the archive is not writable. Left to the caller: a picture- that could not be saved is a failed tool call, not a silent- success with nothing behind the link (AP "no silent except").- """- root = Path(outputs_root) if outputs_root is not None else _outputs_root()-- label = _slugify(utterance or title, limit=_MAX_SLUG_LABEL)- slug = f"{time.strftime('%Y%m%dT%H%M%S')}__{label}__{uuid.uuid4().hex[:8]}"- filename = f"{_slugify(title, limit=_MAX_FILENAME_STEM)}.html"-- run_dir = root / slug- directory = run_dir / "tasks" / TASK_DIR_NAME / "artifacts" / "files"- directory.mkdir(parents=True, exist_ok=True)- target = directory / filename-- # Without this the run is written correctly and never listed: the Outputs- # list hides worktree-slug directories, which have a mission_<short>- # sibling carrying their identity. This one has no sibling and no mission- # row — the marker is how it says so. See jarvis/missions/standalone_run.py.- write_marker(run_dir, kind="visualization", utterance=utterance, title=title)-- # Written whole, then moved into place: the gallery polls this tree, and a- # partially-flushed HTML file would render as a blank frame at exactly the- # moment the user is watching for the picture to appear.- staging = target.with_name(f".{filename}.part")- staging.write_text(html, encoding="utf-8")- os.replace(staging, target)-- artifact_path = f"tasks/{TASK_DIR_NAME}/artifacts/files/{filename}"- log.info("visualization_archived slug=%s file=%s", slug, filename)- return StoredVisual(slug=slug, artifact_path=artifact_path, file=target)---__all__ = ["TASK_DIR_NAME", "StoredVisual", "store_visual"]diff --git a/jarvis/voice/action_phrases.py b/jarvis/voice/action_phrases.pyindex 6992fbca0e..d71fbac7ff 100644--- a/jarvis/voice/action_phrases.py+++ b/jarvis/voice/action_phrases.py@@ -382,6 +382,23 @@ _PHRASES: dict[str, dict[str, str]] = {"en": "I can't start the task right now. Please restart me.","es": "No puedo iniciar la tarea ahora. Reiníciame, por favor.",},+ # ``create_artifact`` handed the page to a background agent. The promise+ # names the artifact and says the result will be announced — the tool's+ # fallback when the brain supplied no ``spoken_ack`` of its own.+ "artifact_building": {+ "de": ( # i18n-allow+ "Ich baue „{title}“ im Hintergrund und sage Bescheid, sobald es fertig ist."+ ),+ "en": "I'm building “{title}” in the background and will tell you when it's ready.",+ "es": "Estoy creando «{title}» en segundo plano y te aviso cuando esté listo.",+ },+ "artifact_revising": {+ "de": ( # i18n-allow+ "Ich überarbeite „{title}“ im Hintergrund und sage Bescheid, sobald es fertig ist."+ ),+ "en": "I'm revising “{title}” in the background and will tell you when it's ready.",+ "es": "Estoy revisando «{title}» en segundo plano y te aviso cuando esté listo.",+ },# Scheduled-routine failures (jarvis/workflows). A broken routine used to# vanish into a log line, which is the maintainer's exact complaint: "you# tell him something and nothing happens" (AU-12 / AU-13). ``{name}`` is thediff --git a/pyproject.toml b/pyproject.tomlindex b1fc428a97..3c789dbc61 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -750,13 +750,14 @@ inspect-pointer = "jarvis.plugins.tool.inspect_pointer:InspectPointerTool"# Publishes NavigateSidebar; the frontend switches the section. Never a spawn# (AP-5/AP-14). See ADR-0011 amendment "Navigate tool".navigate = "jarvis.plugins.tool.navigate:NavigateTool"-# On-demand visualisation (2026-08-11) — draw the thing under discussion when-# the user explicitly asks to SEE it ("visualisier mir das", "draw me a-# flowchart"). Router-tier, risk safe: renders one HTML artifact into the run-# archive and publishes NavigateSidebar. ASK-ONLY — withheld from the tool set-# on every turn that did not ask (jarvis/brain/visualize_gate.py). Never a-# spawn (AP-5/AP-14).-visualize = "jarvis.plugins.tool.visualize:VisualizeTool"+# On-demand artifact (2026-08-23) — build one self-contained HTML page when+# the user explicitly asks to SEE something ("visualisier mir das", "mach mir+# ein Dashboard", "build me an artifact"). Router-tier dispatch to the mission+# stack (a worker on the strongest model writes the page), risk monitor like+# spawn-worker; publishes NavigateSidebar. ASK-ONLY — withheld from the tool+# set on every turn that did not ask (jarvis/brain/artifact_gate.py). Never in+# a worker set (AP-5/AP-14).+create-artifact = "jarvis.plugins.tool.create_artifact:CreateArtifactTool"# Command Registry executor (2026-07-09) — run ONE curated app command# (provider switch, wake word, language, volume, missions/tasks, restart)# through the SAME REST endpoint the UI uses, in-process via ASGI. Enum-diff --git a/scripts/ci/german-allowlist.txt b/scripts/ci/german-allowlist.txtindex 36f53b59d4..9a6febc44f 100644--- a/scripts/ci/german-allowlist.txt+++ b/scripts/ci/german-allowlist.txt@@ -461,5 +461,5 @@ docs/commands-reference.md# impossible inside a docstring (reason 3, same rationale as# navigation_intent.py / local_action_gate.py). Its hide-wiring test feeds# German voice fixtures — content under test (reason 4). ----jarvis/brain/visualize_gate.py-tests/unit/brain/test_visualize_tool_hide.py+jarvis/brain/artifact_gate.py+tests/unit/brain/test_artifact_tool_hide.pydiff --git a/tests/unit/artifacts/test_brief.py b/tests/unit/artifacts/test_brief.pynew file mode 100644index 0000000000..ca9a6503f8--- /dev/null+++ b/tests/unit/artifacts/test_brief.py@@ -0,0 +1,90 @@+"""The artifact brief — what a worker is told, pinned.++The brief is the one text that decides whether a mission returns an artifact+(one self-contained page that renders in the app's sandbox) or a project+scaffold. So what is tested is the contract, not the prose: the file rule, the+no-network rule, the language, the brand palette, the quality lead the Outputs+rail strips, and the revision block that carries the previous page.+"""++from __future__ import annotations++from jarvis.artifacts.brief import (+ MAX_PREVIOUS_HTML_CHARS,+ artifact_filename,+ build_artifact_brief,+)+from jarvis.missions.stream_evidence import clean_request_body+from jarvis.visuals.brand import BRAND+++def test_filename_comes_from_the_title_and_stays_short() -> None:+ assert artifact_filename("Sales dashboard — Q3 2026") == "sales-dashboard-q3-2026.html"+ assert artifact_filename(" ") == "artifact.html"+ long = artifact_filename("x" * 200)+ assert long.endswith(".html") and len(long) <= 48 + len(".html")+++def test_brief_states_the_single_file_and_no_network_contract() -> None:+ brief = build_artifact_brief(+ "Compare the three plans by price and features.",+ title="Plan comparison",+ language="en",+ )+ assert brief.filename == "plan-comparison.html"+ assert brief.revision is False+ prompt = brief.prompt+ assert "Exactly ONE self-contained HTML file named `plan-comparison.html`" in prompt+ assert "no CDN scripts, no web fonts" in prompt+ assert "JavaScript is allowed" in prompt+ assert "`<title>` that names the artifact: `Plan comparison`" in prompt+ assert "written in English" in prompt+ assert "Compare the three plans by price and features." in prompt+ # Brand palette rides along so the page matches the app.+ assert BRAND["primary"] in prompt and BRAND["bg"] in prompt+ assert "prefers-color-scheme: light" in prompt+++def test_language_code_lands_in_the_html_lang_and_the_content_rule() -> None:+ prompt = build_artifact_brief("Zeig die Zahlen.", title="Zahlen", language="de").prompt+ assert '<html lang="de">' in prompt+ assert "written in German" in prompt+++def test_outputs_rail_sees_the_artifact_line_not_the_quality_lead() -> None:+ """``clean_request_body`` strips the first paragraph by its phrasing — the+ brief keeps that phrasing so the rail shows "Artifact: <title>" first."""+ brief = build_artifact_brief("Build it.", title="Team roster", language="en")+ body = clean_request_body(brief.prompt)+ assert body.startswith("Artifact: Team roster\nBuild it.")+ assert "production-quality" not in body.split("\n\n", 1)[0]+++def test_revision_carries_the_previous_page_and_keeps_its_filename() -> None:+ previous = "<!doctype html><html><head><title>Old</title></head><body>v1</body></html>"+ brief = build_artifact_brief(+ "Make the bars red.",+ title="Old",+ language="en",+ previous_html=previous,+ previous_filename="old-page.html",+ )+ assert brief.revision is True+ assert brief.filename == "old-page.html"+ assert "## Starting point" in brief.prompt+ assert previous in brief.prompt+ assert "Rewrite the ENTIRE file `old-page.html`" in brief.prompt+++def test_an_oversized_previous_page_is_clipped_head_and_tail() -> None:+ huge = "A" * (MAX_PREVIOUS_HTML_CHARS + 5_000) + "ZEND"+ brief = build_artifact_brief("Tweak.", title="Huge", language="en", previous_html=huge)+ assert "middle of the previous version omitted" in brief.prompt+ assert brief.prompt.rstrip("`\n").endswith("ZEND")+ assert len(brief.prompt) < MAX_PREVIOUS_HTML_CHARS + 6_000+++def test_brief_is_deterministic() -> None:+ a = build_artifact_brief("Same.", title="Same", language="es")+ b = build_artifact_brief("Same.", title="Same", language="es")+ assert a == bdiff --git a/tests/unit/artifacts/test_locate.py b/tests/unit/artifacts/test_locate.pynew file mode 100644index 0000000000..d06518ddc5--- /dev/null+++ b/tests/unit/artifacts/test_locate.py@@ -0,0 +1,62 @@+"""Finding an existing artifact for a revision — by title, or the newest one.++The archive layout is the real one (``<run>/tasks/<id>/artifacts/files/``), so+the test writes that shape into a temp root rather than faking the walker.+"""++from __future__ import annotations++import os+import time+from pathlib import Path++from jarvis.artifacts.locate import locate_artifact+++def _page(root: Path, run: str, name: str, title: str, *, age_s: float = 0.0) -> Path:+ directory = root / run / "tasks" / "019e0001" / "artifacts" / "files"+ directory.mkdir(parents=True, exist_ok=True)+ file = directory / name+ file.write_text(+ f"<!doctype html><html><head><title>{title}</title></head><body>x</body></html>",+ encoding="utf-8",+ )+ stamp = time.time() - age_s+ os.utime(file, (stamp, stamp))+ os.utime(root / run, (stamp, stamp))+ return file+++def test_latest_is_the_newest_page_across_runs(tmp_path: Path) -> None:+ _page(tmp_path, "mission_old", "old.html", "Old dashboard", age_s=600)+ newest = _page(tmp_path, "mission_new", "new.html", "New dashboard", age_s=10)+ found = locate_artifact("latest", outputs_roots=(tmp_path,))+ assert found is not None+ assert found.file == newest+ assert found.slug == "mission_new"+ assert found.artifact_path == "tasks/019e0001/artifacts/files/new.html"+ assert found.title == "New dashboard"+ assert "<title>New dashboard</title>" in found.html+++def test_a_title_fragment_matches_case_and_punctuation_insensitively(tmp_path: Path) -> None:+ _page(tmp_path, "mission_a", "plans.html", "Plan comparison — Q3", age_s=100)+ _page(tmp_path, "mission_b", "roster.html", "Team roster", age_s=50)+ found = locate_artifact("PLAN COMPARISON", outputs_roots=(tmp_path,))+ assert found is not None and found.title == "Plan comparison — Q3"+ by_stem = locate_artifact("roster", outputs_roots=(tmp_path,))+ assert by_stem is not None and by_stem.file.name == "roster.html"+++def test_no_match_is_none_not_a_guess(tmp_path: Path) -> None:+ _page(tmp_path, "mission_a", "plans.html", "Plan comparison", age_s=100)+ assert locate_artifact("budget forecast", outputs_roots=(tmp_path,)) is None+ assert locate_artifact("", outputs_roots=(tmp_path,)) is None+ assert locate_artifact("latest", outputs_roots=(tmp_path / "missing",)) is None+++def test_only_html_deliverables_count(tmp_path: Path) -> None:+ directory = tmp_path / "mission_a" / "tasks" / "019e0001" / "artifacts" / "files"+ directory.mkdir(parents=True)+ (directory / "notes.md").write_text("# not a page", encoding="utf-8")+ assert locate_artifact("latest", outputs_roots=(tmp_path,)) is Nonediff --git a/tests/unit/brain/test_visualize_gate.py b/tests/unit/brain/test_artifact_gate.pysimilarity index 61%rename from tests/unit/brain/test_visualize_gate.pyrename to tests/unit/brain/test_artifact_gate.pyindex d9af7947c4..6bdcd5588d 100644--- a/tests/unit/brain/test_visualize_gate.py+++ b/tests/unit/brain/test_artifact_gate.py@@ -1,13 +1,15 @@-"""Tests for the explicit-request gate in front of the ``visualize`` tool.+"""Tests for the explicit-request gate in front of the ``create_artifact`` tool.The contract is asymmetric on purpose. A missed request costs one extra turn —-the user repeats themselves and gets their picture. An unasked-for picture is-the failure this gate exists to prevent (maintainer mandate 2026-08-11: "only-when someone says they want to understand it visually"), so the negative list-is the important half of this file and carries the real regressions:--* the utterance that opens the EXISTING gallery must never draw a new picture- (that is ``navigate``'s job, and both share the word "Visualisierung"),+the user repeats themselves and gets their artifact. An unasked-for artifact+is the failure this gate exists to prevent (maintainer mandate 2026-08-11:+"only when someone says they want to understand it visually"; 2026-08-23: an+artifact is asked for by name), so the negative list is the important half of+this file and carries the real regressions:++* the utterance that opens the EXISTING section must never build a new page+ (that is ``navigate``'s job, and both share the words "Visualisierung" and+ "Artefakt"),* a question about the word is not a request for the thing,* an ordinary turn that merely mentions a chart is not a request either.@@ -17,7 +19,7 @@ from __future__ import annotationsimport pytest-from jarvis.brain.visualize_gate import wants_visualization+from jarvis.brain.artifact_gate import wants_artifact# Turns that ask, in the user's own words, to be shown something as a picture._WANTS = [@@ -46,6 +48,17 @@ _WANTS = [# a nav verb followed by "of/for" is still a request for a NEW picture"zeig mir eine visualisierung von den zahlen", # i18n-allow: DE test vocabulary"show me a visualization of the results",+ # the artifact by name, and the page shapes that are artifacts+ "mach mir ein artefakt daraus", # i18n-allow: German speech-input test vocabulary+ "ich möchte ein artefakt davon", # i18n-allow: German speech-input test vocabulary+ "build me an artifact for this",+ "turn that into an artifact",+ "bau mir ein dashboard mit den zahlen", # i18n-allow: German speech-input test vocabulary+ "make an infographic of the results",+ "mach mir eine html-seite dazu", # i18n-allow: German speech-input test vocabulary+ "erstell mir einen bericht als seite", # i18n-allow: German speech-input test vocabulary+ "build me a report page on this",+ "hazme una página con eso", # i18n-allow: Spanish speech-input test vocabulary]# Turns that must leave the tool out of the set entirely.@@ -58,15 +71,22 @@ _DOES_NOT_WANT = ["show the visualizations","switch to visuals","muestrame las visualizaciones", # i18n-allow: Spanish speech-input test vocabulary+ "zeig mir die artefakte", # i18n-allow: German speech-input test vocabulary+ "open the artifacts section",+ "geh zu den artefakten", # i18n-allow: German speech-input test vocabulary# a question about the word, answered with words"was ist eine visualisierung", # i18n-allow: German speech-input test vocabulary"was bedeutet datenvisualisierung", # i18n-allow: German speech-input test vocabulary"what is a flowchart","explain what a mindmap is",+ "was ist ein artefakt", # i18n-allow: German speech-input test vocabulary+ "what is an artifact"# ordinary turns that merely mention something chart-shaped"der chart ist heute rot", # i18n-allow: German speech-input test vocabulary"wie ist der bitcoin chart gerade", # i18n-allow: German speech-input test vocabulary"das diagramm im bericht war falsch", # i18n-allow: German speech-input test vocabulary+ "die seite war heute langsam", # i18n-allow: German speech-input test vocabulary+ "the report is due on friday",# the everyday turns this gate keeps cheap"wie spät ist es", # i18n-allow: German speech-input test vocabulary"was haben wir gerade besprochen", # i18n-allow: German speech-input test vocabulary@@ -83,26 +103,29 @@ _DOES_NOT_WANT = [@pytest.mark.parametrize("text", _WANTS)def test_explicit_requests_open_the_gate(text: str) -> None:- assert wants_visualization(text) is True, text+ assert wants_artifact(text) is True, text@pytest.mark.parametrize("text", _DOES_NOT_WANT)def test_everything_else_keeps_the_gate_shut(text: str) -> None:- assert wants_visualization(text) is False, text+ assert wants_artifact(text) is False, textdef test_navigation_beats_the_drawing_verb() -> None:- """The shared word must resolve to navigation, not to a new picture.+ """The shared word must resolve to navigation, not to a new page.- "Visualisierung" is both the section name and the thing being asked for.- Rule order (navigation first) is what keeps ``navigate`` reachable, so it- is pinned here rather than left to the parametrized lists.+ "Visualisierung" and "Artefakt" are both the section name and the thing+ being asked for. Rule order (navigation first) is what keeps ``navigate``+ reachable, so it is pinned here rather than left to the parametrized lists."""- assert wants_visualization("zeig mir die visualisierungen") is False # i18n-allow: input vocab- assert wants_visualization("visualisier mir die zahlen") is True # i18n-allow: input vocab+ assert wants_artifact("zeig mir die visualisierungen") is False # i18n-allow: input vocab+ assert wants_artifact("zeig mir die artefakte") is False # i18n-allow: input vocab+ assert wants_artifact("visualisier mir die zahlen") is True # i18n-allow: input vocab+ assert wants_artifact("zeig mir ein artefakt von den zahlen") is True # i18n-allow: input vocabdef test_a_visual_noun_alone_is_not_a_request() -> None:- """Without a producing verb, "diagram" is just a word in a sentence."""- assert wants_visualization("das diagramm") is False # i18n-allow: input vocab- assert wants_visualization("timeline") is False+ """Without a producing verb, "diagram" or "page" is just a word in a sentence."""+ assert wants_artifact("das diagramm") is False # i18n-allow: input vocab+ assert wants_artifact("timeline") is False+ assert wants_artifact("die webseite") is False # i18n-allow: input vocabdiff --git a/tests/unit/brain/test_visualize_tool_hide.py b/tests/unit/brain/test_artifact_tool_hide.pysimilarity index 52%rename from tests/unit/brain/test_visualize_tool_hide.pyrename to tests/unit/brain/test_artifact_tool_hide.pyindex 8b3ceac441..848985053a 100644--- a/tests/unit/brain/test_visualize_tool_hide.py+++ b/tests/unit/brain/test_artifact_tool_hide.py@@ -1,13 +1,14 @@-"""The ``visualize`` tool is offered only on a turn that asked for a picture.+"""The ``create_artifact`` tool is offered only on a turn that asked for one.-Maintainer mandate (2026-08-11): a visualisation is something the user asks-for — "visualisier mir das", "zeig mir das bildlich" — never something the-assistant decides an answer would benefit from. Prompt wording does not hold-that line reliably, so the enforcement is structural: on any other turn the-tool is removed from the surface and the model cannot call what it cannot see.+Maintainer mandate (2026-08-11, artifacts 2026-08-23): an artifact is+something the user asks for — "visualisier mir das", "mach ein Artefakt+draus" — never something the assistant decides an answer would benefit from.+Prompt wording does not hold that line reliably, so the enforcement is+structural: on any other turn the tool is removed from the surface and the+model cannot call what it cannot see.This pins the gate's placement in ``BrainManager``. The vocabulary itself is-tested in ``test_visualize_gate.py``; here the questions are narrower — does+tested in ``test_artifact_gate.py``; here the questions are narrower — doesthe manager actually strip it, does it leave every other tool alone, and does afault in the gate fail OPEN (tools unchanged) rather than blinding the brain."""@@ -22,7 +23,7 @@ def _mgr() -> BrainManager:def _surface() -> dict:return {- "visualize": object(), # the gated one+ "create_artifact": object(), # the gated one"navigate": object(), # opens the EXISTING gallery — never gated"search_web": object(),"screenshot": object(),@@ -31,56 +32,56 @@ def _surface() -> dict:def test_an_explicit_request_keeps_the_tool():- out = _mgr()._hide_visualize_tool_without_request(+ out = _mgr()._hide_artifact_tool_without_request(_surface(), "visualisier mir das mal" # i18n-allow: DE test vocabulary)- assert "visualize" in out+ assert "create_artifact" in outdef test_an_ordinary_turn_loses_it():- out = _mgr()._hide_visualize_tool_without_request(+ out = _mgr()._hide_artifact_tool_without_request(_surface(), "was haben wir gerade besprochen" # i18n-allow: DE test vocabulary)- assert "visualize" not in out+ assert "create_artifact" not in outdef test_nothing_else_is_touched():"""The gate owns exactly one name."""- out = _mgr()._hide_visualize_tool_without_request(_surface(), "wie spät ist es")+ out = _mgr()._hide_artifact_tool_without_request(_surface(), "wie spät ist es")assert set(out) == {"navigate", "search_web", "screenshot", "spawn_worker"}def test_opening_the_gallery_does_not_draw_a_new_picture():- """"Zeig mir die Visualisierungen" is navigate's turn, not visualize's.+ """"Zeig mir die Visualisierungen" is navigate's turn, not create_artifact's.The regression that makes this worth its own test: both features answer to- the same word, and a visualize tool left on the surface here would produce- a brand-new picture instead of showing the ones already there.+ the same word, and an artifact tool left on the surface here would start a+ background build instead of showing the pages already there."""- out = _mgr()._hide_visualize_tool_without_request(+ out = _mgr()._hide_artifact_tool_without_request(_surface(), "zeig mir die visualisierungen" # i18n-allow: DE test vocabulary)- assert "visualize" not in out+ assert "create_artifact" not in outassert "navigate" in outdef test_a_surface_without_the_tool_is_returned_untouched():surface = {"search_web": object()}- assert _mgr()._hide_visualize_tool_without_request(surface, "hallo") is surface+ assert _mgr()._hide_artifact_tool_without_request(surface, "hallo") is surfacedef test_a_gate_fault_fails_open(monkeypatch):"""A gate bug must never cost the brain a tool it was supposed to have."""- import jarvis.brain.visualize_gate as gate+ import jarvis.brain.artifact_gate as gatedef _boom(_text: str) -> bool:raise RuntimeError("gate exploded")- monkeypatch.setattr(gate, "wants_visualization", _boom)- out = _mgr()._hide_visualize_tool_without_request(_surface(), "anything")- assert "visualize" in out+ monkeypatch.setattr(gate, "wants_artifact", _boom)+ out = _mgr()._hide_artifact_tool_without_request(_surface(), "anything")+ assert "create_artifact" in outdef test_a_non_dict_surface_is_passed_through():sentinel = ["not", "a", "dict"]- assert _mgr()._hide_visualize_tool_without_request(sentinel, "visualisier das") is sentinel+ assert _mgr()._hide_artifact_tool_without_request(sentinel, "visualisier das") is sentineldiff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.pyindex bb1618147f..a19d58140c 100644--- a/tests/unit/brain/test_routing.py+++ b/tests/unit/brain/test_routing.py@@ -1985,19 +1985,20 @@ def test_router_tools_is_pure_dispatcher_set() -> None:# never a spawn (AP-5/AP-14). See ADR-0011 amendment# "MCP-Tools Virtual Loader"."mcp-tools",- # On-demand visualisation (2026-08-11, maintainer mandate): draws- # what is under discussion as a flow / hierarchy / comparison /- # timeline / bar chart, archives it in the run tree, and opens the- # Visualization section. Risk safe (writes one artifact of its own,- # touches nothing else), never a spawn (AP-5/AP-14).+ # On-demand artifact (2026-08-23, maintainer mandate; rebuilt from+ # the 2026-08-11 visualize tool): builds ONE self-contained HTML+ # page through the mission stack on the strongest model and shows+ # it full-size in the Artifacts section. Risk monitor — a dispatch+ # like spawn-worker — never in a worker set (AP-5/AP-14). See+ # ADR-0011 amendment "create-artifact".## Router-tier membership makes it REACHABLE; it is emphatically not# ambient. The tool is removed from the surface on every turn whose- # utterance does not explicitly ask for a picture- # (BrainManager._hide_visualize_tool_without_request over- # jarvis/brain/visualize_gate.py), because the mandate is that a- # visualisation is asked for, never volunteered.- "visualize",+ # utterance does not explicitly ask for an artifact+ # (BrainManager._hide_artifact_tool_without_request over+ # jarvis/brain/artifact_gate.py), because the mandate is that an+ # artifact is asked for, never volunteered.+ "create-artifact",# Assistant modes (2026-08-13, maintainer mandate): the assistant's# own character. list-modes (safe, property read), switch-mode# (monitor, changes tone only and is visible on screen the moment itdiff --git a/tests/unit/plugins/tool/test_create_artifact.py b/tests/unit/plugins/tool/test_create_artifact.pynew file mode 100644index 0000000000..8e733fe5f1--- /dev/null+++ b/tests/unit/plugins/tool/test_create_artifact.py@@ -0,0 +1,202 @@+"""Tests for the ``create_artifact`` router tool.++The tool is a dispatcher: validate, brief, hand to the mission stack, promise+aloud. What is worth pinning is each seam — the brief reaches the manager+verbatim, the Kontrollierer actually runs the mission (BUG-016's lesson), the+UI is moved to the Artifacts section, the call returns at once with a+background marker, and every dead end becomes a spoken failure rather than a+log line (AU-11). Fakes, not mocks (project convention).+"""++from __future__ import annotations++import asyncio+from pathlib import Path+from typing import Any+from uuid import uuid4++import pytest++from jarvis.core.events import (+ JarvisAgentAnnouncement,+ JarvisAgentBackgroundCompleted,+ NavigateSidebar,+)+from jarvis.core.protocols import ExecutionContext+from jarvis.plugins.tool.create_artifact import CreateArtifactTool+++class _FakeBus:+ def __init__(self) -> None:+ self.published: list[Any] = []++ async def publish(self, event: Any) -> None:+ self.published.append(event)+++class _FakeManager:+ def __init__(self) -> None:+ self.dispatched: list[dict[str, Any]] = []++ async def dispatch(self, *, prompt: str, language: str, source_actor: str) -> str:+ self.dispatched.append(+ {"prompt": prompt, "language": language, "source_actor": source_actor}+ )+ return f"mission-{len(self.dispatched)}"+++class _FakeKontrollierer:+ def __init__(self, *, fail: bool = False) -> None:+ self.ran: list[str] = []+ self._fail = fail++ async def run_mission(self, mission_id: str) -> None:+ if self._fail:+ raise RuntimeError("worker exploded")+ self.ran.append(mission_id)+++def _ctx(+ utterance: str = "mach mir ein dashboard", # i18n-allow: DE test vocabulary+ language: str = "de",+) -> ExecutionContext:+ return ExecutionContext(+ trace_id=uuid4(),+ user_utterance=utterance,+ config={"output_language": language},+ memory_read=None,+ )+++async def _settle() -> None:+ """Let the fire-and-forget task run to completion."""+ for _ in range(5):+ await asyncio.sleep(0)+++async def test_dispatches_the_brief_and_runs_the_mission() -> None:+ bus, manager, kontrollierer = _FakeBus(), _FakeManager(), _FakeKontrollierer()+ tool = CreateArtifactTool(bus, manager=manager, kontrollierer=kontrollierer)++ result = await tool.execute(+ {"title": "Umsatz-Dashboard", "request": "Umsatz pro Monat 2026 als Balken."}, # i18n-allow+ _ctx(),+ )+ await _settle()++ assert result.success is True+ assert result.artifacts[0]["background_task"] is True # type: ignore[index]+ assert result.artifacts[0]["artifact_file"] == "umsatz-dashboard.html" # type: ignore[index]+ # The spoken promise names the artifact and is in the turn's language.+ assert "Umsatz-Dashboard" in result.output and "Hintergrund" in result.output # i18n-allow++ assert len(manager.dispatched) == 1+ prompt = manager.dispatched[0]["prompt"]+ assert "Exactly ONE self-contained HTML file named `umsatz-dashboard.html`" in prompt+ assert "Umsatz pro Monat 2026 als Balken." in prompt # i18n-allow+ assert manager.dispatched[0]["language"] == "de"+ assert kontrollierer.ran == ["mission-1"]++ kinds = [type(e) for e in bus.published]+ assert JarvisAgentAnnouncement in kinds+ nav = next(e for e in bus.published if isinstance(e, NavigateSidebar))+ assert nav.section == "visualization"+++async def test_a_brain_supplied_ack_is_spoken_verbatim() -> None:+ tool = CreateArtifactTool(+ _FakeBus(), manager=_FakeManager(), kontrollierer=_FakeKontrollierer()+ )+ result = await tool.execute(+ {"title": "T", "request": "R", "spoken_ack": "Kommt sofort."}, # i18n-allow+ _ctx(),+ )+ await _settle()+ assert result.output == "Kommt sofort." # i18n-allow+++async def test_missing_fields_are_the_models_to_fix() -> None:+ tool = CreateArtifactTool(_FakeBus(), manager=_FakeManager())+ no_title = await tool.execute({"request": "x"}, _ctx())+ no_request = await tool.execute({"title": "x"}, _ctx())+ assert no_title.success is False and "title" in (no_title.error or "")+ assert no_request.success is False and "request" in (no_request.error or "")+++async def test_no_mission_stack_is_an_honest_error_not_a_promise() -> None:+ tool = CreateArtifactTool(_FakeBus(), manager_resolver=lambda: None)+ result = await tool.execute({"title": "T", "request": "R"}, _ctx(language="en"))+ assert result.success is False+ assert "restart" in (result.error or "").lower()+++async def test_no_kontrollierer_becomes_a_spoken_failure() -> None:+ bus, manager = _FakeBus(), _FakeManager()+ tool = CreateArtifactTool(bus, manager=manager, kontrollierer_resolver=lambda: None)+ result = await tool.execute({"title": "T", "request": "R"}, _ctx())+ await _settle()+ assert result.success is True # the promise was made...+ done = [e for e in bus.published if isinstance(e, JarvisAgentBackgroundCompleted)]+ assert len(done) == 1 and done[0].success is False # ...and honestly withdrawn+++async def test_a_crashing_worker_becomes_a_spoken_failure() -> None:+ bus = _FakeBus()+ tool = CreateArtifactTool(+ bus, manager=_FakeManager(), kontrollierer=_FakeKontrollierer(fail=True)+ )+ await tool.execute({"title": "T", "request": "R"}, _ctx())+ await _settle()+ done = [e for e in bus.published if isinstance(e, JarvisAgentBackgroundCompleted)]+ assert len(done) == 1 and done[0].success is False+ assert "worker exploded" in (done[0].error or "")+++async def test_revise_starts_from_the_existing_page(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("JARVIS_ISOLATION_ROOT", str(tmp_path))+ files = tmp_path / "mission_a" / "tasks" / "019e0001" / "artifacts" / "files"+ files.mkdir(parents=True)+ (files / "plan-comparison.html").write_text(+ "<!doctype html><html><head><title>Plan comparison</title></head>"+ "<body>OLD-BODY</body></html>",+ encoding="utf-8",+ )+ manager = _FakeManager()+ tool = CreateArtifactTool(_FakeBus(), manager=manager, kontrollierer=_FakeKontrollierer())++ result = await tool.execute(+ {"title": "whatever", "request": "Make the bars red.", "revise": "plan comparison"},+ _ctx(language="en"),+ )+ await _settle()++ assert result.success is True+ assert result.artifacts[0]["revision"] is True # type: ignore[index]+ assert result.artifacts[0]["artifact_file"] == "plan-comparison.html" # type: ignore[index]+ prompt = manager.dispatched[0]["prompt"]+ assert "## Starting point" in prompt and "OLD-BODY" in prompt+ assert "Artifact: Plan comparison" in prompt # the page's own title wins+++async def test_revise_of_an_unknown_artifact_is_a_retryable_error(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("JARVIS_ISOLATION_ROOT", str(tmp_path))+ manager = _FakeManager()+ tool = CreateArtifactTool(_FakeBus(), manager=manager)+ result = await tool.execute(+ {"title": "T", "request": "R", "revise": "budget forecast"}, _ctx(language="en")+ )+ assert result.success is False+ assert "budget forecast" in (result.error or "")+ assert manager.dispatched == []diff --git a/tests/unit/plugins/tool/test_visualize.py b/tests/unit/plugins/tool/test_visualize.pydeleted file mode 100644index f35cc1c4bb..0000000000--- a/tests/unit/plugins/tool/test_visualize.py+++ /dev/null@@ -1,180 +0,0 @@-"""Tests for the ``visualize`` router tool.--The tool is thin by design — validate, render, archive, announce — so what is-worth pinning is the seams between those four, and the failure behaviour of-each. Two of them matter more than the rest:--* a rejected spec must come back as a RETRYABLE error carrying the validator's- own words, because that message is what the model reads before its second- attempt;-* a bus fault must not turn a successfully drawn picture into a failed call.- The file exists and the gallery lists it either way; reporting failure would- make the model apologise for something that worked, or draw it twice.--``JARVIS_ISOLATION_ROOT`` redirects the archive so no test writes into the real-outputs tree — the documented override, not a monkeypatched internal.-"""-from __future__ import annotations--from pathlib import Path-from typing import Any--import pytest--from jarvis.plugins.tool.visualize import VisualizeTool-from jarvis.visuals.spec import VISUAL_KINDS---class _FakeBus:- """Records what was published; a fake, not a mock (project convention)."""-- def __init__(self, *, fail: bool = False) -> None:- self.published: list[Any] = []- self._fail = fail-- async def publish(self, event: Any) -> None:- if self._fail:- raise RuntimeError("bus is down")- self.published.append(event)---def archive(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- monkeypatch.setenv("JARVIS_ISOLATION_ROOT", str(tmp_path))- return tmp_path---def _args(**overrides: Any) -> dict[str, Any]:- args: dict[str, Any] = {- "title": "How a turn is answered",- "kind": "flow",- "items": [{"label": "Listen"}, {"label": "Decide"}, {"label": "Answer"}],- }- args.update(overrides)- return args---class _Ctx:- user_text = "visualisier mir den ablauf" # i18n-allow: DE test vocabulary---def _read_archived_page(archive: Path, output: dict[str, Any]) -> str:- """The page's text, reached exactly the way the gallery reaches it.-- Reading it back through ``slug`` + ``artifact_path`` (rather than by- globbing) is what proves those two strings actually point at the file.- Synchronous on purpose: filesystem calls do not belong in an async body.- """- page = archive.joinpath(output["slug"], *output["artifact_path"].split("/"))- assert page.is_file(), page- return page.read_text(encoding="utf-8")---def _archived_runs(archive: Path) -> list[str]:- """Run directories in the archive. Synchronous, for the same reason."""- return sorted(entry.name for entry in archive.iterdir())---# --- Contract -------------------------------------------------------------------def test_the_tool_declares_itself_as_a_safe_router_tool():- assert VisualizeTool.name == "visualize"- assert VisualizeTool.risk_tier == "safe"---def test_the_schema_enum_matches_the_renderer_kinds():- """Five-layer parity: schema, VISUAL_KINDS and the renderer branches agree.-- A kind advertised to the model but unknown to the renderer is a KeyError on- the user's turn; one the renderer knows but the schema hides is dead code.- """- schema_kinds = VisualizeTool.schema["properties"]["kind"]["enum"]- assert list(schema_kinds) == list(VISUAL_KINDS)---def test_the_description_sends_gallery_requests_to_navigate():- """The two features answer to the same word; the tool has to disambiguate."""- assert "navigate" in VisualizeTool.description---# --- Happy path -----------------------------------------------------------------async def test_a_request_produces_a_page_and_opens_the_section(archive: Path):- bus = _FakeBus()- result = await VisualizeTool(bus=bus).execute(_args(), _Ctx())-- assert result.success is True- body = _read_archived_page(archive, result.output)- assert "How a turn is answered" in body- assert "Listen" in body-- # The UI is moved to the section that shows it.- assert len(bus.published) == 1- assert getattr(bus.published[0], "section", None) == "visualization"---async def test_the_summary_says_what_was_drawn(archive: Path):- result = await VisualizeTool(bus=_FakeBus()).execute(_args(), _Ctx())- summary = result.output["summary"]- assert "How a turn is answered" in summary- assert "flow" in summary---async def test_the_utterance_labels_the_run(archive: Path):- """The tile in the gallery reads as what was asked, not as a hex id."""- result = await VisualizeTool(bus=_FakeBus()).execute(_args(), _Ctx())- assert "visualisier" in result.output["slug"]---async def test_a_missing_context_still_draws(archive: Path):- """The utterance is decoration; no picture fails over a missing attribute."""- result = await VisualizeTool(bus=_FakeBus()).execute(_args(), object())- assert result.success is True--[email protected]("kind", VISUAL_KINDS)-async def test_every_advertised_kind_can_actually_be_drawn(kind: str, archive: Path):- items = [{"label": "A", "value": 2}, {"label": "B", "value": 5}]- result = await VisualizeTool(bus=_FakeBus()).execute(- _args(kind=kind, items=items), _Ctx()- )- assert result.success is True, result.error---# --- Failure behaviour ----------------------------------------------------------async def test_a_bad_spec_comes_back_retryable_with_the_reason(archive: Path):- bus = _FakeBus()- result = await VisualizeTool(bus=bus).execute(_args(kind="piechart"), _Ctx())-- assert result.success is False- assert "piechart" in result.error- for kind in VISUAL_KINDS:- assert kind in result.error # the model is told what to pick instead- assert bus.published == [] # nothing was announced for a picture never drawn---async def test_bars_without_numbers_are_refused_before_anything_is_written(archive: Path):- result = await VisualizeTool(bus=_FakeBus()).execute(- _args(kind="bars", items=[{"label": "A"}]), _Ctx()- )- assert result.success is False- assert _archived_runs(archive) == []---async def test_a_dead_bus_does_not_undo_a_drawn_picture(archive: Path):- """The file exists and the gallery lists it — the call succeeded."""- result = await VisualizeTool(bus=_FakeBus(fail=True)).execute(_args(), _Ctx())- assert result.success is True- assert "How a turn is answered" in _read_archived_page(archive, result.output)diff --git a/tests/unit/ui/web/test_outputs_routes.py b/tests/unit/ui/web/test_outputs_routes.pyindex 10fe11f566..b2fcaeb51c 100644--- a/tests/unit/ui/web/test_outputs_routes.py+++ b/tests/unit/ui/web/test_outputs_routes.py@@ -1329,6 +1329,36 @@ def test_download_inline_html_has_csp(app):assert "default-src 'none'" in r.headers.get("content-security-policy", "")+def test_artifact_page_allows_inline_scripts_but_no_network(app):+ """The Artifacts section frames HTML through ``/page``: the page's own JS+ runs (the iframe is sandboxed to an opaque origin on the client side), while+ every way out — network, forms, frames, navigation — stays shut."""+ root = Path(app.state.outputs_root)+ slug = "mission_019ed2dfd0fab"+ rel = _make_deliverable(+ root, "019ed2dfd0fab1234", "dash.html", "<script>document.title='ok'</script>"+ )+ client = TestClient(app)+ r = client.get(f"/api/outputs/{slug}/files/{rel}/page")+ assert r.status_code == 200+ assert r.headers["content-type"].startswith("text/html")+ csp = r.headers.get("content-security-policy", "")+ assert "script-src 'unsafe-inline'" in csp+ assert "connect-src 'none'" in csp+ assert "default-src 'none'" in csp+ assert r.headers.get("cache-control") == "no-store"+ assert "document.title" in r.text+++def test_artifact_page_refuses_non_html(app):+ root = Path(app.state.outputs_root)+ slug = "mission_019ed2dfd0fab"+ rel = _make_deliverable(root, "019ed2dfd0fab1234", "notes.md", "# not a page")+ client = TestClient(app)+ r = client.get(f"/api/outputs/{slug}/files/{rel}/page")+ assert r.status_code == 415++def test_download_attachment_html_no_csp_needed(app):# Attachment (download to disk) is not rendered, so no CSP is required.root = Path(app.state.outputs_root)diff --git a/tests/unit/visuals/test_visual_reaches_the_gallery.py b/tests/unit/visuals/test_visual_reaches_the_gallery.pydeleted file mode 100644index 57757d1fa5..0000000000--- a/tests/unit/visuals/test_visual_reaches_the_gallery.py+++ /dev/null@@ -1,100 +0,0 @@-"""An archived visualisation must actually reach the Visualization section.--``store.py`` matches two conventions it does not own — the run-directory slug-that ``outputs_routes`` parses, and the ``tasks/<id>/artifacts/files/`` subtree-that is the only one it will list or serve. Both are read-side rules, and-getting either subtly wrong writes a picture successfully and makes it-invisible forever: no exception, no log line, just a gallery that never shows-what the user asked for.--Unit tests on either side cannot catch that, because each would be asserting-its own idea of the convention. So this drives the REAL route over a real-archive directory and asserts the whole path end to end: the run is listed, the-file is listed, and it comes back with the no-script CSP that makes it safe to-render inside the app.-"""-from __future__ import annotations--from pathlib import Path--import pytest-from fastapi import FastAPI-from fastapi.testclient import TestClient--from jarvis.ui.web.outputs_routes import router as outputs_router-from jarvis.visuals.render import render_visual_html-from jarvis.visuals.spec import parse_spec-from jarvis.visuals.store import store_visual---def archive(tmp_path: Path) -> Path:- return tmp_path---def client(archive: Path) -> TestClient:- app = FastAPI()- app.include_router(outputs_router)- app.state.outputs_root = archive- return TestClient(app)---def _draw(archive: Path) -> dict[str, str]:- spec = parse_spec(- {- "title": "How a turn is answered",- "kind": "flow",- "items": [{"label": "Listen"}, {"label": "Decide"}],- },- source_utterance="visualisier mir den ablauf", # i18n-allow: DE test vocabulary- )- stored = store_visual(- render_visual_html(spec),- title=spec.title,- utterance=spec.source_utterance,- outputs_root=archive,- )- return {"slug": stored.slug, "path": stored.artifact_path}---def test_the_run_is_listed_with_what_was_asked(client: TestClient, archive: Path) -> None:- drawn = _draw(archive)-- body = client.get("/api/outputs").json()- sessions = body["sessions"] if isinstance(body, dict) else body- slugs = [row["slug"] for row in sessions]- assert drawn["slug"] in slugs-- row = next(r for r in sessions if r["slug"] == drawn["slug"])- # The tile's label comes from the slug, so the request has to survive it.- assert "visualisier" in (row.get("utterance") or "")---def test_the_page_is_listed_as_a_deliverable(client: TestClient, archive: Path) -> None:- drawn = _draw(archive)-- listing = client.get(f"/api/outputs/{drawn['slug']}/artifacts").json()- paths = [f["path"] for f in listing["files"]]- assert drawn["path"] in paths, paths---def test_the_gallery_would_classify_it_as_a_visual(client: TestClient, archive: Path) -> None:- """``useVisualArtifacts`` selects by extension — ``.html`` is kind "page"."""- drawn = _draw(archive)- assert drawn["path"].endswith(".html")---def test_it_renders_inline_under_the_no_script_csp(client: TestClient, archive: Path) -> None:- drawn = _draw(archive)-- response = client.get(- f"/api/outputs/{drawn['slug']}/files/{drawn['path']}/download",- params={"disposition": "inline"},- )- assert response.status_code == 200- assert "How a turn is answered" in response.text- # The picture is served into the app origin; the CSP is what makes that safe.- csp = response.headers.get("content-security-policy", "")- assert "default-src 'none'" in csp- assert "style-src 'unsafe-inline'" in cspdiff --git a/tests/unit/visuals/test_visual_render_store.py b/tests/unit/visuals/test_visual_render_store.pydeleted file mode 100644index 7a87fd27da..0000000000--- a/tests/unit/visuals/test_visual_render_store.py+++ /dev/null@@ -1,157 +0,0 @@-"""Tests for the visualisation renderer and its place in the run archive.--The renderer's hard constraint is the serving CSP: the page is delivered inside-the app origin with ``default-src 'none'``, so a document that reaches for-JavaScript, a font, or a remote image renders broken — and one that echoes a-model-authored label unescaped is an injection into the app's own origin. Both-are pinned here rather than left to review.--The store's hard constraint is the read side: two path conventions that-``outputs_routes`` enforces and this module has to match exactly, or the-picture is written successfully and is invisible forever.-"""-from __future__ import annotations--import re-from pathlib import Path--import pytest--from jarvis.visuals.render import render_visual_html-from jarvis.visuals.spec import VISUAL_KINDS, parse_spec-from jarvis.visuals.store import TASK_DIR_NAME, store_visual---def _spec(kind: str = "flow"):- return parse_spec(- {- "title": "How a turn is answered",- "kind": kind,- "items": [- {"label": "Listen", "detail": "Speech becomes text.", "value": 3},- {"label": "Decide", "detail": "The router picks a tool.", "value": 8},- ],- "caption": "Drawn on request.",- },- source_utterance="visualisier mir den ablauf",- )---# --- Renderer ------------------------------------------------------------------[email protected]("kind", VISUAL_KINDS)-def test_every_kind_renders_a_complete_document(kind: str) -> None:- """One branch per declared kind — a new kind without a branch fails here."""- html = render_visual_html(_spec(kind))- assert html.startswith("<!doctype html>")- assert html.rstrip().endswith("</html>")- assert "How a turn is answered" in html- assert "Listen" in html--[email protected]("kind", VISUAL_KINDS)-def test_no_kind_reaches_for_anything_the_csp_forbids(kind: str) -> None:- """default-src 'none': no script, no network, no external asset."""- html = render_visual_html(_spec(kind)).lower()- for forbidden in ("<script", "javascript:", "http://", "https://", "@import", "<img"):- assert forbidden not in html, forbidden---def test_model_authored_text_is_escaped() -> None:- """A label is untrusted input rendered into the app's own origin."""- spec = parse_spec(- {- "title": "<script>alert(1)</script>",- "kind": "comparison",- "items": [{"label": "a\"b<c>", "detail": "<b>bold</b>"}],- }- )- html = render_visual_html(spec)- assert "<script>alert(1)</script>" not in html- assert "<script>" in html- assert "<b>bold</b>" not in html---def test_bar_widths_are_proportional_from_zero() -> None:- """A bar axis that starts somewhere convenient overstates every difference."""- spec = parse_spec(- {- "title": "Runs per day",- "kind": "bars",- "items": [{"label": "Mon", "value": 5}, {"label": "Tue", "value": 10}],- }- )- html = render_visual_html(spec)- widths = [float(w) for w in re.findall(r'bar-fill" style="width:([\d.]+)%', html)]- assert widths == [50.0, 100.0]---def test_a_bar_without_a_value_renders_as_an_honest_gap() -> None:- spec = parse_spec(- {- "title": "Runs per day",- "kind": "bars",- "items": [{"label": "Mon", "value": 5}, {"label": "Tue"}],- }- )- html = render_visual_html(spec)- assert "—" in html---def test_rendering_is_deterministic() -> None:- """No clock, no randomness — which is what makes the archive diffable."""- assert render_visual_html(_spec()) == render_visual_html(_spec())---def test_the_utterance_is_shown_but_the_caption_owns_the_footer() -> None:- html = render_visual_html(_spec())- assert "visualisier mir den ablauf" in html- assert "Drawn on request." in html---# --- Store ----------------------------------------------------------------------def test_the_file_lands_where_the_gallery_looks(tmp_path: Path) -> None:- """Both conventions at once: the run slug and the deliverable subtree.-- ``outputs_routes`` parses the first and lists only the second; getting- either wrong writes a picture nobody can ever see.- """- stored = store_visual(- "<!doctype html><html></html>",- title="How a turn is answered",- utterance="visualisier mir den ablauf",- outputs_root=tmp_path,- )-- # The slug shape outputs_routes._SLUG_RE parses.- assert re.fullmatch(r"\d{8}T\d{6}__[a-z0-9-]+__[0-9a-f]{8}", stored.slug), stored.slug- # The only subtree outputs_routes will list or serve.- assert stored.artifact_path == (- f"tasks/{TASK_DIR_NAME}/artifacts/files/how-a-turn-is-answered.html"- )- assert stored.file.read_text(encoding="utf-8").startswith("<!doctype html>")- # The absolute path and the listed path describe the same file.- assert stored.file == tmp_path.joinpath(stored.slug, *stored.artifact_path.split("/"))---def test_no_partial_file_is_left_behind(tmp_path: Path) -> None:- """The gallery polls this tree; a half-written page renders as a blank frame."""- stored = store_visual("<!doctype html><html></html>", title="T", outputs_root=tmp_path)- leftovers = [p.name for p in stored.file.parent.iterdir() if p.name.startswith(".")]- assert leftovers == []---def test_two_pictures_of_the_same_thing_do_not_collide(tmp_path: Path) -> None:- first = store_visual("<html>1</html>", title="Same", outputs_root=tmp_path)- second = store_visual("<html>2</html>", title="Same", outputs_root=tmp_path)- assert first.slug != second.slug- assert first.file.read_text(encoding="utf-8") == "<html>1</html>"- assert second.file.read_text(encoding="utf-8") == "<html>2</html>"---def test_a_title_with_nothing_sluggable_still_produces_a_filename(tmp_path: Path) -> None:- stored = store_visual("<html></html>", title="???", outputs_root=tmp_path)- assert stored.file.name == "visualization.html"diff --git a/tests/unit/visuals/test_visual_spec.py b/tests/unit/visuals/test_visual_spec.pydeleted file mode 100644index e250c4cd82..0000000000--- a/tests/unit/visuals/test_visual_spec.py+++ /dev/null@@ -1,132 +0,0 @@-"""Tests for the validation in front of the visualisation renderer.--The spec layer is the only thing standing between model-authored JSON and a-page served inside the app origin, so its job is to be strict and to say why.-Two properties matter beyond "valid input parses":--* every rejection names what to fix, because the message goes back to the model- as the tool error and a precise one turns a bad call into a corrected retry;-* the caps actually bind — they are the reason "visualise the whole codebase"- cannot turn into a multi-megabyte document.-"""-from __future__ import annotations--import pytest--from jarvis.visuals.spec import (- MAX_DEPTH,- MAX_ITEMS,- MAX_LABEL_CHARS,- VISUAL_KINDS,- VisualSpecError,- parse_spec,-)---def _flow(**overrides: object) -> dict[str, object]:- payload: dict[str, object] = {- "title": "How a turn is answered",- "kind": "flow",- "items": [{"label": "Listen"}, {"label": "Decide"}, {"label": "Answer"}],- }- payload.update(overrides)- return payload---def test_a_plain_spec_parses() -> None:- spec = parse_spec(_flow(caption="Three steps."), source_utterance="visualisier das")- assert spec.kind == "flow"- assert [item.label for item in spec.items] == ["Listen", "Decide", "Answer"]- assert spec.caption == "Three steps."- assert spec.source_utterance == "visualisier das"---def test_a_bare_string_is_a_valid_item() -> None:- """The cheapest thing a model can emit still describes the picture."""- spec = parse_spec(_flow(items=["Listen", "Decide"]))- assert [item.label for item in spec.items] == ["Listen", "Decide"]---def test_whitespace_is_collapsed() -> None:- spec = parse_spec(_flow(title=" How a\n turn is answered "))- assert spec.title == "How a turn is answered"--[email protected]("kind", VISUAL_KINDS)-def test_every_declared_kind_is_accepted(kind: str) -> None:- """VISUAL_KINDS is the contract the tool schema advertises."""- items = [{"label": "A", "value": 1}, {"label": "B", "value": 2}]- assert parse_spec({"title": "T", "kind": kind, "items": items}).kind == kind---def test_an_unknown_kind_names_the_valid_ones() -> None:- with pytest.raises(VisualSpecError) as excinfo:- parse_spec(_flow(kind="piechart"))- message = str(excinfo.value)- assert "piechart" in message- for kind in VISUAL_KINDS:- assert kind in message---def test_a_missing_title_is_rejected() -> None:- with pytest.raises(VisualSpecError, match="title"):- parse_spec(_flow(title=" "))---def test_an_empty_item_list_is_rejected() -> None:- with pytest.raises(VisualSpecError, match="at least one"):- parse_spec(_flow(items=[]))---def test_a_missing_label_is_rejected_with_its_position() -> None:- with pytest.raises(VisualSpecError, match=r"items'\[1\]\.label"):- parse_spec(_flow(items=[{"label": "Listen"}, {"detail": "no label"}]))---def test_too_many_items_is_rejected_not_truncated() -> None:- """Silently dropping items would draw a picture that is quietly wrong."""- with pytest.raises(VisualSpecError, match=str(MAX_ITEMS)):- parse_spec(_flow(items=[{"label": f"Step {n}"} for n in range(MAX_ITEMS + 1)]))---def test_an_over_long_label_is_clipped_rather_than_rejected() -> None:- """The model described the right picture; it just wrote too much."""- spec = parse_spec(_flow(items=[{"label": "x" * (MAX_LABEL_CHARS + 50)}]))- assert len(spec.items[0].label) == MAX_LABEL_CHARS- assert spec.items[0].label.endswith("…")---def test_nesting_is_capped() -> None:- deepest: dict[str, object] = {"label": "leaf"}- for level in range(MAX_DEPTH + 1):- deepest = {"label": f"level {level}", "children": [deepest]}- with pytest.raises(VisualSpecError, match=str(MAX_DEPTH)):- parse_spec({"title": "T", "kind": "hierarchy", "items": [deepest]})---def test_nesting_within_the_cap_is_kept() -> None:- spec = parse_spec(- {- "title": "T",- "kind": "hierarchy",- "items": [{"label": "Brain", "children": [{"label": "Router"}]}],- }- )- assert spec.items[0].children[0].label == "Router"---def test_bars_without_a_single_number_are_rejected() -> None:- """A bar chart with no numbers is a bullet list wearing a costume."""- with pytest.raises(VisualSpecError, match="comparison"):- parse_spec({"title": "T", "kind": "bars", "items": [{"label": "A"}]})---def test_a_non_numeric_bar_value_is_rejected() -> None:- with pytest.raises(VisualSpecError, match="value"):- parse_spec({"title": "T", "kind": "bars", "items": [{"label": "A", "value": "lots"}]})---def test_an_extra_field_for_the_wrong_kind_is_ignored_not_rejected() -> None:- """A field too many still describes the picture correctly."""- spec = parse_spec(_flow(items=[{"label": "Listen", "value": 7}]))- assert spec.items[0].value == 7