Skip to content

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

feat(visualization): draw what is being discussed, when asked

rubenluetke10-beep8df237cadc97
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.py
index 4c440bbb23..723d873c4c 100644
--- a/jarvis/brain/factory.py
+++ b/jarvis/brain/factory.py
@@ -76,6 +76,17 @@ ROUTER_TOOLS = frozenset({
# frontend listener moves the UI. Pure UI action, risk safe, NO spawn —
# 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).
+ #
+ # 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).
+ # Membership here is what makes it REACHABLE; the gate decides WHEN.
+ "visualize",
# 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 +
@@ -460,6 +471,11 @@ 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 == "whoami":
inst = cls(profile=user_profile, people=people)
elif ep.name == "awareness-snapshot":
@@ -1371,7 +1387,7 @@ def _phase2_full_brain(
search=search,
max_chars=getattr(wiki_cfg, "max_chars", 1500),
latency_budget_ms=getattr(wiki_cfg, "latency_budget_ms", 150),
- min_keyword_length=getattr(wiki_cfg, "min_keyword_length", 4),
+ min_keyword_length=getattr(wiki_cfg, "min_keyword_length", 3),
relevance_gate=bool(getattr(wiki_cfg, "relevance_gate", True)),
min_coverage=float(getattr(wiki_cfg, "min_coverage", 0.5)),
strict_min_coverage=float(
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 7f9a6012b0..361ca208f6 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -819,6 +819,13 @@ _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"
+
+# Agentic-IDE pane tools that only make sense RELATIVE TO AN OPEN WORKSPACE.
_AGENTIC_IDE_WORKSPACE_TOOL_NAMES: frozenset[str] = frozenset({
"agentic-ide-terminal-report",
"agentic-ide-prompt",
@@ -5648,6 +5655,40 @@ class BrainManager:
log.debug("agentic-ide workspace tool gate failed", exc_info=True)
return tools
+ def _hide_visualize_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.
+ """
+ if not isinstance(tools, dict) or _VISUALIZE_TOOL_NAME not in tools:
+ return tools
+ try:
+ from jarvis.brain.visualize_gate import ( # noqa: PLC0415
+ wants_visualization,
+ )
+
+ if wants_visualization(user_text or ""):
+ return tools
+ return {n: tool for n, tool in tools.items() if n != _VISUALIZE_TOOL_NAME}
+ except Exception: # noqa: BLE001 — gate must never blind the brain
+ log.debug("visualize request gate failed", exc_info=True)
+ return tools
+
def _hide_action_tools_on_signalless_turn(
self, tools: dict[str, Tool], user_text: str
) -> dict[str, Tool]:
@@ -6133,25 +6174,6 @@ class BrainManager:
)
if retry is not None:
return retry
- # In the Command Deck the user is a team lead, and a team lead does
- # not address people by name for every order. "Somebody get the
- # wake-path tests green" is a real instruction; asking WHICH agent
- # would be the deck handing its own job back.
- #
- # Only in the deck: everywhere else an unaddressed sentence keeps
- # meaning what it always did, or an open workspace would start
- # swallowing ordinary conversation.
- delegated = await self._delegate_in_command_deck(
- user_text,
- session=session,
- candidates=candidates,
- language=out_lang,
- consume_pending_voice_attachments=(
- consume_pending_voice_attachments
- ),
- )
- if delegated is not None:
- return delegated
return self._ask_which_agentic_ide_terminal(
user_text, candidates=candidates, language=out_lang
)
@@ -6331,114 +6353,6 @@ class BrainManager:
)
return _fanout_reply_line(result, language)
- async def _delegate_in_command_deck(
- self,
- user_text: str,
- *,
- session: Any,
- candidates: list[str],
- language: str,
- consume_pending_voice_attachments: bool = False,
- ) -> str | None:
- """Hand work that names no pane to whoever is free. Deck only.
-
- Everywhere else, an instruction with no call-sign in it is a question
- for Jarvis. In the Command Deck the user is running a team and has
- stopped naming people for every order, so "somebody get the wake-path
- tests green" has to reach an agent — asking which one would be the deck
- handing its own job back to the person who opened it.
-
- Three answers, and the middle one is the reason this is not a loop over
- ``deliver``:
-
- * one free agent, or an order that does not decompose → one brief;
- * several free agents AND an explicit request to split → ``work_split``
- plans distinct assignments and the fan-out delivers them together,
- because the same sentence sent five times is five agents racing on
- one file rather than a team;
- * nobody free → SAY so. A silently held order is how a user ends up
- waiting an hour on work that was never started.
-
- Returns ``None`` for anything that is not deck delegation, so the
- caller's clarifying question still runs.
- """
- try:
- from jarvis.agentic_ide import fleet_actions as ide_fleet
- from jarvis.agentic_ide import intent as ide_intent
- from jarvis.agentic_ide.workspace_view import VIEW_DECK
-
- if getattr(session, "surface_view", "") != VIEW_DECK:
- return None
- work = ide_intent.unaddressed_work(user_text, names=candidates)
- if work is None:
- return None
- free = ide_fleet.free_agents(session)
- except Exception: # noqa: BLE001 - never crash a turn over an optional surface
- log.warning("Command Deck delegation check failed", exc_info=True)
- return None
-
- if not free:
- # Two different situations, two different answers: a workspace whose
- # agents are all busy, and one that has no agent at all. Offering to
- # "open one" is right in both, but telling somebody their agents are
- # busy when they have none is the kind of small lie that makes a
- # surface untrustworthy.
- try:
- from jarvis.agentic_ide.session import accepts_prompts
-
- has_agents = any(
- accepts_prompts(str(getattr(term, "agent", "") or ""))
- for term in getattr(session, "terminals", [])
- )
- except Exception: # noqa: BLE001 - the phrasing is not worth a crash
- has_agents = True
- key = "ide_deck_nobody_free" if has_agents else "ide_deck_no_agents"
- log.info("Command Deck: nothing free for an unaddressed order")
- return action_phrase(key, language)
-
- # An explicit split across a free fleet, or one agent takes it. The
- # default is deliberately ONE: "fix the wake path" is a job, not a
- # committee, and spending five subscriptions on it because five panes
- # happened to be idle is the fan-out mistake in reverse.
- names = [term.name for term in free]
- assignments: dict[str, str] | None = None
- if len(names) > 1 and ide_intent.wants_split(user_text):
- try:
- from jarvis.agentic_ide import work_split as ide_split
-
- plan = await ide_split.split(
- work,
- session=session,
- count=len(names),
- conversation=self._agentic_ide_conversation(user_text),
- )
- assignments = {
- name: item.task
- for name, item in zip(names, plan.assignments, strict=False)
- }
- log.info(
- "Command Deck: split %s across %d free panes (%s)",
- plan.split_by,
- len(assignments),
- ", ".join(a.area for a in plan.assignments),
- )
- except Exception: # noqa: BLE001 - an unplanned fleet still works
- log.warning("Command Deck work split failed", exc_info=True)
- names = names[:1]
- else:
- names = names[:1]
-
- log.info("Command Deck: delegating an unaddressed order to %s", ", ".join(names))
- return await self._deliver_agentic_ide_prompt(
- session=session,
- names=names,
- utterance=work,
- instruction="",
- language=language,
- assignments=assignments,
- consume_pending_voice_attachments=consume_pending_voice_attachments,
- )
-
#: How long a "you never prompted it" complaint may reach back. Bounded to
#: the running conversation: past this, "do it again" is a fresh request and
#: replaying a stale sentence into a coding agent would be its own bug.
@@ -10425,6 +10339,15 @@ 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.
+ if isinstance(_turn_tools, dict):
+ _turn_tools = self._hide_visualize_tool_without_request(
+ _turn_tools, user_text
+ )
# A referential follow-up that inherited a currently registered
# plugin/MCP tool remains inline even when that tool has no usage
# card. The explicit heavy-work and artifact requests above retain
diff --git a/jarvis/brain/visualize_gate.py b/jarvis/brain/visualize_gate.py
new file mode 100644
index 0000000000..3ad0157646
--- /dev/null
+++ b/jarvis/brain/visualize_gate.py
@@ -0,0 +1,147 @@
+"""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.
+
+Regex-only, provider-agnostic, no model in the detection path (AP-11): the gate
+runs on every single turn, so an LLM here would tax exactly the turns this
+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
+ ``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
+ words. 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.
+
+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.
+
+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.
+"""
+
+from __future__ import annotations
+
+import re
+
+# --- 1. Navigation to the existing gallery — never a request to draw ---------
+# "zeig mir die Visualisierungen", "open the visualization section". The
+# negative lookahead keeps a genuine request that happens to start with a nav
+# verb: "zeig mir eine Visualisierung VON den Zahlen" still wants a new picture.
+_NAV_VERBS = (
+ r"öffne|oeffne|geh(?:e)?\s+(?:mal\s+)?(?:zu|in)|" # i18n-allow: input vocab
+ r"wechs(?:le|el)\s+(?:zu|in)|navigier\w*\s+zu|zeig(?:e|s)?|" # i18n-allow: input vocab
+ r"open|go\s+to|switch\s+to|navigate\s+to|show|"
+ r"abre|ve\s+a|muestra(?:me)?" # i18n-allow: input vocab
+)
+_NAV_ARTICLES = (
+ r"(?:mir\s+|me\s+)?(?:die|den|das|the|la|el|los|las)?" # i18n-allow: input vocab
+)
+_NAV_SECTION_NOUNS = (
+ r"visualisierung(?:s\w*)?(?:en)?|" # i18n-allow: input vocab
+ r"visualiz(?:ation|aciones|aci[oó]n)s?|visualisations?|visuals"
+)
+_NAV_SUFFIX = (
+ r"(?:\s*[-–]?\s*"
+ r"(?:section|bereich|sektion|tab|board|ansicht|view))?" # i18n-allow: input vocab
+)
+# A following "of/for/about" turns the noun back into the THING being asked for.
+_NAV_NOT_FOLLOWED_BY = (
+ r"(?!\s*(?:von|vom|für|fuer|davon|dazu|hiervon|of|for|about|de|del))" # i18n-allow: input vocab
+)
+_NAVIGATION_RE = re.compile(
+ rf"\b(?:{_NAV_VERBS})\s+{_NAV_ARTICLES}\s*"
+ rf"(?:{_NAV_SECTION_NOUNS}){_NAV_SUFFIX}\b{_NAV_NOT_FOLLOWED_BY}",
+ re.IGNORECASE,
+)
+
+# --- 2. A question ABOUT the word, not a request for the thing ---------------
+_DEFINITION_RE = re.compile(
+ r"\b(?:"
+ r"was\s+(?:ist|sind|bedeutet|heißt|heisst)|" # i18n-allow: input vocab
+ r"erkl[äa]r\w*\s+mir\s+was|" # i18n-allow: input vocab
+ r"what\s+(?:is|are|does)|explain\s+what|"
+ r"qu[ée]\s+(?:es|son|significa)" # i18n-allow: input vocab
+ r")\b",
+ 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
+# so every inflection is covered ("visualisiere", "visualizing", "visualízalo").
+_EXPLICIT_RE = re.compile(
+ r"\b(?:"
+ # One stem for all three languages and every inflection, accents included:
+ # visualisieren, visualize, visualising, visualízamelo.
+ r"visual[ií]\w*|" # i18n-allow: input vocab
+ r"veranschaulich\w*|skizzier\w*|" # i18n-allow: input vocab
+ r"schaubild|flussdiagramm|ablaufdiagramm|organigramm|" # i18n-allow: input vocab
+ r"mindmap|mind\s+map|flowchart|flow\s+chart|org\s+chart|"
+ r"esquematiza\w*|diagrama\s+de\s+flujo" # i18n-allow: input vocab
+ r")\b",
+ re.IGNORECASE,
+)
+
+# --- 3b. Build/show verb + visual noun — a request only in combination -------
+# "diagramm" or "chart" alone is ordinary conversation ("der Chart ist rot").
+# Paired with a verb that PRODUCES or DISPLAYS something, it is a request.
+_VERB_RE = re.compile(
+ r"\b(?:"
+ r"mach|mache|erstell\w*|bau\w*|zeichne|zeichnen|mal|male|" # i18n-allow: input vocab
+ r"stell\w*|gib\s+mir|zeig\w*|erkl[äa]r\w*|fass\w*|" # i18n-allow: input vocab
+ r"make|create|build|draw|sketch|render|turn\s+(?:it|this|that)\s+into|"
+ r"give\s+me|show|explain|summari[sz]e|map\s+out|"
+ # "chart"/"graph"/"plot" are nouns as often as verbs, and _NOUN_RE already
+ # matches them. Without an object they would let ONE word play both halves
+ # of the combination and fire on "wie ist der bitcoin chart gerade".
+ r"(?:plot|chart|graph|map)\s+(?:it|this|that|these|those|the)|"
+ r"haz(?:me)?|crea|dibuja|muestra(?:me)?|resume" # i18n-allow: input vocab
+ r")\b",
+ re.IGNORECASE,
+)
+
+_NOUN_RE = re.compile(
+ r"\b(?:"
+ r"diagramm\w*|grafik\w*|schaubild\w*|zeitstrahl|" # i18n-allow: input vocab
+ r"bildlich|grafisch|visuell|anschaulich|als\s+bild|" # i18n-allow: input vocab
+ 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")\b",
+ re.IGNORECASE,
+)
+
+
+def wants_visualization(text: str) -> bool:
+ """True when the utterance explicitly asks for a picture to be drawn.
+
+ 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.
+ """
+ t = (text or "").strip()
+ if not t:
+ return False
+ if _NAVIGATION_RE.search(t):
+ return False
+ if _DEFINITION_RE.search(t):
+ return False
+ if _EXPLICIT_RE.search(t):
+ return True
+ return bool(_VERB_RE.search(t) and _NOUN_RE.search(t))
+
+
+__all__ = ["wants_visualization"]
diff --git a/jarvis/missions/standalone_run.py b/jarvis/missions/standalone_run.py
new file mode 100644
index 0000000000..a0521c5d5a
--- /dev/null
+++ b/jarvis/missions/standalone_run.py
@@ -0,0 +1,94 @@
+"""The marker that says "this run directory stands on its own".
+
+The Outputs list deliberately hides worktree-slug directories
+(``<ts>__<utterance>__<short>``). A worker mission creates two directories —
+the temporary worktree it builds in, and the persistent ``mission_<short>``
+sibling that carries its identity — and listing both produced the "two agents
+for one task" cards reported on 2026-05-26. Hiding the slug directory is the
+right 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.
+
+So the exception is made explicit rather than inferred. A standalone run drops
+this small JSON file at its root; the list treats a directory carrying it as a
+first-class run and takes the label from it. A real worktree directory never
+has one, so the 2026-05-26 behaviour is untouched.
+
+The alternative considered and rejected: naming the directory
+``mission_<hex>`` so the existing branch picks it up. That fakes a mission-id
+prefix — on a collision the picture would inherit an unrelated mission's status
+and error text, and the name would sort by hex instead of by time, which
+silently pushes a fresh picture out of the gallery's newest-runs scan window.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+#: Filename of the marker, at the root of the run directory. Dot-prefixed so it
+#: never reads as a deliverable, and outside ``tasks/`` so the artifact
+#: allowlist ignores it without needing to know about it.
+MARKER_NAME = ".standalone-run.json"
+
+
+def write_marker(run_dir: Path, *, kind: str, utterance: str = "", title: str = "") -> None:
+ """Mark ``run_dir`` as a complete run in its own right.
+
+ Inputs:
+ run_dir: the run directory (the ``/api/outputs/{slug}`` one).
+ kind: what produced it, e.g. ``"visualization"``. Shown to nobody;
+ it exists so a future reader can tell the sources apart.
+ utterance: what the user asked for — the label under the tile.
+ title: what the run produced, used when there is no utterance.
+
+ Raises:
+ OSError: the marker could not be written. Not swallowed: a run that
+ silently loses its marker is a run that silently vanishes from the
+ list, which is the exact failure this module exists to prevent.
+ """
+ payload = {"kind": kind, "utterance": utterance, "title": title}
+ run_dir.mkdir(parents=True, exist_ok=True)
+ (run_dir / MARKER_NAME).write_text(
+ json.dumps(payload, ensure_ascii=False), encoding="utf-8"
+ )
+
+
+def read_marker(run_dir: Path) -> dict[str, Any] | None:
+ """Return the marker's contents, or None when this is an ordinary run.
+
+ Never raises: this runs inside the Outputs listing, over directories any
+ process may be writing at the same moment. An unreadable or malformed
+ marker means "treat it as an ordinary directory" — the listing degrades to
+ the old behaviour for that one entry instead of failing for all of them.
+ """
+ try:
+ raw = (run_dir / MARKER_NAME).read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ return None
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError:
+ log.debug("standalone-run marker is not valid JSON: %s", run_dir)
+ return None
+ return data if isinstance(data, dict) else None
+
+
+def marker_label(marker: dict[str, Any]) -> str | None:
+ """The tile label for a standalone run: what was asked, else what came out."""
+ for key in ("utterance", "title"):
+ value = marker.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ return None
+
+
+__all__ = ["MARKER_NAME", "marker_label", "read_marker", "write_marker"]
diff --git a/jarvis/plugins/tool/visualize.py b/jarvis/plugins/tool/visualize.py
new file mode 100644
index 0000000000..ab157122e3
--- /dev/null
+++ b/jarvis/plugins/tool/visualize.py
@@ -0,0 +1,195 @@
+"""``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:
+ 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/frontend/src/hooks/useWebSocket.test.tsx b/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx
index 3c72a67f28..a407758167 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx
+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx
@@ -227,6 +227,52 @@ describe("useWebSocket VoiceBootStatus handling", () => {
);
});
+ it("stages the newest picture when the brain opens the Visualization section", async () => {
+ // The visualize tool publishes NavigateSidebar right after archiving a
+ // picture the user asked for. Merely landing on the gallery would make
+ // them hunt for the tile they just requested, so the stage is pulled to
+ // the newest visual — the "latest" target of requestVisual.
+ useEventStore.setState({ solo: false, visualStage: null, toasts: [] });
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver(envelope("NavigateSidebar", { section: "visualization" }));
+
+ expect(useEventStore.getState().activeSection).toBe("visualization");
+ expect(useEventStore.getState().visualStage?.target).toBe("latest");
+ });
+
+ it("stages into a detached Visualization window without switching its section", async () => {
+ // A solo window is pinned to the section it was split off for. The request
+ // still has to land — that window is exactly the one showing the picture.
+ useEventStore.setState({
+ solo: true,
+ activeSection: "visualization",
+ visualStage: null,
+ toasts: [],
+ });
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver(envelope("NavigateSidebar", { section: "visualization" }));
+
+ expect(useEventStore.getState().visualStage?.target).toBe("latest");
+ expect(useEventStore.getState().activeSection).toBe("visualization");
+ // A solo window announces nothing: it did not navigate anywhere.
+ expect(useEventStore.getState().toasts).toHaveLength(0);
+ });
+
+ it("leaves every other section on the plain navigation path", async () => {
+ useEventStore.setState({ solo: false, visualStage: null, toasts: [] });
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver(envelope("NavigateSidebar", { section: "settings" }));
+
+ expect(useEventStore.getState().activeSection).toBe("settings");
+ expect(useEventStore.getState().visualStage).toBeNull();
+ });
+
it("invalidates every documentation query after a registry reload", async () => {
const invalidate = vi.spyOn(queryClient, "invalidateQueries");
render(<Harness />);
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
index a504231a99..0ff140a8c4 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
@@ -347,15 +347,30 @@ export function useWebSocket(): void {
if (env.event_name === "NavigateSidebar") {
const p = env.payload as { section?: string };
- // A detached solo window is pinned to its one section; the spoken
- // "go to settings" targets the main window, and following it here
- // would blank the very view the user split off to keep.
- if (isSectionId(p.section) && !useEventStore.getState().solo) {
- setActiveSection(p.section);
- pushToast(
- "info",
- `${translate("use_web_socket.jarvis_opened")} ${SECTION_LABELS[p.section]}`,
- );
+ const solo = useEventStore.getState().solo;
+ if (isSectionId(p.section)) {
+ if (p.section === "visualization") {
+ // The one section whose event can mean "and here is a NEW
+ // picture": the visualize tool publishes this right after
+ // archiving one. Landing on the gallery with the newest tile
+ // merely selected would make the user hunt for what they just
+ // asked to see, so stage it. `requestVisual` does both halves in
+ // one update, and is the safe call in a solo window too — there
+ // it stages without switching the section, which is precisely
+ // what a detached Visualization window needs.
+ useEventStore.getState().requestVisual();
+ } else if (!solo) {
+ // A detached solo window is pinned to its one section; the spoken
+ // "go to settings" targets the main window, and following it here
+ // would blank the very view the user split off to keep.
+ setActiveSection(p.section);
+ }
+ if (!solo) {
+ pushToast(
+ "info",
+ `${translate("use_web_socket.jarvis_opened")} ${SECTION_LABELS[p.section]}`,
+ );
+ }
}
}
diff --git a/jarvis/ui/web/mission_graph.py b/jarvis/ui/web/mission_graph.py
index db5bdd4b20..829cdcec8b 100644
--- a/jarvis/ui/web/mission_graph.py
+++ b/jarvis/ui/web/mission_graph.py
@@ -35,23 +35,13 @@ import re
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
+from jarvis.visuals.brand import BRAND
+
# --- Brand palette -----------------------------------------------------------
-# Mirrors video/src/intro/theme.ts COLORS, which mirrors the desktop app's
-# frontend/src/index.css dark tokens. Change all three together.
-BRAND: Mapping[str, str] = {
- "bg": "#0A0A0A",
- "bg_elevated": "#141414",
- "bg_card": "#181818",
- "primary": "#FFD60A",
- "primary_deep": "#E6BE00",
- "text": "#FAFAFA",
- "text_muted": "#9A9A9A",
- "text_faint": "#6B6B6B",
- "border": "rgba(255,255,255,0.10)",
- "border_strong": "rgba(255,255,255,0.18)",
- "good": "#4ADE80",
- "primary_glow": "rgba(255,214,10,0.35)",
-}
+# ``BRAND`` moved to jarvis.visuals.brand once the on-demand visualisation
+# renderer needed the same colours. It is imported at the top of this module
+# and re-exported (see __all__): this module's ``BRAND`` is already part of its
+# API for outputs_routes and the tests.
# Status → pill/track accent. Keys match OUTPUT_STATUSES in outputs_routes.
_STATUS_ACCENTS: Mapping[str, str] = {
diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.py
index 3e1550c200..5aacf6ad45 100644
--- a/jarvis/ui/web/outputs_routes.py
+++ b/jarvis/ui/web/outputs_routes.py
@@ -32,6 +32,8 @@ from starlette.responses import FileResponse, HTMLResponse
from jarvis.missions.kontrollierer.deliverable_paths import (
is_nondeliverable_scratch,
)
+from jarvis.missions.standalone_run import marker_label as standalone_marker_label
+from jarvis.missions.standalone_run import read_marker as read_standalone_marker
from jarvis.missions.state_machine import MissionState, is_terminal
from jarvis.missions.stream_evidence import clean_request_body
from jarvis.platform import detect_platform
@@ -545,9 +547,27 @@ async def list_outputs(request: Request) -> OutputsResponse:
# scaffolding (cleaned in ``Kontrollierer._run_task_with_critic_loop``
# finally); power users can still address it via
# ``/api/outputs/{slug}/artifacts`` directly.
- if dir_to_mission_prefix.get(entry.name) is None:
+ #
+ # A STANDALONE run is the documented exception: it has no
+ # ``mission_<short>`` sibling to be a duplicate of, so skipping it does
+ # not de-duplicate anything — it just hides the run entirely. An
+ # on-demand visualisation is the first of these; see
+ # jarvis/missions/standalone_run.py for why the exception is a marker
+ # file rather than a naming trick.
+ standalone = read_standalone_marker(entry)
+ if standalone is None and dir_to_mission_prefix.get(entry.name) is None:
continue
parsed = _parse_slug(entry.name)
+ if standalone is not None:
+ # The run finished the moment the directory existed: there is no
+ # worker, no review, and nothing that can still change. Saying
+ # "unknown" would put a question mark on a file that is right there.
+ summary_status_override: str | None = "success"
+ standalone_label = standalone_marker_label(standalone)
+ if standalone_label:
+ parsed["utterance"] = standalone_label
+ else:
+ summary_status_override = None
# Persistent mission_* dirs have no timestamp in the slug — fall back
# to mtime so the sidebar still sorts newest-first sensibly.
if parsed["started_at"] is None:
@@ -566,7 +586,7 @@ async def list_outputs(request: Request) -> OutputsResponse:
summary: dict[str, Any] = {
"slug": entry.name,
"utterance": parsed["utterance"],
- "status": "unknown",
+ "status": summary_status_override or "unknown",
"mission_id": None,
"started_at": parsed["started_at"],
"completed_at": None,
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 05b6dea479..480acc1a14 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -588,21 +588,6 @@ class WebServer:
app.state.config = self.cfg
app.state.bus = self.bus
- # The Command Deck's way back to the user: when a coding agent stops,
- # say so instead of only counting it in the header bell. Attached here
- # because this is where the speech bus becomes available, and it is
- # cheap — three subscriptions and nothing running. The queue behind it
- # only ever fills while a workspace is actually being READ as a deck
- # (see agentic_ide/standup.py), so an install that never opens the IDE
- # pays for three handlers that are never called.
- try:
- from jarvis.agentic_ide import deck_voice
-
- app.state.deck_voice = deck_voice.attach(self.bus)
- except Exception as exc: # noqa: BLE001 - an optional surface never breaks boot
- logger.opt(exception=exc).warning("Command Deck voice not attached")
- app.state.deck_voice = None
-
# Voice boot-readiness mirror. WS events are one-shot, so a tab that
# connects after warm-up finished would never see VoiceBootStatus.
# Persist the latest state on this (long-lived) server instance for
diff --git a/jarvis/visuals/__init__.py b/jarvis/visuals/__init__.py
new file mode 100644
index 0000000000..3990921f9f
--- /dev/null
+++ b/jarvis/visuals/__init__.py
@@ -0,0 +1,33 @@
+"""On-demand visualisations — the pictures a user explicitly asked for.
+
+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.
+"""
+
+from __future__ import annotations
+
+from 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",
+]
diff --git a/jarvis/visuals/brand.py b/jarvis/visuals/brand.py
new file mode 100644
index 0000000000..45815f29c4
--- /dev/null
+++ b/jarvis/visuals/brand.py
@@ -0,0 +1,36 @@
+"""The brand palette every server-rendered page shares.
+
+Extracted from :mod:`jarvis.ui.web.mission_graph`, which used to own it, once a
+second renderer needed the same colours. A palette copied into two modules
+drifts within a release: someone adjusts the yellow in one place, and the
+mission map and the visualisation stop looking like they came from the same
+product. One definition, imported by both.
+
+Mirrors ``video/src/intro/theme.ts`` COLORS, which mirrors the desktop app's
+``frontend/src/index.css`` dark tokens. Change all three together.
+
+The app is dark-first and these pages open from inside it, so they commit to
+the dark brand look rather than following the OS light/dark preference — the
+same decision ``artifact_view`` documents for the markdown view.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+
+BRAND: Mapping[str, str] = {
+ "bg": "#0A0A0A",
+ "bg_elevated": "#141414",
+ "bg_card": "#181818",
+ "primary": "#FFD60A",
+ "primary_deep": "#E6BE00",
+ "text": "#FAFAFA",
+ "text_muted": "#9A9A9A",
+ "text_faint": "#6B6B6B",
+ "border": "rgba(255,255,255,0.10)",
+ "border_strong": "rgba(255,255,255,0.18)",
+ "good": "#4ADE80",
+ "primary_glow": "rgba(255,214,10,0.35)",
+}
+
+__all__ = ["BRAND"]
diff --git a/jarvis/visuals/render.py b/jarvis/visuals/render.py
new file mode 100644
index 0000000000..d73447a577
--- /dev/null
+++ b/jarvis/visuals/render.py
@@ -0,0 +1,275 @@
+"""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.py
new file mode 100644
index 0000000000..6eceb10ab1
--- /dev/null
+++ b/jarvis/visuals/spec.py
@@ -0,0 +1,240 @@
+"""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.py
new file mode 100644
index 0000000000..e2154d5f4b
--- /dev/null
+++ b/jarvis/visuals/store.py
@@ -0,0 +1,132 @@
+"""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/pyproject.toml b/pyproject.toml
index e1c1a58b7a..e3f1cb4ce6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -681,6 +681,13 @@ 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"
# 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.txt
index 48b7966b2d..66e5861040 100644
--- a/scripts/ci/german-allowlist.txt
+++ b/scripts/ci/german-allowlist.txt
@@ -443,3 +443,13 @@ tests/unit/brain/test_agentic_ide_clarify_fast_path.py
# (jarvis/commands/registry.py) stays English-checked, which is where a real
# German leak would have to be fixed. ---
docs/commands-reference.md
+
+# --- Visualize ask-gate (2026-08-11): the classifier must contain the German
+# drawing verbs and visual nouns LITERALLY to match German voice requests
+# ("visualisier mir das"), and its docstring/comments quote the German
+# example utterances that specify the matcher — inline i18n-allow is
+# 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
diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.py
index 86fbc8a545..920a5b39fe 100644
--- a/tests/unit/brain/test_routing.py
+++ b/tests/unit/brain/test_routing.py
@@ -1965,6 +1965,19 @@ 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).
+ #
+ # 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",
}
)
assert ROUTER_TOOLS == expected, (
diff --git a/tests/unit/brain/test_visualize_gate.py b/tests/unit/brain/test_visualize_gate.py
new file mode 100644
index 0000000000..d9af7947c4
--- /dev/null
+++ b/tests/unit/brain/test_visualize_gate.py
@@ -0,0 +1,108 @@
+"""Tests for the explicit-request gate in front of the ``visualize`` 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"),
+* 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.
+
+Every German/Spanish literal here is speech-input vocabulary under test.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.brain.visualize_gate import wants_visualization
+
+# Turns that ask, in the user's own words, to be shown something as a picture.
+_WANTS = [
+ # explicit drawing verb — enough on its own
+ "visualisier mir das mal", # i18n-allow: German speech-input test vocabulary
+ "visualisiere das bitte", # i18n-allow: German speech-input test vocabulary
+ "kannst du mir das visualisieren", # i18n-allow: German speech-input test vocabulary
+ "visualize this for me",
+ "visualise it",
+ "veranschaulich mir den ablauf", # i18n-allow: German speech-input test vocabulary
+ "skizzier mir kurz die architektur", # i18n-allow: German speech-input test vocabulary
+ "mach eine mindmap daraus", # i18n-allow: German speech-input test vocabulary
+ "draw me a flowchart of the deploy",
+ "ein flussdiagramm dazu waere super", # i18n-allow: German speech-input test vocabulary
+ "visualízamelo por favor", # i18n-allow: Spanish speech-input test vocabulary
+ # build/show verb + visual noun — a request only in combination
+ "erklär mir das bildlich", # i18n-allow: German speech-input test vocabulary
+ "zeig mir das grafisch", # i18n-allow: German speech-input test vocabulary
+ "stell das mal visuell dar", # i18n-allow: German speech-input test vocabulary
+ "mach mir ein diagramm von den schritten", # i18n-allow: German speech-input test vocabulary
+ "gib mir eine grafik dazu", # i18n-allow: German speech-input test vocabulary
+ "show me that visually",
+ "can you explain this as a diagram",
+ "turn this into a timeline",
+ "hazme un diagrama de esto", # i18n-allow: Spanish speech-input test vocabulary
+ # 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",
+]
+
+# Turns that must leave the tool out of the set entirely.
+_DOES_NOT_WANT = [
+ # navigation to the gallery that already exists — navigate's job
+ "zeig mir die visualisierungen", # i18n-allow: German speech-input test vocabulary
+ "öffne die visualisierung", # i18n-allow: German speech-input test vocabulary
+ "geh zu den visualisierungen", # i18n-allow: German speech-input test vocabulary
+ "open the visualization section",
+ "show the visualizations",
+ "switch to visuals",
+ "muestrame las visualizaciones", # i18n-allow: Spanish 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",
+ # 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
+ # 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
+ "schreib mir eine mail an ruben", # i18n-allow: German speech-input test vocabulary
+ "erklär mir wie tcp funktioniert", # i18n-allow: German speech-input test vocabulary
+ "explain how the router picks a tool",
+ "summarize the last three emails",
+ "bau mir eine flask app", # i18n-allow: German speech-input test vocabulary
+ "mach das fenster zu", # i18n-allow: German speech-input test vocabulary
+ "",
+ " ",
+]
+
+
[email protected]("text", _WANTS)
+def test_explicit_requests_open_the_gate(text: str) -> None:
+ assert wants_visualization(text) is True, text
+
+
[email protected]("text", _DOES_NOT_WANT)
+def test_everything_else_keeps_the_gate_shut(text: str) -> None:
+ assert wants_visualization(text) is False, text
+
+
+def test_navigation_beats_the_drawing_verb() -> None:
+ """The shared word must resolve to navigation, not to a new picture.
+
+ "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.
+ """
+ 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
+
+
+def 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
diff --git a/tests/unit/brain/test_visualize_tool_hide.py b/tests/unit/brain/test_visualize_tool_hide.py
new file mode 100644
index 0000000000..8b3ceac441
--- /dev/null
+++ b/tests/unit/brain/test_visualize_tool_hide.py
@@ -0,0 +1,86 @@
+"""The ``visualize`` tool is offered only on a turn that asked for a picture.
+
+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.
+
+This pins the gate's placement in ``BrainManager``. The vocabulary itself is
+tested in ``test_visualize_gate.py``; here the questions are narrower — does
+the manager actually strip it, does it leave every other tool alone, and does a
+fault in the gate fail OPEN (tools unchanged) rather than blinding the brain.
+"""
+from __future__ import annotations
+
+from jarvis.brain.manager import BrainManager
+
+
+def _mgr() -> BrainManager:
+ return BrainManager.__new__(BrainManager) # bypass heavy __init__
+
+
+def _surface() -> dict:
+ return {
+ "visualize": object(), # the gated one
+ "navigate": object(), # opens the EXISTING gallery — never gated
+ "search_web": object(),
+ "screenshot": object(),
+ "spawn_worker": object(),
+ }
+
+
+def test_an_explicit_request_keeps_the_tool():
+ out = _mgr()._hide_visualize_tool_without_request(
+ _surface(), "visualisier mir das mal" # i18n-allow: DE test vocabulary
+ )
+ assert "visualize" in out
+
+
+def test_an_ordinary_turn_loses_it():
+ out = _mgr()._hide_visualize_tool_without_request(
+ _surface(), "was haben wir gerade besprochen" # i18n-allow: DE test vocabulary
+ )
+ assert "visualize" not in out
+
+
+def test_nothing_else_is_touched():
+ """The gate owns exactly one name."""
+ out = _mgr()._hide_visualize_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.
+
+ 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.
+ """
+ out = _mgr()._hide_visualize_tool_without_request(
+ _surface(), "zeig mir die visualisierungen" # i18n-allow: DE test vocabulary
+ )
+ assert "visualize" not in out
+ assert "navigate" in out
+
+
+def test_a_surface_without_the_tool_is_returned_untouched():
+ surface = {"search_web": object()}
+ assert _mgr()._hide_visualize_tool_without_request(surface, "hallo") is surface
+
+
+def 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
+
+ def _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
+
+
+def test_a_non_dict_surface_is_passed_through():
+ sentinel = ["not", "a", "dict"]
+ assert _mgr()._hide_visualize_tool_without_request(sentinel, "visualisier das") is sentinel
diff --git a/tests/unit/plugins/tool/test_visualize.py b/tests/unit/plugins/tool/test_visualize.py
new file mode 100644
index 0000000000..f35cc1c4bb
--- /dev/null
+++ b/tests/unit/plugins/tool/test_visualize.py
@@ -0,0 +1,180 @@
+"""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.py
index 8c809a9a4b..10fe11f566 100644
--- a/tests/unit/ui/web/test_outputs_routes.py
+++ b/tests/unit/ui/web/test_outputs_routes.py
@@ -31,6 +31,8 @@ import pytest_asyncio
from fastapi import FastAPI
from fastapi.testclient import TestClient
+from jarvis.missions.standalone_run import MARKER_NAME as STANDALONE_MARKER_NAME
+from jarvis.missions.standalone_run import write_marker as write_standalone_marker
from jarvis.ui.web.outputs_routes import (
_is_deliverable_relpath,
_mission_id_prefix_for_dir,
@@ -749,6 +751,69 @@ async def test_list_outputs_hides_worktree_slug_dirs(app: FastAPI, tmp_path: Pat
)
+async def test_list_outputs_shows_a_marked_standalone_run(
+ app: FastAPI, tmp_path: Path
+) -> None:
+ """A slug dir that marked itself standalone is listed — with its label.
+
+ The rule above hides slug dirs because each one duplicates a canonical
+ ``mission_<short>`` sibling. A standalone run (an on-demand visualisation)
+ has no sibling, so hiding it does not de-duplicate anything: it makes a
+ finished, complete run invisible. The marker is the explicit opt-out —
+ see jarvis/missions/standalone_run.py.
+ """
+ run_dir = _make_worktree_dir(tmp_path, utterance="drawn-on-request", short="feedface")
+ write_standalone_marker(
+ run_dir,
+ kind="visualization",
+ utterance="visualisier mir den ablauf", # i18n-allow: DE test vocabulary
+ title="How a turn is answered",
+ )
+
+ with TestClient(app) as client:
+ r = client.get("/api/outputs")
+ sessions = r.json()["sessions"]
+
+ assert [s["slug"] for s in sessions] == [run_dir.name]
+ # The label is what the user asked, not the directory's slugified echo.
+ assert sessions[0]["utterance"] == "visualisier mir den ablauf"
+ # Nothing about it can still change, so "unknown" would be a false question.
+ assert sessions[0]["status"] == "success"
+
+
+async def test_list_outputs_still_hides_an_unmarked_neighbour(
+ app: FastAPI, tmp_path: Path
+) -> None:
+ """The marker is an opt-in for one directory, not a loosening for all.
+
+ Pinned next to the standalone case because a regression here restores the
+ 2026-05-26 "two agents for one task" cards.
+ """
+ marked = _make_worktree_dir(tmp_path, utterance="drawn", short="feedface")
+ write_standalone_marker(marked, kind="visualization", title="Drawn")
+ _make_worktree_dir(tmp_path, utterance="worker-scaffolding", short="cafebabe")
+
+ with TestClient(app) as client:
+ r = client.get("/api/outputs")
+
+ assert [s["slug"] for s in r.json()["sessions"]] == [marked.name]
+
+
+async def test_list_outputs_tolerates_a_corrupt_marker(app: FastAPI, tmp_path: Path) -> None:
+ """A half-written marker degrades that ONE entry, never the whole listing."""
+ run_dir = _make_worktree_dir(tmp_path, utterance="broken", short="feedface")
+ (run_dir / STANDALONE_MARKER_NAME).write_text("{not json", encoding="utf-8")
+
+ with TestClient(app) as client:
+ r = client.get("/api/outputs")
+
+ assert r.status_code == 200
+ assert r.json()["sessions"] == [] # falls back to the ordinary hidden case
+
+
@pytest.mark.asyncio
async def test_list_outputs_worktree_dir_random_short_does_not_collide(
app: FastAPI, tmp_path: Path, db_conn: aiosqlite.Connection
diff --git a/tests/unit/visuals/test_visual_reaches_the_gallery.py b/tests/unit/visuals/test_visual_reaches_the_gallery.py
new file mode 100644
index 0000000000..57757d1fa5
--- /dev/null
+++ b/tests/unit/visuals/test_visual_reaches_the_gallery.py
@@ -0,0 +1,100 @@
+"""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 csp
diff --git a/tests/unit/visuals/test_visual_render_store.py b/tests/unit/visuals/test_visual_render_store.py
new file mode 100644
index 0000000000..7a87fd27da
--- /dev/null
+++ b/tests/unit/visuals/test_visual_render_store.py
@@ -0,0 +1,157 @@
+"""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 "&lt;script&gt;" 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.py
new file mode 100644
index 0000000000..e250c4cd82
--- /dev/null
+++ b/tests/unit/visuals/test_visual_spec.py
@@ -0,0 +1,132 @@
+"""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