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(outputs): reconstruct a run's step timeline for the plan endpoint

rubenluetke10-beep50d24b15d6d8
diff --git a/jarvis/missions/stream_evidence.py b/jarvis/missions/stream_evidence.py
index 4b39f98aba..b8c2f9448b 100644
--- a/jarvis/missions/stream_evidence.py
+++ b/jarvis/missions/stream_evidence.py
@@ -219,6 +219,18 @@ def _normalize_worker_stream(stream_text: str) -> str:
return "\n".join(out)
+def normalize_worker_stream(stream_text: str) -> str:
+ """Public canonicalizer for archived worker streams.
+
+ Single source of truth shared by the Critic/Kontrollierer extractors above
+ and the Outputs/Visualization step-timeline reader
+ (``jarvis.ui.web.run_plan``). Both must see the SAME claude-shaped frames
+ for every worker backend, or a codex/gemini run would grade one way and
+ display another.
+ """
+ return _normalize_worker_stream(stream_text)
+
+
def extract_stream_evidence(
stream_text: str,
*,
@@ -1315,6 +1327,7 @@ __all__ = [
"informational_file_answer",
"is_clarification_only_answer",
"is_informational_request",
+ "normalize_worker_stream",
"readonly_answer",
"strip_spawn_meta",
"summarize_answers",
diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.py
index 1eddeed5f7..53c0465839 100644
--- a/jarvis/ui/web/outputs_routes.py
+++ b/jarvis/ui/web/outputs_routes.py
@@ -35,6 +35,7 @@ from jarvis.missions.kontrollierer.deliverable_paths import (
from jarvis.missions.state_machine import MissionState, is_terminal
from jarvis.platform import detect_platform
from jarvis.ui.web.artifact_view import VIEW_CSP, render_artifact_html
+from jarvis.ui.web.run_plan import build_run_plan
logger = logging.getLogger(__name__)
@@ -667,16 +668,21 @@ def outputs_capabilities(request: Request) -> dict[str, Any]:
@router.get("/{slug}/plan")
async def get_output_plan(slug: str, request: Request) -> dict[str, Any]:
- """Return the plan + steps for a single session — empty stub for now.
+ """Return the run's reconstructed step timeline (plan + steps).
- The `OutputsView` shows a `PlanStepList` in the right pane. Welle-4 hasn't
- plumbed plan/step persistence back through the Mission stack yet, so this
- intentionally returns `{plan: null, steps: []}` instead of 404 — the view
- treats that as "no plan available" and the user sees the session metadata
- plus the "open in Explorer" button.
+ The steps are not a separate store — they are read on demand from the
+ worker transcripts the mission archived under ``tasks/*/logs/stream.jsonl``
+ (see :mod:`jarvis.ui.web.run_plan`), so every run ever archived has its
+ timeline without a migration. A run with no readable stream still returns
+ ``{plan: null, steps: []}`` — the former stub's contract — which consumers
+ render as "no step data available".
+
+ Off the event loop for the same reason the artifact counts are: the parse
+ is bounded but still a filesystem read of potentially many MB.
"""
- _resolve_output_dir(request, slug)
- return {"plan": None, "steps": []}
+ session_dir = _resolve_output_dir(request, slug)
+ utterance = _parse_slug(session_dir.name)["utterance"]
+ return await asyncio.to_thread(build_run_plan, session_dir, utterance=utterance)
# Soft size limits for the artifact preview endpoint — full bytes are
diff --git a/jarvis/ui/web/run_plan.py b/jarvis/ui/web/run_plan.py
new file mode 100644
index 0000000000..c407bc3344
--- /dev/null
+++ b/jarvis/ui/web/run_plan.py
@@ -0,0 +1,259 @@
+"""Reconstruct a run's step timeline from its archived worker streams.
+
+The Visualization section draws a run as a node graph: what was asked, which
+tools the worker actually invoked (with their real success/failure), and what
+came out. The ground truth for that already exists on disk — every mission
+archives its worker transcript at ``tasks/<task_id>/logs/stream.jsonl`` — so
+this module is a READ over the archive, never a second store. A run that
+predates the feature gets its timeline for free, and there is nothing to
+migrate or keep in sync.
+
+Provider-agnosticism is inherited, not re-implemented: the raw stream may be
+claude ``stream-json``, codex ``exec --json`` or gemini plain text, and
+:func:`jarvis.missions.stream_evidence.normalize_worker_stream` rewrites all of
+them into the canonical claude shape the walker below understands. That is the
+same canonicalizer the Critic grades through, so the graph can never show a
+different story than the one the mission pipeline judged.
+
+Anti-hearsay discipline carries over too: a ``tool_use`` becomes a ``done`` or
+``failed`` step only when its correlated ``tool_result`` frame was observed;
+a call whose result never arrived (truncated stream, killed worker) is
+reported as ``skipped`` rather than silently trusted.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+from typing import Any, Final
+
+from jarvis.missions.stream_evidence import normalize_worker_stream
+
+logger = logging.getLogger(__name__)
+
+# Bounded work per request: the endpoint re-reads the archive on demand, so a
+# pathological multi-hundred-MB transcript must not stall the event loop's
+# worker thread or balloon the response. Caps are stated in the payload
+# (``truncated`` / ``dropped_steps``) so a shortened timeline reads as
+# "shortened", never as "the run did less".
+MAX_STREAM_BYTES: Final[int] = 24 * 1_048_576
+MAX_STEPS: Final[int] = 200
+_DETAIL_CHARS: Final[int] = 160
+_OUTPUT_CHARS: Final[int] = 400
+
+# tool_use.input keys that carry the one line a node label wants, tried in
+# order per tool family. Everything else falls back to the first short string
+# value of the input dict.
+_PATH_KEYS: Final[tuple[str, ...]] = (
+ "file_path",
+ "path",
+ "notebook_path",
+ "filePath",
+)
+_DETAIL_KEYS: Final[tuple[str, ...]] = (
+ "command",
+ "cmd",
+ "script",
+ *_PATH_KEYS,
+ "pattern",
+ "query",
+ "url",
+ "prompt",
+ "description",
+)
+
+# Tool names that materialise a file — their target path is surfaced on the
+# step (``writes``) so the frontend can connect an artifact node to the exact
+# step that produced it. Mirrors ``stream_evidence._WRITE_TOOL_NAMES``.
+_WRITE_TOOL_NAMES: Final[frozenset[str]] = frozenset(
+ {"Write", "Edit", "MultiEdit", "NotebookEdit", "file_write", "write_file", "create_file"}
+)
+
+
+def _clip(text: str, cap: int) -> str:
+ text = " ".join(text.split())
+ if len(text) <= cap:
+ return text
+ return text[: cap - 1].rstrip() + "…"
+
+
+def _tool_detail(name: str, tool_input: dict[str, Any]) -> str:
+ """The one-line label for a tool call — its command, path or query."""
+ for key in _DETAIL_KEYS:
+ value = tool_input.get(key)
+ if isinstance(value, str) and value.strip():
+ return _clip(value.strip(), _DETAIL_CHARS)
+ for value in tool_input.values():
+ if isinstance(value, str) and value.strip():
+ return _clip(value.strip(), _DETAIL_CHARS)
+ return ""
+
+
+def _result_text(content: Any) -> str:
+ """Flatten a tool_result ``content`` (str | list[block] | dict) to text."""
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ parts: list[str] = []
+ for blk in content:
+ if isinstance(blk, dict):
+ parts.append(str(blk.get("text", "")))
+ else:
+ parts.append(str(blk))
+ return " ".join(p for p in parts if p)
+ if isinstance(content, dict):
+ return str(content.get("text", ""))
+ return str(content)
+
+
+def _result_is_error(blk: dict[str, Any]) -> bool:
+ if blk.get("is_error") is True:
+ return True
+ return "tool_use_error" in _result_text(blk.get("content", ""))
+
+
+def _read_stream(path: Path) -> tuple[str, bool]:
+ """Read a stream file up to :data:`MAX_STREAM_BYTES`. Returns (text, truncated)."""
+ try:
+ size = path.stat().st_size
+ with path.open("rb") as fh:
+ raw = fh.read(MAX_STREAM_BYTES)
+ except OSError as exc:
+ logger.debug("run_plan: unreadable stream %s: %s", path, exc)
+ return "", False
+ return raw.decode("utf-8", errors="replace"), size > MAX_STREAM_BYTES
+
+
+def _walk_stream(stream_text: str, task_key: str) -> tuple[list[dict[str, Any]], str]:
+ """Turn one canonical claude stream into ordered steps + the final answer."""
+ steps: list[dict[str, Any]] = []
+ # tool_use id -> step (awaiting its correlated result frame).
+ pending: dict[str, dict[str, Any]] = {}
+ final_answer = ""
+ last_assistant_text = ""
+ seq = 0
+
+ for raw in stream_text.splitlines():
+ line = raw.strip()
+ if not line:
+ continue
+ try:
+ obj = json.loads(line)
+ except (json.JSONDecodeError, ValueError):
+ continue
+ if not isinstance(obj, dict):
+ continue
+ otype = obj.get("type")
+
+ if otype == "assistant":
+ for blk in (obj.get("message", {}) or {}).get("content", []) or []:
+ if not isinstance(blk, dict):
+ continue
+ if blk.get("type") == "tool_use":
+ name = str(blk.get("name", "")).strip() or "tool"
+ tool_input = blk.get("input") or {}
+ if not isinstance(tool_input, dict):
+ tool_input = {}
+ step: dict[str, Any] = {
+ "step_id": f"{task_key}:{seq}",
+ "name": _tool_detail(name, tool_input) or name,
+ "tool_name": name,
+ # Anti-hearsay default — upgraded to done/failed only
+ # by a correlated result frame below.
+ "status": "skipped",
+ "output": None,
+ "error": None,
+ "writes": [],
+ }
+ if name in _WRITE_TOOL_NAMES:
+ for key in _PATH_KEYS:
+ value = tool_input.get(key)
+ if isinstance(value, str) and value.strip():
+ step["writes"] = [value.strip()]
+ break
+ seq += 1
+ steps.append(step)
+ tid = str(blk.get("id", "")).strip()
+ if tid:
+ pending[tid] = step
+ elif blk.get("type") == "text":
+ txt = str(blk.get("text", "")).strip()
+ if txt:
+ last_assistant_text = txt
+ elif otype == "user":
+ for blk in (obj.get("message", {}) or {}).get("content", []) or []:
+ if not isinstance(blk, dict) or blk.get("type") != "tool_result":
+ continue
+ tid = str(blk.get("tool_use_id", "")).strip()
+ if tid not in pending:
+ continue
+ step = pending.pop(tid)
+ excerpt = _clip(_result_text(blk.get("content", "")).strip(), _OUTPUT_CHARS)
+ if _result_is_error(blk):
+ step["status"] = "failed"
+ step["error"] = excerpt or "tool call failed"
+ else:
+ step["status"] = "done"
+ step["output"] = excerpt or None
+ elif otype == "result":
+ res = obj.get("result")
+ if isinstance(res, str) and res.strip():
+ final_answer = res.strip()
+
+ if not final_answer:
+ final_answer = last_assistant_text
+ return steps, final_answer
+
+
+def build_run_plan(session_dir: Path, *, utterance: str | None = None) -> dict[str, Any]:
+ """The Visualization/Outputs read model for one archived run.
+
+ Returns the ``{plan, steps}`` shape ``usePlanForOutput`` already types,
+ plus honesty fields (``truncated``, ``dropped_steps``, ``final_answer``).
+ A run with no readable stream returns ``{plan: None, steps: []}`` — the
+ exact contract of the former stub, so every consumer of "no plan
+ available" keeps working unchanged.
+ """
+ steps: list[dict[str, Any]] = []
+ final_answer = ""
+ truncated = False
+
+ try:
+ stream_paths = sorted(session_dir.glob("tasks/*/logs/stream.jsonl"))
+ except OSError as exc:
+ logger.debug("run_plan: cannot list %s: %s", session_dir, exc)
+ stream_paths = []
+
+ for stream_path in stream_paths:
+ raw, was_cut = _read_stream(stream_path)
+ truncated = truncated or was_cut
+ if not raw.strip():
+ continue
+ task_key = stream_path.parent.parent.name
+ task_steps, answer = _walk_stream(normalize_worker_stream(raw), task_key)
+ steps.extend(task_steps)
+ if answer:
+ final_answer = answer
+
+ dropped = max(0, len(steps) - MAX_STEPS)
+ if dropped:
+ steps = steps[:MAX_STEPS]
+
+ if not steps and not final_answer:
+ return {"plan": None, "steps": []}
+
+ failed = sum(1 for s in steps if s["status"] == "failed")
+ plan = {
+ "plan_id": session_dir.name,
+ "vision": utterance or "",
+ "status": "failed" if failed and failed == len(steps) else "complete",
+ "total_steps": len(steps) + dropped,
+ }
+ return {
+ "plan": plan,
+ "steps": steps,
+ "final_answer": final_answer or None,
+ "truncated": truncated,
+ "dropped_steps": dropped,
+ }
diff --git a/tests/unit/ui/web/test_run_plan.py b/tests/unit/ui/web/test_run_plan.py
new file mode 100644
index 0000000000..f006f807f6
--- /dev/null
+++ b/tests/unit/ui/web/test_run_plan.py
@@ -0,0 +1,174 @@
+"""Unit tests for the run step-timeline reader (`jarvis.ui.web.run_plan`).
+
+The Visualization node graph is only as honest as this parser: a tool call
+must become `done`/`failed` ONLY via its correlated result frame, a truncated
+stream must say so, and a run without a stream must return the former stub's
+`{plan: None, steps: []}` contract unchanged.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.ui.web.outputs_routes import router as outputs_router
+from jarvis.ui.web.run_plan import MAX_STEPS, build_run_plan
+
+
+def _stream_dir(root: Path, task_id: str = "task-1") -> Path:
+ d = root / "tasks" / task_id / "logs"
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def _tool_use(tid: str, name: str, tool_input: dict) -> str:
+ return json.dumps(
+ {
+ "type": "assistant",
+ "message": {
+ "role": "assistant",
+ "content": [
+ {"type": "tool_use", "id": tid, "name": name, "input": tool_input}
+ ],
+ },
+ }
+ )
+
+
+def _tool_result(tid: str, content: str, *, is_error: bool = False) -> str:
+ blk: dict = {"type": "tool_result", "tool_use_id": tid, "content": content}
+ if is_error:
+ blk["is_error"] = True
+ return json.dumps({"type": "user", "message": {"role": "user", "content": [blk]}})
+
+
+def _result(text: str) -> str:
+ return json.dumps({"type": "result", "result": text})
+
+
+def test_no_stream_keeps_stub_contract(tmp_path: Path) -> None:
+ assert build_run_plan(tmp_path) == {"plan": None, "steps": []}
+
+
+def test_empty_stream_keeps_stub_contract(tmp_path: Path) -> None:
+ (_stream_dir(tmp_path) / "stream.jsonl").write_text("", encoding="utf-8")
+ assert build_run_plan(tmp_path) == {"plan": None, "steps": []}
+
+
+def test_steps_carry_correlated_status_and_final_answer(tmp_path: Path) -> None:
+ lines = [
+ _tool_use("t1", "Bash", {"command": "python plot.py"}),
+ _tool_result("t1", "wrote chart.png"),
+ _tool_use("t2", "Write", {"file_path": "report/chart.png", "content": "…"}),
+ _tool_result("t2", "<tool_use_error>disk full</tool_use_error>", is_error=False),
+ _tool_use("t3", "Read", {"file_path": "notes.md"}), # no result frame
+ _result("All done: one chart rendered."),
+ ]
+ (_stream_dir(tmp_path) / "stream.jsonl").write_text(
+ "\n".join(lines), encoding="utf-8"
+ )
+
+ payload = build_run_plan(tmp_path, utterance="Draw a chart")
+
+ assert payload["plan"]["vision"] == "Draw a chart"
+ assert payload["plan"]["total_steps"] == 3
+ assert payload["final_answer"] == "All done: one chart rendered."
+ assert payload["truncated"] is False
+
+ by_tool = {s["tool_name"]: s for s in payload["steps"]}
+ assert by_tool["Bash"]["status"] == "done"
+ assert by_tool["Bash"]["name"] == "python plot.py"
+ assert by_tool["Bash"]["output"] == "wrote chart.png"
+ # The <tool_use_error> marker counts as failure even without is_error.
+ assert by_tool["Write"]["status"] == "failed"
+ assert by_tool["Write"]["writes"] == ["report/chart.png"]
+ # Anti-hearsay: a call whose result never arrived is skipped, not done.
+ assert by_tool["Read"]["status"] == "skipped"
+
+
+def test_codex_stream_is_normalized_before_walking(tmp_path: Path) -> None:
+ lines = [
+ json.dumps(
+ {
+ "type": "item.completed",
+ "item": {
+ "type": "command_execution",
+ "command": "ls -la",
+ "aggregated_output": "total 4",
+ "exit_code": 0,
+ },
+ }
+ ),
+ json.dumps(
+ {"type": "item.completed", "item": {"type": "agent_message", "text": "Done."}}
+ ),
+ ]
+ (_stream_dir(tmp_path) / "stream.jsonl").write_text(
+ "\n".join(lines), encoding="utf-8"
+ )
+
+ payload = build_run_plan(tmp_path)
+
+ assert [s["tool_name"] for s in payload["steps"]] == ["Bash"]
+ assert payload["steps"][0]["status"] == "done"
+ assert payload["final_answer"] == "Done."
+
+
+def test_step_cap_reports_dropped_count(tmp_path: Path) -> None:
+ lines: list[str] = []
+ for i in range(MAX_STEPS + 25):
+ lines.append(_tool_use(f"t{i}", "Bash", {"command": f"step {i}"}))
+ lines.append(_tool_result(f"t{i}", "ok"))
+ (_stream_dir(tmp_path) / "stream.jsonl").write_text(
+ "\n".join(lines), encoding="utf-8"
+ )
+
+ payload = build_run_plan(tmp_path)
+
+ assert len(payload["steps"]) == MAX_STEPS
+ assert payload["dropped_steps"] == 25
+ assert payload["plan"]["total_steps"] == MAX_STEPS + 25
+
+
+def test_multiple_tasks_walk_in_order_with_unique_ids(tmp_path: Path) -> None:
+ for task, cmd in (("a-task", "first"), ("b-task", "second")):
+ (_stream_dir(tmp_path, task) / "stream.jsonl").write_text(
+ "\n".join(
+ [_tool_use("t1", "Bash", {"command": cmd}), _tool_result("t1", "ok")]
+ ),
+ encoding="utf-8",
+ )
+
+ payload = build_run_plan(tmp_path)
+
+ assert [s["name"] for s in payload["steps"]] == ["first", "second"]
+ ids = [s["step_id"] for s in payload["steps"]]
+ assert len(ids) == len(set(ids))
+
+
+def test_plan_route_serves_reconstructed_steps(tmp_path: Path) -> None:
+ app = FastAPI()
+ app.include_router(outputs_router)
+ app.state.outputs_root = tmp_path
+
+ run = tmp_path / "mission_deadbeef"
+ (_stream_dir(run) / "stream.jsonl").write_text(
+ "\n".join(
+ [
+ _tool_use("t1", "Bash", {"command": "echo hi"}),
+ _tool_result("t1", "hi"),
+ _result("Said hi."),
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ client = TestClient(app)
+ payload = client.get("/api/outputs/mission_deadbeef/plan").json()
+
+ assert payload["plan"]["plan_id"] == "mission_deadbeef"
+ assert payload["steps"][0]["tool_name"] == "Bash"
+ assert payload["final_answer"] == "Said hi."