Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agentic-ide): recap what each pane is doing, for its header
Ruben Lütke4b4358e73d83
diff --git a/jarvis/agentic_ide/recap.py b/jarvis/agentic_ide/recap.pynew file mode 100644index 0000000000..6fb6577640--- /dev/null+++ b/jarvis/agentic_ide/recap.py@@ -0,0 +1,283 @@+"""A one-glance answer to "what is this pane actually doing?".++Every pane header used to say the same two things: the call-sign the user chose+and the CLI behind it ("Mika — CLAUDE CODE"). Both are constant for the life of+the pane, so a grid of eight terminals answered the one question a grid of eight+terminals raises — *which of these is doing the thing I care about?* — with+eight identical labels. The information was on screen the whole time, buried in+a full-screen TUI the user has to read pane by pane.++This module derives a short recap from state the workspace already keeps, and+deliberately nothing else:++* what the pane was last **asked** to do (``last_prompt`` — the instruction that+ went in through the prompt bar or by voice),+* what it last **printed** (the readable transcript, already replayed off a+ terminal screen by :mod:`.transcript`),+* whether it is running, starting, dead, or broken, and how long ago it spoke.++No model call, no network, no background task — a recap is computed when someone+asks for one, from a buffer that is filled anyway. That is a hard constraint,+not an optimisation: this text is rendered for every pane of every workspace on+a poll, and an LLM round-trip per pane per few seconds would cost more than the+feature is worth and would fail entirely for a user without a spare key (§3).++Two forms come out, because the header and the tooltip answer differently sized+questions:++* :attr:`Recap.headline` — ONE clause for a label that will be truncated by the+ pane's width. Front-loaded with the freshest signal, since the beginning is+ the part that survives the ellipsis.+* :attr:`Recap.detail` — one or two plain sentences for the hover tooltip: what+ it was asked to do, and what has happened since.++Honest limits: a coding CLI's last printed line is a heuristic for "what it is+doing", not a summary of the session, and a TUI that redraws a status bar as its+bottom row will surface that instead of its last real step. So the wording never+claims more than it knows — it quotes what the pane printed rather than+asserting what the agent "is working on".+"""++from __future__ import annotations++import re+import time+from dataclasses import dataclass+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING: # pragma: no cover - typing only+ from collections.abc import Sequence++# How many transcript rows the recap looks back over. Enough to step past a+# status bar and a blank frame row, small enough that the scan is free.+TAIL_LINES = 14++# The header label is truncated by CSS anyway; this is the transport cap, so a+# pane that printed a 3,000-character JSON blob cannot push that through the+# state payload of every poll.+HEADLINE_CHARS = 120+# Two readable sentences in a tooltip roughly 20 rem wide.+DETAIL_CHARS = 280+# How much of the instruction is quoted. A prompt is often a whole brief; the+# first line of it is what identifies the task.+TASK_CHARS = 80++# Glyphs an agent TUI draws in front of its input line. A row starting with one+# is the prompt box, not something the agent did.+_INPUT_MARKERS = ("❯", ">", "›")++# Fragments that mark a row as the TUI's own chrome — key hints, the context+# meter, the permission-mode banner. They are drawn on every frame, so without+# this the recap of every busy pane would read "? for shortcuts".+_CHROME_FRAGMENTS = (+ "for shortcuts",+ "to interrupt",+ "to cancel",+ "ctrl+c",+ "ctrl-c",+ "shift+tab",+ "esc to",+ "press enter",+ "auto-compact",+ "context left",+ "accept edits on",+ "bypassing permissions",+ "plan mode on",+)++# Leading decoration a TUI puts in front of a real line: bullets, tree glyphs,+# check marks, spinner frames. Stripped so the recap starts on a word. The+# allowed openers are kept out of the class deliberately — a path, a quote or an+# @reference is content, not decoration.+_LEAD_RE = re.compile(r'^[^\w"\'(\[@/#]+')+++@dataclass(frozen=True, slots=True)+class Recap:+ """What one pane is doing, in the two lengths the UI needs.++ ``headline`` goes in the pane header and is expected to be clipped;+ ``detail`` is the one-or-two-sentence version behind the hover tooltip.+ Both are plain English and both may be empty — a pane that has done nothing+ yet has nothing to report, and inventing a sentence for it would be noise.+ """++ headline: str+ detail: str+++def _condense(text: str, limit: int) -> str:+ """One line of ``text``, whitespace collapsed, cut on a word boundary."""+ cleaned = " ".join(str(text or "").split())+ if len(cleaned) <= limit:+ return cleaned+ cut = cleaned[:limit]+ spaced = cut.rsplit(" ", 1)[0]+ # A single very long token (a path, a hash) has no space to cut at — take+ # the hard cut rather than returning nothing.+ return f"{spaced or cut}…"+++def _informative(line: str) -> bool:+ """True for a transcript row that says something about the work."""+ text = line.strip()+ if len(text) < 4 or text.startswith(_INPUT_MARKERS):+ return False+ lowered = text.lower()+ if any(fragment in lowered for fragment in _CHROME_FRAGMENTS):+ return False+ # A row of numbers, punctuation or box residue is not a sentence.+ return sum(1 for ch in text if ch.isalpha()) >= 3+++def _activity(tail: Sequence[str]) -> str:+ """The most recent row that reads like something the agent did."""+ for line in reversed(list(tail)):+ if not _informative(line):+ continue+ return _condense(_LEAD_RE.sub("", line.strip()), HEADLINE_CHARS)+ return ""+++def _task(term: Any) -> str:+ """The instruction this pane was last given, short enough to quote.++ The FIRST line of it: a composed prompt is a structured markdown brief whose+ later lines are context and file references, and the opening line is the one+ that names the job.+ """+ first_line = str(getattr(term, "last_prompt", "") or "").split("\n", 1)[0]+ return _condense(first_line, TASK_CHARS)+++def _idle_phrase(term: Any) -> str:+ """How long ago this pane last printed anything, in words."""+ last = getattr(term, "last_output_at", None)+ if not last:+ return ""+ seconds = max(0, int(time.time() - float(last)))+ if seconds < 60:+ return f"{seconds}s ago"+ if seconds < 3600:+ return f"{seconds // 60} min ago"+ return f"{seconds // 3600} h ago"+++def _sentences(*parts: str) -> str:+ """Join the non-empty parts into one paragraph, capped for transport."""+ return _condense(" ".join(part for part in parts if part), DETAIL_CHARS)+++def _typed_into(term: Any) -> bool:+ """Can Jarvis send this pane an instruction at all?++ False for a plain terminal: it is a shell, and Jarvis deliberately does not+ type into one (see ``session.accepts_prompts``). Saying "no instruction has+ been sent yet" about such a pane would promise one that is never coming.++ Every step is defensive, like the rest of this module: an entry that predates+ the shell panes, or a registry this build does not have, answers "yes, it+ takes prompts" — which is what every pane did before plain terminals existed.+ """+ try:+ from jarvis.workspace.agents import get_agent++ spec = get_agent(str(getattr(term, "agent", "") or ""))+ except Exception: # noqa: BLE001 - a recap must never break a state read+ return True+ return spec is None or bool(getattr(spec, "is_coding_agent", True))+++def _task_sentence(task: str, *, sent: int) -> str:+ """What this pane was told to do, or an honest note that nothing was."""+ if task:+ return f'Last asked to: "{task}".'+ if sent:+ return "Its last instruction came from Jarvis."+ return "No instruction has been sent to it from Jarvis yet."+++def summarize(term: Any, *, tail: Sequence[str] | None = None) -> Recap:+ """Recap the session running in ``term``.++ ``tail`` lets a caller that has already read the transcript pass the rows in+ rather than have them read a second time — :meth:`Terminal.to_dict` counts+ the transcript anyway, and replaying a 600-row screen twice per poll per+ pane is a cost with nothing to show for it.++ Duck-typed on purpose (``Terminal`` lives in :mod:`.session`, which imports+ this module): every attribute is read defensively so a test double carrying+ half a pane still produces a sentence instead of an ``AttributeError``.+ """+ if tail is None:+ transcript = getattr(term, "transcript", None)+ try:+ tail = transcript.tail(TAIL_LINES) if transcript is not None else []+ except Exception: # noqa: BLE001 - a recap must never break a state read+ tail = []++ status = str(getattr(term, "status", "") or "pending")+ task = _task(term)+ sent = int(getattr(term, "prompts_sent", 0) or 0)+ # One sentence about the instruction, computed once: every branch below+ # opens with it, and a plain terminal answers it differently.+ asked = (+ _task_sentence(task, sent=sent)+ if _typed_into(term)+ else "This is a plain terminal — you type into it yourself."+ )+ activity = _activity(tail)+ idle = _idle_phrase(term)++ if status == "error":+ problem = _condense(getattr(term, "error", ""), HEADLINE_CHARS)+ problem = problem or "it could not be started"+ return Recap(+ headline=f"Not running — {problem}",+ detail=_sentences(+ f"This pane is not running: {problem}.",+ asked,+ ),+ )++ if status == "pending":+ return Recap(+ headline="Not started yet — connect to it to start its agent.",+ detail=_sentences(+ "This pane has no agent running yet; it starts as soon as the terminal connects.",+ asked if task else "",+ ),+ )++ if status == "exited":+ code = getattr(term, "exit_code", None)+ ended = "Finished and exited" if code in (0, None) else f"Exited with code {code}"+ closing = f"{ended}. Last output: {activity}" if activity else f"{ended}."+ return Recap(+ headline=_condense(closing, HEADLINE_CHARS),+ detail=_sentences(+ asked,+ f"{ended}" + (f", last printing: {activity}." if activity else "."),+ ),+ )++ # Live. Freshest signal first: what it is printing beats what it was told,+ # because the instruction is minutes old by the time the pane is glanced at+ # and the output is what changed since.+ if activity:+ headline = activity+ elif task:+ headline = f'Working on: "{task}"'+ else:+ headline = "Running — nothing printed yet."++ now = f"Working now, last output {idle}: {activity}." if idle and activity else (+ f"Working now: {activity}." if activity else "Running, with nothing printed yet."+ )+ return Recap(+ headline=_condense(headline, HEADLINE_CHARS),+ detail=_sentences(asked, now),+ )+++__all__ = ["DETAIL_CHARS", "HEADLINE_CHARS", "TAIL_LINES", "Recap", "summarize"]diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex b49612bf83..e2aa019b76 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -64,7 +64,8 @@ from uuid import uuid4from loguru import logger-from . import resume_store++from . import recap, resume_storefrom .agent_sessions import (ResumeHandle,can_resume,@@ -477,6 +478,11 @@ class Terminal:viewer_exit: Any = Nonedef to_dict(self) -> dict[str, Any]:+ # Read the replayed screen ONCE. `lines()` walks the whole scrollback,+ # and both the line count below and the recap want it — asking twice per+ # pane per poll is a cost with nothing to show for it.+ lines = self.transcript.lines()+ summary = recap.summarize(self, tail=lines[-recap.TAIL_LINES :])return {"key": self.key,"name": self.name,@@ -496,7 +502,13 @@ class Terminal:"prompts_sent": self.prompts_sent,"last_prompt": self.last_prompt,"submitted": self.submitted,- "lines_captured": len(self.transcript.lines()),+ "lines_captured": len(lines),+ # What this pane is doing, in the two lengths the header needs: one+ # clause for the label (which the pane's width will clip) and one or+ # two sentences for the tooltip behind it. Derived, never stored —+ # see .recap for why it is computed on read.+ "recap": summary.headline,+ "recap_detail": summary.detail,"resumed": self.resumed,# Whether a handle EXISTS, never the handle itself: it is an# internal pointer into the CLI's history and no client needs it.diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex e9827ca398..df138918b4 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -53,7 +53,7 @@ from fastapi import ()from pydantic import BaseModel, Field-from jarvis.agentic_ide import native_picker, recents, resume_store+from jarvis.agentic_ide import native_picker, recap, recents, resume_storefrom jarvis.agentic_ide.agent_sessions import has_conversationfrom jarvis.agentic_ide.device import device_namefrom jarvis.agentic_ide.folders import list_dir, search_folders, start_points@@ -467,6 +467,21 @@ class ResumeOffer(BaseModel):workspaces: list[ResumeWorkspace] = Field(default_factory=list)+class TerminalRecap(BaseModel):+ """What one pane is doing, in the two lengths its header renders."""++ key: str+ name: str+ status: str+ recap: str = Field(description="One clause for the pane header; the pane's width clips it.")+ recap_detail: str = Field(description="The one-or-two-sentence version, shown on hover.")+++class RecapsResponse(BaseModel):+ workspace_id: str | None = None+ terminals: list[TerminalRecap] = Field(default_factory=list)++# --------------------------------------------------------------------------- ## REST ## --------------------------------------------------------------------------- #@@ -1084,6 +1099,39 @@ async def close_terminal(name: str) -> dict:return {"ok": True, "closed": term.name, "state": get_registry().state()}[email protected]("/recaps", response_model=RecapsResponse, summary="What every terminal is doing")+async def get_recaps(workspace_id: str | None = None) -> RecapsResponse:+ """A short recap per pane — the header line and its hover tooltip.++ Separate from ``/state`` because the two change at completely different+ rates. The workspace state changes when a pane is opened, closed or moved,+ which is rare; a recap changes whenever an agent prints something, which is+ constantly. Polling ``/state`` fast enough for a live recap would re-send+ every project profile, resume flag and account label several times a minute+ to update one sentence — so the cheap half is its own read.++ Without ``workspace_id`` the workspace on screen answers. An unknown or+ closed one comes back empty rather than as an error: a poll that outlives+ the workspace it was started for is normal, not a failure worth a red pane.+ """+ session = get_registry().get(workspace_id)+ if session is None:+ return RecapsResponse(workspace_id=None, terminals=[])+ rows: list[TerminalRecap] = []+ for term in session.terminals:+ summary = recap.summarize(term)+ rows.append(+ TerminalRecap(+ key=term.key,+ name=term.name,+ status=term.status,+ recap=summary.headline,+ recap_detail=summary.detail,+ )+ )+ return RecapsResponse(workspace_id=session.id, terminals=rows)++@router.get("/terminals/{name}/report", summary="What one terminal is doing")async def terminal_report(name: str, lines: int = 40) -> dict:"""Status plus the recent readable output of the terminal called ``name``."""diff --git a/tests/unit/agentic_ide/test_recap.py b/tests/unit/agentic_ide/test_recap.pynew file mode 100644index 0000000000..a0bec40bf9--- /dev/null+++ b/tests/unit/agentic_ide/test_recap.py@@ -0,0 +1,146 @@+"""Session recap: the one-line answer a pane header gives.++The recap is derived, never stored, so every test here pins a property of the+derivation: which signal wins when several are available, what a pane says when+it has nothing to report, and which rows of a coding CLI's TUI must never end up+in the header. Without the last one every busy pane in a grid reads "? for+shortcuts", which is the shape of a label that answers nothing.+"""+from __future__ import annotations++import time++from jarvis.agentic_ide.recap import HEADLINE_CHARS, summarize+from jarvis.agentic_ide.session import Terminal+++def _pane(**changes: object) -> Terminal:+ term = Terminal(+ key="mika",+ name="Mika",+ agent="claude",+ display_name="Claude Code",+ index=0,+ )+ for field, value in changes.items():+ setattr(term, field, value)+ return term+++def test_a_fresh_pane_says_it_has_not_started() -> None:+ recap = summarize(_pane())+ assert "Not started" in recap.headline+ assert recap.detail+++def test_the_headline_reports_what_the_pane_last_printed() -> None:+ """The freshest signal wins: output beats the instruction that caused it."""+ term = _pane(status="live", last_prompt="Fix the failing login test")+ term.transcript.feed("Running pytest tests/unit/test_login.py\r\n")++ recap = summarize(term)++ assert recap.headline == "Running pytest tests/unit/test_login.py"+ # ...and the instruction is still there, in the longer form.+ assert "Fix the failing login test" in recap.detail+++def test_a_live_pane_that_printed_nothing_falls_back_to_its_instruction() -> None:+ term = _pane(status="live", last_prompt="Refactor the config writer", prompts_sent=1)++ recap = summarize(term)++ assert "Refactor the config writer" in recap.headline+++def test_tui_chrome_never_becomes_the_headline() -> None:+ """A status bar is drawn on every frame — it is not what the agent did."""+ term = _pane(status="live")+ term.transcript.feed("Writing jarvis/core/config_writer.py\r\n")+ term.transcript.feed("? for shortcuts\r\n")+ term.transcript.feed("Context left until auto-compact: 34%\r\n")++ assert summarize(term).headline == "Writing jarvis/core/config_writer.py"+++def test_the_input_line_never_becomes_the_headline() -> None:+ """The prompt box is what the USER is typing, not what the agent is doing."""+ term = _pane(status="live")+ term.transcript.feed("Ran 42 tests, all green\r\n")+ term.transcript.feed("> and now update the docs\r\n")++ assert summarize(term).headline == "Ran 42 tests, all green"+++def test_bullet_glyphs_are_stripped_from_the_headline() -> None:+ term = _pane(status="live")+ term.transcript.feed("⏺ Read jarvis/agentic_ide/session.py\r\n")++ assert summarize(term).headline == "Read jarvis/agentic_ide/session.py"+++def test_a_failed_pane_leads_with_the_reason() -> None:+ term = _pane(status="error", error="Claude Code is not on PATH.")++ recap = summarize(term)++ assert "not on PATH" in recap.headline+ assert "not running" in recap.detail+++def test_an_exited_pane_reports_its_exit_code() -> None:+ term = _pane(status="exited", exit_code=1)+ term.transcript.feed("Build failed: 3 type errors\r\n")++ recap = summarize(term)++ assert "code 1" in recap.headline+ assert "Build failed: 3 type errors" in recap.detail+++def test_a_clean_exit_is_not_reported_as_a_failure() -> None:+ recap = summarize(_pane(status="exited", exit_code=0))+ assert "code" not in recap.headline.lower()+++def test_the_detail_says_when_the_pane_last_spoke() -> None:+ term = _pane(status="live", last_output_at=time.time() - 90)+ term.transcript.feed("Compiling the frontend\r\n")++ assert "1 min ago" in summarize(term).detail+++def test_the_headline_is_capped_for_transport() -> None:+ """A pane that prints a wall of JSON must not push it through every poll."""+ term = _pane(status="live")+ # A wide pane, so the row is not already clipped by the terminal's width.+ term.transcript.resize(400, 30)+ term.transcript.feed("word " * 200 + "\r\n")++ headline = summarize(term).headline++ assert len(headline) <= HEADLINE_CHARS + 1 # the ellipsis+ assert headline.endswith("…")+++def test_a_pane_serializes_its_recap_for_the_ui() -> None:+ term = _pane(status="live", last_prompt="Ship the release")+ term.transcript.feed("Tagging v2.4.0\r\n")++ data = term.to_dict()++ assert data["recap"] == "Tagging v2.4.0"+ assert "Ship the release" in data["recap_detail"]+++def test_summarize_survives_a_pane_without_a_transcript() -> None:+ """A recap is a convenience — it must never be what breaks a state read."""++ class Half:+ status = "live"+ last_prompt = ""+ prompts_sent = 0+ transcript = None+ last_output_at = None++ assert summarize(Half()).headlinediff --git a/tests/unit/agentic_ide/test_recap_route.py b/tests/unit/agentic_ide/test_recap_route.pynew file mode 100644index 0000000000..f516cb2404--- /dev/null+++ b/tests/unit/agentic_ide/test_recap_route.py@@ -0,0 +1,98 @@+"""`GET /api/agentic-ide/recaps` — the read the pane headers poll.++It runs several times a minute per open workspace, so the properties worth+pinning are the boring ones: it answers for the workspace asked for, it never+raises when the workspace is gone, and it says the same thing the state payload+says (two surfaces disagreeing about what a pane is doing is worse than either+of them being silent).+"""++from __future__ import annotations++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.agentic_ide import session as ide+from jarvis.ui.web import agentic_ide_routes+++def client() -> TestClient:+ ide.reset_registry()+ app = FastAPI()+ app.include_router(agentic_ide_routes.router)+ with TestClient(app) as test_client:+ yield test_client+ ide.reset_registry()+++def _workspace(tmp_path, name: str = "Mika") -> ide.Session:+ """One open workspace holding a single pane, without spawning anything."""+ registry = ide.get_registry()+ session = ide.Session(+ id="ide_test",+ folder=str(tmp_path),+ name="Test",+ profile=ide.probe_project(tmp_path),+ terminals=[+ ide.Terminal(+ key=name.lower(),+ name=name,+ agent="claude",+ display_name="Claude Code",+ index=0,+ )+ ],+ created_at=0.0,+ )+ registry._sessions[session.id] = session # noqa: SLF001 - no spawn in a unit test+ registry._active = session.id # noqa: SLF001+ return session+++def test_recaps_describe_every_pane_of_the_open_workspace(client, tmp_path) -> None:+ session = _workspace(tmp_path)+ term = session.terminals[0]+ term.status = "live"+ term.last_prompt = "Fix the failing login test"+ term.transcript.feed("Running pytest tests/unit/test_login.py\r\n")++ body = client.get("/api/agentic-ide/recaps").json()++ assert body["workspace_id"] == session.id+ assert len(body["terminals"]) == 1+ row = body["terminals"][0]+ assert row["name"] == "Mika"+ assert row["status"] == "live"+ assert row["recap"] == "Running pytest tests/unit/test_login.py"+ assert "Fix the failing login test" in row["recap_detail"]+++def test_the_route_and_the_state_payload_agree(client, tmp_path) -> None:+ session = _workspace(tmp_path)+ session.terminals[0].status = "live"+ session.terminals[0].transcript.feed("Reading jarvis/core/config.py\r\n")++ polled = client.get("/api/agentic-ide/recaps").json()["terminals"][0]+ state = client.get("/api/agentic-ide/state").json()["session"]["terminals"][0]++ assert polled["recap"] == state["recap"]+ assert polled["recap_detail"] == state["recap_detail"]+++def test_an_unknown_workspace_answers_empty_rather_than_404(client, tmp_path) -> None:+ """A poll outliving the workspace it started for is normal, not an error."""+ _workspace(tmp_path)++ response = client.get("/api/agentic-ide/recaps?workspace_id=ide_gone")++ assert response.status_code == 200+ assert response.json() == {"workspace_id": None, "terminals": []}+++def test_no_workspace_at_all_is_an_empty_answer(client) -> None:+ response = client.get("/api/agentic-ide/recaps")++ assert response.status_code == 200+ assert response.json()["terminals"] == []