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
fix(agentic-ide): deliver correlated coding reports before announcing completion (#448)
Ruben Lütkef86e3519e0d3
diff --git a/jarvis/agentic_ide/followthrough.py b/jarvis/agentic_ide/followthrough.pyindex 11990c48ec..4f9c80d0c1 100644--- a/jarvis/agentic_ide/followthrough.py+++ b/jarvis/agentic_ide/followthrough.py@@ -14,6 +14,8 @@ from loguru import loggerfrom jarvis.core.delegation import result_announcement+from . import agent_transcript+@dataclass(frozen=True, slots=True)class PendingResult:@@ -25,10 +27,10 @@ class PendingResult:generation: intreply_session_id: str = ""submitted_at: float | None = None+ prepared_at: float = 0.0-def _turns(term: Any) -> list:- from . import agent_transcript+def _events(term: Any) -> list:from .session import account_home# A remote pane's local transcript belongs to its old process.@@ -36,30 +38,80 @@ def _turns(term: Any) -> list:return []if not agent_transcript.can_read(term.agent):return []- return agent_transcript.read(+ events = agent_transcript.read_events(term.agent, term.resume.id, home=account_home(term.agent, term.account),+ live=True,) or []+ # Tool output is unnecessary for correlation and can be very large. Keep+ # work boundaries, so a new turn still invalidates an earlier completion.+ return [event for event in events if event["kind"] in {+ "user_message", "assistant_text", "turn_started", "turn_finished",+ }]-def _fingerprint(turns: list) -> str:- return hashlib.sha256(repr([(t.role, t.text) for t in turns]).encode()).hexdigest()+def _fingerprint(events: list) -> str:+ return hashlib.sha256(repr(events).encode()).hexdigest()def _snapshot(term: Any) -> list:try:- return _turns(term)+ return _events(term)except Exception: # A missing transcript cannot prevent authorized delivery.logger.opt(exception=True).debug("Delegated pane transcript unavailable")return []+def _completion_report(events: list, pending: PendingResult) -> str:+ """Read the final answer to this submission, preserving message boundaries.++ Display turns merge adjacent user messages (including repository instructions)+ and assistant progress. They cannot identify a work order or its final report.+ The live event reader retains those boundaries and requires a CLI end marker.+ """+ if not events or _fingerprint(events) == pending.baseline:+ return ""+ start = next(+ (i for i in range(len(events) - 1, -1, -1) if events[i]["kind"] == "user_message"),+ None,+ )+ if start is None:+ return ""+ user = events[start]+ expected = agent_transcript._clip(agent_transcript._spoken(pending.prompt))+ if (+ int(user.get("ts_ms") or 0)+ < int((pending.prepared_at or pending.submitted_at or 0) * 1000)+ or " ".join(user["payload"].get("text", "").split()) != " ".join(expected.split())+ ):+ return ""+ own = events[start + 1:]+ if not own or own[-1]["kind"] != "turn_finished":+ return ""+ finish = own[-1]["payload"]+ if finish.get("status") != "done" or not finish.get("turn_id"):+ return ""+ return next(+ (+ str(event["payload"].get("text") or "").strip()+ for event in reversed(own)+ if event["kind"] == "assistant_text"+ and event["payload"].get("turn_id") == finish["turn_id"]+ ),+ "",+ )++async def prepare(term: Any, prompt: str, request: str, origin: dict[str, str]) -> PendingResult:- turns = await asyncio.to_thread(_snapshot, term)+ # The CLI can record the prompt before its input receipt is confirmed and+ # last_submit_at is stamped. Freshness starts before that write, not after.+ prepared_at = time.time()+ events = await asyncio.to_thread(_snapshot, term)return PendingResult(request_id=uuid4().hex, prompt=prompt, request=request or prompt,- language=origin.get("lang", ""), baseline=_fingerprint(turns),+ language=origin.get("lang", ""), baseline=_fingerprint(events),generation=term.process_generation,reply_session_id=origin.get("reply_session_id", ""),+ prepared_at=prepared_at,)@@ -81,7 +133,7 @@ def current(term: Any, pending: PendingResult) -> bool:async def publish_result(- kind: str, term: Any, pending: PendingResult, publish: Any, *, require_report: bool = False,+ kind: str, term: Any, pending: PendingResult, publish: Any,) -> bool:"""Return an observed stop/question, never convert silence into success."""if publish is None or not current(term, pending):@@ -96,22 +148,28 @@ async def publish_result(if kind == "needs_input" and proof.state != "asking" and not shows_question(term):return Falsetry:- turns = await asyncio.to_thread(_snapshot, term)+ events = await asyncio.to_thread(_snapshot, term)if not current(term, pending):return Falseproof = await probe(term)+ if not current(term, pending):+ return Falseif kind in {"completed", "stopped"} and (proof is None or proof.state != expected[kind]):return Falseif kind == "needs_input" and proof.state != "asking" and not shows_question(term):return False- last_user = next((t.text for t in reversed(turns) if t.role == "user"), "")- matches = " ".join(last_user.split()) == " ".join(pending.prompt.split())- fresh = bool(turns and _fingerprint(turns) != pending.baseline and matches)report = ""evidence = "terminal_state_only; task success is unverified"- if kind == "completed" and fresh and turns[-1].role == "assistant":- report = str(turns[-1].text or "")- evidence = "fresh assistant message for this exact prompt; not independent verification"+ if kind == "completed":+ report = _completion_report(events, pending)+ # Completion and transcript persistence can be observed separately.+ # Keep the request pending for the next sweep instead of delivering+ # an empty report that the conversation mistakes for missing work.+ if not report:+ return False+ evidence = (+ "recorded CLI completion and matching final report; not independent verification"+ )elif kind == "needs_input":report = "\n".join(term.transcript.tail(20))[-3000:]evidence = "current terminal question; not a completed task"@@ -120,8 +178,6 @@ async def publish_result(evidence = "explicit interruption in the current CLI session"elif kind in {"failed", "exited"}:report = f"Process state: {kind}; exit code: {getattr(term, 'exit_code', None)}"- if require_report and not report:- return Falseevent = result_announcement(source="agentic_ide.readback", request_id=pending.request_id,name=str(term.name), request=pending.request, status=kind,@@ -173,6 +229,4 @@ async def poll_ready(registry: Any, publish: Any, *, now: float | None = None) -}.get(term.reading().activity)if kind is not None:term.delegation_probe_at = moment- await publish_result(- kind, term, pending, publish, require_report=kind == "completed",- )+ await publish_result(kind, term, pending, publish)diff --git a/tests/unit/agentic_ide/test_followthrough.py b/tests/unit/agentic_ide/test_followthrough.pyindex b201da27e8..98a1240449 100644--- a/tests/unit/agentic_ide/test_followthrough.py+++ b/tests/unit/agentic_ide/test_followthrough.py@@ -5,20 +5,30 @@ from types import SimpleNamespaceimport pytestfrom jarvis.agentic_ide import followthrough as ft-from jarvis.agentic_ide.agent_transcript import Turnfrom jarvis.core.events import AnnouncementRequested, DelegationResultReady+def _finished(prompt, report, *, at=101):+ return [+ {"kind": "user_message", "ts_ms": at * 1000, "payload": {"text": prompt}},+ {"kind": "assistant_text", "ts_ms": (at + 1) * 1000,+ "payload": {"text": report, "turn_id": "current"}},+ {"kind": "turn_finished", "ts_ms": (at + 2) * 1000,+ "payload": {"status": "done", "turn_id": "current"}},+ ]++@pytest.fixturedef pane(monkeypatch):- turns = [Turn("user", "Old task"), Turn("assistant", "Old answer")]+ monkeypatch.setattr(ft, "time", SimpleNamespace(time=lambda: 100.0))+ turns = [*_finished("Old task", "Old answer", at=90)]term = SimpleNamespace(name="T2", process_generation=1, last_submit_at=100.0, last_prompt="Fix the bug",submitted=True, delegation_result=None, exit_code=None,last_output_at=100.0, reading=lambda: SimpleNamespace(activity="waiting"),transcript=SimpleNamespace(tail=lambda n: ["Which repository should I change?"]),)- monkeypatch.setattr(ft, "_turns", lambda t: list(turns))+ monkeypatch.setattr(ft, "_events", lambda t: list(turns))from jarvis.agentic_ide import task_stateasync def completed(_term):@@ -39,7 +49,7 @@ async def arm(pane, **origin):async def test_fresh_correlated_answer_reaches_voice_once(pane):pending = await arm(pane)term, turns = pane- turns.extend([Turn("user", "Fix the bug"), Turn("assistant", "Fixed login; tests passed.")])+ turns.extend(_finished("Fix the bug", "Fixed login; tests passed."))events = []assert await ft.publish_result("completed", term, pending, events.append)assert not await ft.publish_result("completed", term, pending, events.append)@@ -53,14 +63,14 @@ async def test_fresh_correlated_answer_reaches_voice_once(pane):async def test_stale_transcript_never_becomes_the_current_answer(pane, stale):term, turns = paneif stale == "same_prompt":- turns[:] = [Turn("user", "Fix the bug"), Turn("assistant", "Old answer")]+ turns[:] = _finished("Fix the bug", "Old answer", at=90)pending = await arm(pane)if stale == "unrelated":- turns.extend([Turn("user", "Other task"), Turn("assistant", "Unrelated answer")])+ turns.extend(_finished("Other task", "Unrelated answer"))events = []- await ft.publish_result("completed", term, pending, events.append)- assert "Old answer" not in events[0].report and "Unrelated answer" not in events[0].report- assert "unverified" in events[0].report+ assert not await ft.publish_result("completed", term, pending, events.append)+ assert not events+ assert term.delegation_result is pending@pytest.mark.asyncio@@ -90,7 +100,7 @@ async def test_question_does_not_consume_later_completion(pane, monkeypatch):await ft.publish_result("needs_input", term, pending, events.append)assert "Which repository" in events[0].reportassert term.delegation_result is pending- turns.extend([Turn("user", "Fix the bug"), Turn("assistant", "Resolved.")])+ turns.extend(_finished("Fix the bug", "Resolved."))await ft.publish_result("completed", term, pending, events.append)assert len(events) == 2 and "Resolved" in events[1].report@@ -119,7 +129,7 @@ async def test_fast_job_finishing_between_sweeps_still_returns_its_fresh_answer(events = []await ft.poll_ready(registry, events.append, now=130.0)assert not events # An idle terminal and an old answer are not completion evidence.- turns.extend([Turn("user", "Fix the bug"), Turn("assistant", "Fixed immediately.")])+ turns.extend(_finished("Fix the bug", "Fixed immediately."))await ft.poll_ready(registry, events.append, now=141.0)assert len(events) == 1 and "Fixed immediately" in events[0].report@@ -131,7 +141,7 @@ async def test_silence_and_interim_text_do_not_announce_completion(pane, monkeyppending = await arm(pane)term, turns = pane- turns.extend([Turn("user", "Fix the bug"), Turn("assistant", "Checking the tests now.")])+ turns.extend(_finished("Fix the bug", "Checking the tests now."))async def unfinished(_term):return task_state.Evidence(state)@@ -175,3 +185,35 @@ async def test_confirmed_stop_has_distinct_wording_and_no_completion_claim(pane,assert "was interrupted" in events[0].textassert "no completion" in events[0].reportassert pane[0].delegation_result is None+++async def test_submission_change_during_final_probe_cannot_consume_result(pane, monkeypatch):+ from jarvis.agentic_ide import task_state++ pending = await arm(pane)+ term, turns = pane+ turns.extend(_finished("Fix the bug", "Fixed."))+ calls = []++ async def changing(_term):+ calls.append(None)+ if len(calls) == 2:+ term.last_submit_at += 1+ return task_state.Evidence("completed")++ monkeypatch.setattr(task_state, "probe", changing)+ events = []+ assert not await ft.publish_result("completed", term, pending, events.append)+ assert not events+++async def test_late_old_record_for_identical_prompt_is_not_fresh_work(pane):+ pending = await arm(pane)+ term, turns = pane+ turns.extend(_finished("Fix the bug", "An older result.", at=90))+ events = []+ assert not await ft.publish_result("completed", term, pending, events.append)+ assert not events+ assert term.delegation_result is pendingdiff --git a/tests/unit/agentic_ide/test_followthrough_recorded.py b/tests/unit/agentic_ide/test_followthrough_recorded.pynew file mode 100644index 0000000000..314f592066--- /dev/null+++ b/tests/unit/agentic_ide/test_followthrough_recorded.py@@ -0,0 +1,175 @@+"""Exercise automatic readback with native CLI records, not display-turn fakes."""++import json+from datetime import UTC, datetime+from types import SimpleNamespace++import pytest++from jarvis.agentic_ide import agent_transcript, followthrough, task_state+from jarvis.core.delegation import ResultInbox+++def _stamp(seconds):+ return datetime.fromtimestamp(seconds, UTC).isoformat()+++def recorded(tmp_path, monkeypatch):+ monkeypatch.setattr(followthrough, "time", SimpleNamespace(time=lambda: 100.0))+ path = tmp_path / "session.jsonl"+ path.write_text("", encoding="utf-8")+ monkeypatch.setattr(agent_transcript, "_codex_file", lambda *args: path)+ monkeypatch.setattr(agent_transcript, "_claude_file", lambda *args: path)+ task_state.reset()+ term = SimpleNamespace(+ name="Coder", agent="codex", account=None, resume=SimpleNamespace(id="recorded"),+ process_generation=1, last_submit_at=100.0, last_prompt="Fix startup latency",+ submitted=True, delegation_result=None, last_output_at=103.0,+ reading=lambda: SimpleNamespace(activity="waiting"),+ )++ def write(rows):+ path.write_text("\n".join(json.dumps(row) for row in rows) + "\n", encoding="utf-8")++ yield term, write+ task_state.reset()+++def _message(role, text, at):+ return {+ "timestamp": _stamp(at), "type": "response_item",+ "payload": {"type": "message", "role": role, "content": [+ {"type": "input_text" if role == "user" else "output_text", "text": text},+ ]},+ }+++def _codex_rows(prompt, *, complete=True):+ rows = [+ _message(+ "user", "# AGENTS.md instructions for /project\n<INSTRUCTIONS>Rules</INSTRUCTIONS>",+ 100,+ ),+ _message("user", prompt, 101),+ _message("assistant", "Investigating; no result yet.", 102),+ _message(+ "assistant", "Fixed startup latency. Offline tests passed; live audio unverified.", 103,+ ),+ ]+ if complete:+ rows.append({"timestamp": _stamp(104), "type": "event_msg",+ "payload": {"type": "task_complete"}})+ return rows+++async def _arm(term):+ pending = await followthrough.prepare(term, term.last_prompt, term.last_prompt, {"lang": "en"})+ followthrough.submitted(term, pending)+ return term.delegation_result++[email protected]("long_prompt", [False, True])+async def test_codex_instructions_do_not_hide_final_report(recorded, long_prompt):+ term, write = recorded+ if long_prompt:+ term.last_prompt += " Preserve cancellation and privacy." * 160+ pending = await _arm(term)+ write(_codex_rows(term.last_prompt))+ inbox = ResultInbox()+ assert await followthrough.publish_result("completed", term, pending, inbox.add)+ batch = inbox.take()+ assert "Fixed startup latency" in batch.report+ assert "live audio unverified" in batch.report+ assert "Investigating; no result yet." not in batch.report+ assert term.delegation_result is None+ assert not await followthrough.publish_result("completed", term, pending, inbox.add)+ assert inbox.take() is None+++async def test_delayed_report_is_retried_without_empty_announcement(recorded, monkeypatch):+ term, write = recorded+ pending = await _arm(term)+ write(_codex_rows(term.last_prompt))+ events = []+ # Lifecycle already sees task_complete while the report read lags behind.+ snapshot = followthrough._snapshot+ with monkeypatch.context() as lagging:+ lagging.setattr(followthrough, "_snapshot", lambda _term: [])+ assert not await followthrough.publish_result("completed", term, pending, events.append)+ assert not events+ assert term.delegation_result is pending+ assert snapshot(term)+ registry = SimpleNamespace(sessions=[SimpleNamespace(terminals=[term])])+ await followthrough.poll_ready(registry, events.append, now=130.0)+ assert len(events) == 1+ assert "Fixed startup latency" in events[0].report+ assert term.delegation_result is None+++async def test_native_claude_report_reaches_the_original_chat(recorded):+ term, write = recorded+ term.agent = "claude"+ pending = await followthrough.prepare(+ term, term.last_prompt, term.last_prompt, {"lang": "en", "reply_session_id": "origin"},+ )+ followthrough.submitted(term, pending)+ write([+ {"type": "user", "timestamp": _stamp(101),+ "message": {"role": "user", "content": term.last_prompt}},+ {"type": "assistant", "timestamp": _stamp(102), "message": {+ "role": "assistant", "content": [{"type": "text", "text": "Fixed; tests passed."}],+ "stop_reason": "end_turn",+ }},+ ])+ events = []+ assert await followthrough.publish_result(+ "completed", term, term.delegation_result, events.append,+ )+ assert events[0].session_id == "origin"+ assert "Fixed; tests passed." in json.loads(events[0].report)["report"]+++async def test_another_submission_cannot_supply_the_missing_report(recorded):+ term, write = recorded+ pending = await _arm(term)+ rows = _codex_rows(term.last_prompt)+ rows.extend(_codex_rows("An unrelated task"))+ write(rows)+ events = []+ assert not await followthrough.publish_result("completed", term, pending, events.append)+ assert not events+ assert term.delegation_result is pending+++async def test_prompt_recorded_before_input_receipt_still_matches(recorded):+ term, write = recorded+ pending = await followthrough.prepare(term, term.last_prompt, term.last_prompt, {"lang": "en"})+ write(_codex_rows(term.last_prompt))+ term.last_submit_at = 102.0 # The prompt was recorded at 101, before receipt confirmation.+ followthrough.submitted(term, pending)+ events = []+ assert await followthrough.publish_result(+ "completed", term, term.delegation_result, events.append,+ )+ assert "Fixed startup latency" in events[0].report++[email protected]("ending", [None, "turn_aborted"])+async def test_unfinished_or_interrupted_output_never_becomes_a_report(recorded, ending):+ term, write = recorded+ pending = await _arm(term)+ rows = _codex_rows(term.last_prompt, complete=False)+ if ending:+ rows.append({"timestamp": _stamp(104), "type": "event_msg", "payload": {"type": ending}})+ write(rows)+ events = []+ assert not await followthrough.publish_result("completed", term, pending, events.append)+ assert not events+ assert term.delegation_result is pending