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): never resume an id with no conversation behind it
Ruben Lütke86389c33e6a0
diff --git a/jarvis/agentic_ide/agent_sessions.py b/jarvis/agentic_ide/agent_sessions.pyindex 8e1d50d660..520a967618 100644--- a/jarvis/agentic_ide/agent_sessions.py+++ b/jarvis/agentic_ide/agent_sessions.py@@ -39,7 +39,7 @@ import osimport timefrom collections.abc import Callable, Collectionfrom dataclasses import dataclass-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom pathlib import Pathfrom typing import Anyfrom uuid import uuid4@@ -110,6 +110,8 @@ class _Adapter:# Finds the id afterwards, for CLIs that cannot be told one. The third# argument is the set of ids other panes already hold — see `discover`.discover: Callable[[str, float, Collection[str]], ResumeHandle | None] | None+ # Is there actually a conversation behind an id? See `has_conversation`.+ exists: Callable[[ResumeHandle], bool]def _claude_launch() -> tuple[tuple[str, ...], ResumeHandle | None]:@@ -132,6 +134,7 @@ _ADAPTERS: dict[str, _Adapter] = {launch=_claude_launch,resume=lambda session_id: ("--resume", session_id),discover=None,+ exists=lambda handle: _claude_conversation_exists(handle),),"codex": _Adapter(kind="codex_rollout",@@ -142,6 +145,7 @@ _ADAPTERS: dict[str, _Adapter] = {# Late-bound on purpose: the discovery function is defined further down,# next to the file-format knowledge it needs.discover=lambda cwd, started, taken: _discover_codex(cwd, started, taken),+ exists=lambda handle: _codex_conversation_exists(handle),),}@@ -178,6 +182,38 @@ def resume_argv(agent: str, handle: ResumeHandle | None) -> tuple[str, ...] | Noreturn adapter.resume(handle.id)+def has_conversation(agent: str, handle: ResumeHandle | None) -> bool:+ """Is there actually something behind this handle, or only a reserved id?++ **The distinction this whole module got wrong at first.** Being handed an id+ at launch does not create a conversation. Claude Code writes a session file+ only once the conversation HAS content, so a pane that was opened and never+ given an instruction leaves nothing behind — and resuming that id makes the+ CLI print "No conversation found" and exit. Measured on a real workspace:+ twelve panes opened, none prompted, twelve dead panes on the way back.++ So a handle is a pointer that has to be dereferenced before it is spent. The+ check is a filename lookup keyed on the id, which is a UUID and therefore+ unique across every project — that keeps it independent of how the CLI+ happens to name its per-project folders, and it costs a few milliseconds.++ Answers False for an unknown agent and for no handle at all. False always+ means the same thing to the caller: start fresh, and say so.+ """+ if handle is None:+ return False+ adapter = _ADAPTERS.get(agent)+ if adapter is None or adapter.kind != handle.kind:+ return False+ try:+ return adapter.exists(handle)+ except OSError as exc:+ # An unreadable history is not a present conversation. Starting fresh is+ # recoverable; launching into a missing one kills the pane.+ logger.debug("Agentic IDE: could not check {} history: {}", agent, exc)+ return False++def discover(agent: str,cwd: str,@@ -208,6 +244,30 @@ def discover(return None+# -------------------------------------------------------------- Claude Code+def _claude_home() -> Path:+ raw = os.environ.get("CLAUDE_CONFIG_DIR")+ return Path(raw).expanduser() if raw else Path.home() / ".claude"+++def _claude_conversation_exists(handle: ResumeHandle) -> bool:+ """True when Claude Code has a transcript filed under this session id.++ Searched by id across all project folders rather than by rebuilding the+ folder name from the working directory. That name is the CLI's own+ convention (separators and spaces folded into dashes) and could change+ without notice, while the id is a UUID and unique everywhere — so this stays+ correct even if the layout shifts, and on any OS.+ """+ session_id = handle.id+ if not session_id or "/" in session_id or "\\" in session_id:+ return False+ projects = _claude_home() / "projects"+ if not projects.is_dir():+ return False+ return next(projects.glob(f"*/{session_id}.jsonl"), None) is not None++# --------------------------------------------------------------------- Codexdef _codex_home() -> Path:raw = os.environ.get("CODEX_HOME")@@ -314,6 +374,37 @@ def _candidate_files(root: Path, started_at: float) -> list[Path]:return keep[:_MAX_CANDIDATES]+def _codex_conversation_exists(handle: ResumeHandle) -> bool:+ """True when Codex still has the rollout file this handle came from.++ The id is in the filename, and ``captured_at`` says roughly when it was+ written, so only the day folders around that moment are searched — a heavy+ user has thousands of rollouts and a full sweep would turn opening a pane+ into a disk crawl. The one-day margin is the same one discovery needs: the+ folder is named in local time and the record inside is UTC.+ """+ session_id = handle.id+ if not session_id or "/" in session_id or "\\" in session_id:+ return False+ sessions = _codex_home() / "sessions"+ if not sessions.is_dir():+ return False+ if handle.captured_at <= 0:+ # No hint when it was written — one bounded sweep rather than none.+ return next(sessions.glob(f"*/*/*/rollout-*{session_id}*.jsonl"), None) is not None+ day = datetime.fromtimestamp(handle.captured_at, tz=UTC).date()+ for offset in (0, -1, 1):+ folder = sessions / f"{day.year:04d}" / f"{day.month:02d}" / f"{day.day:02d}"+ if offset:+ shifted = day + timedelta(days=offset)+ folder = (+ sessions / f"{shifted.year:04d}" / f"{shifted.month:02d}" / f"{shifted.day:02d}"+ )+ if next(folder.glob(f"rollout-*{session_id}*.jsonl"), None) is not None:+ return True+ return False++def _discover_codex(cwd: str, started_at: float, taken: Collection[str] = ()) -> ResumeHandle | None:@@ -364,6 +455,7 @@ __all__ = ["ResumeHandle","can_resume","discover",+ "has_conversation","launch_extra","resume_argv",]diff --git a/jarvis/agentic_ide/resume_store.py b/jarvis/agentic_ide/resume_store.pyindex a9da64d304..ae8c42d42b 100644--- a/jarvis/agentic_ide/resume_store.py+++ b/jarvis/agentic_ide/resume_store.py@@ -40,7 +40,7 @@ from uuid import uuid4from loguru import logger-from .agent_sessions import ResumeHandle+from .agent_sessions import ResumeHandle, has_conversation# Saves arrive from more than one thread (see `save`), and the last one has to# be the one that lands rather than the one that happened to finish its rename@@ -237,6 +237,13 @@ def offer(snapshot: Snapshot | None, *, installed: set[str]) -> dict[str, Any]:A pane that never received a prompt, or whose CLI cannot resume, is``available`` but not ``resumable``: it returns with the right name in theright place and an empty history. Saying so up front is the whole point.++ ``resumable`` asks the coding CLI's own history whether the conversation is+ really there, rather than trusting that a handle exists. Holding an id and+ having a conversation are different things — a pane opened and never given+ an instruction has the first and not the second — and promising twelve+ restored conversations that all turn out to be empty is exactly the lie this+ screen is meant to prevent."""if snapshot is None:return {@@ -268,7 +275,7 @@ def offer(snapshot: Snapshot | None, *, installed: set[str]) -> dict[str, Any]:"column": term.column,"slot": term.slot,"available": agent_available,- "resumable": agent_available and term.resume is not None,+ "resumable": agent_available and has_conversation(term.agent, term.resume),"prompts_sent": term.prompts_sent,})diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex f8ba2ec14b..9d6e8f52d9 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -55,6 +55,7 @@ from .agent_sessions import (ResumeHandle,can_resume,discover,+ has_conversation,launch_extra,resume_argv,)@@ -97,11 +98,13 @@ _SUBMIT_RETRY_AFTER_S = 1.0_INPUT_MARKERS = ("❯", ">", "›")# How quickly an agent has to die after a RESUME for the resume itself to be the-# suspect. A conversation the CLI has since pruned makes it print an error and-# exit almost immediately; a healthy agent that the user quits normally exits-# with code 0 and is never second-guessed. Past this window an exit is just an-# exit, and the pane says so.-RESUME_FAILED_WINDOW_S = 8.0+# suspect. A healthy agent the user quits normally exits with code 0 and is+# never second-guessed, and a deliberate kill is flagged as such — so this only+# has to be longer than a failing agent takes to fail. That is not instant: a+# coding CLI loads its plugins and hooks BEFORE reporting a missing+# conversation, and running SessionEnd hooks on the way out adds more. The+# first version used 8 s and watched twelve real panes die just past it.+RESUME_FAILED_WINDOW_S = 45.0# When to look for the session id of a CLI that cannot be told one (Codex). It# writes its rollout file a beat after launching, so asking immediately finds@@ -753,7 +756,20 @@ class Registry:term.error = f"{term.display_name} is not on PATH."raise SessionError(term.error)+ # A handle is a pointer, and it has to be dereferenced before it is+ # spent. Being handed an id at launch does not create a conversation:+ # a pane that was opened and never given an instruction leaves nothing+ # behind, and asking the CLI to resume that id makes it print "no+ # conversation found" and die. Measured on a real workspace — twelve+ # panes opened, none prompted, twelve dead panes on the way back.continuing = resume_argv(term.agent, term.resume)+ if continuing is not None and not has_conversation(term.agent, term.resume):+ logger.info(+ "Agentic IDE: {} has no conversation to continue — starting fresh",+ term.name,+ )+ term.resume = None+ continuing = Noneif continuing is not None:argv = (*argv, *continuing)term.resumed = Truediff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex d0560cddf6..c57dad18e1 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -45,6 +45,7 @@ from fastapi import (from pydantic import BaseModel, Fieldfrom jarvis.agentic_ide import recents, resume_store+from 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_pointsfrom jarvis.agentic_ide.names import default_names@@ -550,7 +551,17 @@ async def resume_workspace() -> dict:except Exception: # noqa: BLE001 - history must never block reopeninglog.warning("Agentic IDE recent-folder history was not updated", exc_info=True)- resumable = sum(1 for t in session.terminals if t.resume is not None)+ # Counted by asking the coding CLI's history, not by counting handles a pane+ # happens to hold: a pane that was opened and never used holds an id that+ # points at nothing, and reporting it as continued would be the same lie the+ # offer screen exists to prevent. One thread hop for the whole list, since+ # each check is a filename lookup.+ def _count_conversations(panes: list[tuple[str, object]]) -> int:+ return sum(1 for agent, handle in panes if has_conversation(agent, handle))++ resumable = await asyncio.to_thread(+ _count_conversations, [(t.agent, t.resume) for t in session.terminals]+ )return {"ok": True,"session": session.to_dict(),diff --git a/tests/unit/agentic_ide/conftest.py b/tests/unit/agentic_ide/conftest.pyindex d58809e9cc..1c5c2a648a 100644--- a/tests/unit/agentic_ide/conftest.py+++ b/tests/unit/agentic_ide/conftest.py@@ -48,3 +48,45 @@ def _never_touch_real_agent_configs(monkeypatch: pytest.MonkeyPatch) -> None:return []monkeypatch.setattr(trust, "ensure_trusted", _skip)++[email protected](autouse=True)+def _agent_history_in_tmp(+ tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch+) -> Path:+ """Give each test an empty stand-in for the coding CLIs' own histories.++ Resuming asks the CLI whether a conversation really exists, so tests read+ that history. Pointed at the real one they would inherit whatever the+ developer happens to have on disk — a test could pass because an unrelated+ conversation was lying around, or fail on a fresh machine.+ """+ home = tmp_path_factory.mktemp("agent-history")+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(home / "claude"))+ monkeypatch.setenv("CODEX_HOME", str(home / "codex"))+ return home+++def existing_conversation() -> Any:+ """Create the on-disk conversation a resume handle points at.++ Real files rather than a patched check: the difference between "a handle+ exists" and "a conversation exists" is the bug this guards, and stubbing the+ lookup would stub out exactly the thing under test.+ """+ from jarvis.agentic_ide import agent_sessions++ def _make(session_id: str, *, agent: str = "claude") -> None:+ if agent == "claude":+ folder = agent_sessions._claude_home() / "projects" / "a-project"+ folder.mkdir(parents=True, exist_ok=True)+ (folder / f"{session_id}.jsonl").write_text("{}\n", encoding="utf-8")+ else:+ folder = agent_sessions._codex_home() / "sessions" / "2026" / "07" / "26"+ folder.mkdir(parents=True, exist_ok=True)+ (folder / f"rollout-2026-07-26T00-00-00-{session_id}.jsonl").write_text(+ "{}\n", encoding="utf-8"+ )++ return _makediff --git a/tests/unit/agentic_ide/test_resume_routes.py b/tests/unit/agentic_ide/test_resume_routes.pyindex d55a7e74ba..37b7dac139 100644--- a/tests/unit/agentic_ide/test_resume_routes.py+++ b/tests/unit/agentic_ide/test_resume_routes.py@@ -93,9 +93,10 @@ def test_the_offer_names_the_panes_and_where_they_sat(def test_the_offer_says_which_conversations_come_back(- client: TestClient, tmp_path: Path+ client: TestClient, tmp_path: Path, existing_conversation) -> None:_store(tmp_path)+ existing_conversation("u")body = client.get("/api/agentic-ide/resume").json()panes = {t["name"]: t for t in body["terminals"]}assert panes["Mika"]["resumable"] is True@@ -150,10 +151,11 @@ def test_resuming_reopens_the_workspace(client: TestClient, tmp_path: Path) -> Ndef test_resuming_reports_how_much_actually_came_back(- client: TestClient, tmp_path: Path+ client: TestClient, tmp_path: Path, existing_conversation) -> None:"""One pane continues, one reopens empty — and the caller is told."""_store(tmp_path)+ existing_conversation("u")body = client.post("/api/agentic-ide/resume").json()assert body["resumable_count"] == 1assert body["started_fresh"] == 1@@ -207,3 +209,18 @@ def test_discarding_a_restore_point_is_declared_dangerous() -> None:and "DELETE" in getattr(r, "methods", set()))assert route.openapi_extra == {"x-jarvis-dangerous": True}+++def test_resuming_counts_conversations_not_handles(+ client: TestClient, tmp_path: Path+) -> None:+ """A pane that was never used holds an id pointing at nothing.++ Counting handles would report it as continued, which is the same lie the+ offer screen exists to prevent — and the one that reached the user as+ "12 conversations restored" for twelve panes that came back empty.+ """+ _store(tmp_path) # Mika's id is deliberately not backed by a conversation+ body = client.post("/api/agentic-ide/resume").json()+ assert body["resumable_count"] == 0+ assert body["started_fresh"] == 2diff --git a/tests/unit/agentic_ide/test_resume_session.py b/tests/unit/agentic_ide/test_resume_session.pyindex 0eb5f9fa8f..e90b85733f 100644--- a/tests/unit/agentic_ide/test_resume_session.py+++ b/tests/unit/agentic_ide/test_resume_session.py@@ -62,13 +62,17 @@ async def test_a_fresh_pane_is_launched_with_an_id_it_can_be_found_by(async def test_a_pane_with_a_handle_continues_instead_of_starting_over(- registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path+ registry: ide.Registry,+ fake_pty: FakePtyManager,+ tmp_path: Path,+ existing_conversation,) -> None:await registry.start(str(tmp_path), [{"agent": "claude", "name": "Mika"}])term = registry.session.find("Mika")term.resume = ResumeHandle(kind="claude_session", id="known-id", captured_at=1.0)+ existing_conversation("known-id")await registry.attach("Mika", 80, 24, _noop, _noop_exit)assert _argv(fake_pty)[-2:] == ("--resume", "known-id")@@ -76,13 +80,18 @@ async def test_a_pane_with_a_handle_continues_instead_of_starting_over(async def test_reopening_a_pane_keeps_the_same_conversation(- registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path+ registry: ide.Registry,+ fake_pty: FakePtyManager,+ tmp_path: Path,+ existing_conversation,) -> None:"""The browser-close case: the pane reconnects and picks up where it was."""await registry.start(str(tmp_path), [{"agent": "claude", "name": "Mika"}])await registry.attach("Mika", 80, 24, _noop, _noop_exit)minted = registry.session.find("Mika").resumeassert minted is not None+ # The pane was used, so the CLI now has a conversation under that id.+ existing_conversation(minted.id)registry.detach("Mika") # the viewer went away, the agent was stoppedawait registry.attach("Mika", 80, 24, _noop, _noop_exit)@@ -105,14 +114,74 @@ async def test_a_pane_running_a_cli_that_cannot_resume_just_starts(assert registry.session.find("Mika").resumed is False+async def test_a_handle_with_no_conversation_behind_it_starts_fresh(+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """The failure that took down twelve real panes at once.++ Being handed an id at launch does not create a conversation — the CLI files+ one only when it has content. So a pane that was opened and never given an+ instruction holds an id that points at nothing, and asking the CLI to resume+ it makes it print "no conversation found" and exit. Every one of twelve+ panes came back dead that way.++ The pointer has to be dereferenced before it is spent.+ """+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Mika"}])+ term = registry.session.find("Mika")+ term.resume = ResumeHandle(+ kind="claude_session", id="never-written", captured_at=1.0+ )+ # Deliberately no conversation on disk.++ await registry.attach("Mika", 80, 24, _noop, _noop_exit)++ argv = _argv(fake_pty)+ assert "--resume" not in argv, "an id pointing at nothing must not be spent"+ assert "--session-id" in argv, "and the fresh start gets a usable id of its own"+ term = registry.session.find("Mika")+ assert term.resumed is False+ assert term.status == "live", "the pane must come up, not die"+ assert term.resume is not None and term.resume.id != "never-written"+++async def test_the_offer_does_not_promise_a_conversation_that_is_not_there(+ tmp_path: Path,+) -> None:+ """What the card would have claimed: twelve conversations, all empty."""+ snapshot = resume_store.Snapshot(+ session_id="ide_old",+ folder=str(tmp_path),+ saved_at=1.0,+ terminals=[+ resume_store.SnapshotTerminal(+ key="mika",+ name="Mika",+ agent="claude",+ resume=ResumeHandle(+ kind="claude_session", id="never-written", captured_at=1.0+ ),+ )+ ],+ )+ view = resume_store.offer(snapshot, installed={"claude"})+ assert view["terminals"][0]["available"] is True # the pane comes back+ assert view["terminals"][0]["resumable"] is False # the conversation does not+ assert view["resumable_count"] == 0++# ------------------------------------------------------------- self-healingasync def test_a_dead_conversation_falls_back_to_a_fresh_agent(- registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path+ registry: ide.Registry,+ fake_pty: FakePtyManager,+ tmp_path: Path,+ existing_conversation,) -> None:- """A conversation the CLI has pruned must not leave a dead pane behind."""+ """The backstop: a conversation that looks present but the CLI rejects."""await registry.start(str(tmp_path), [{"agent": "claude", "name": "Mika"}])term = registry.session.find("Mika")term.resume = ResumeHandle(kind="claude_session", id="stale", captured_at=1.0)+ existing_conversation("stale")exits: list[int] = []@@ -132,12 +201,16 @@ async def test_a_dead_conversation_falls_back_to_a_fresh_agent(async def test_a_clean_exit_after_a_resume_is_not_second_guessed(- registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path+ registry: ide.Registry,+ fake_pty: FakePtyManager,+ tmp_path: Path,+ existing_conversation,) -> None:"""Quitting an agent on purpose exits 0 — restarting it would be a bug."""await registry.start(str(tmp_path), [{"agent": "claude", "name": "Mika"}])term = registry.session.find("Mika")term.resume = ResumeHandle(kind="claude_session", id="fine", captured_at=1.0)+ existing_conversation("fine")exits: list[int] = []@@ -152,7 +225,10 @@ async def test_a_clean_exit_after_a_resume_is_not_second_guessed(async def test_closing_a_resumed_pane_does_not_resurrect_it(- registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path+ registry: ide.Registry,+ fake_pty: FakePtyManager,+ tmp_path: Path,+ existing_conversation,) -> None:"""The trap the self-healing walks into if it is not told about the kill.@@ -166,6 +242,7 @@ async def test_closing_a_resumed_pane_does_not_resurrect_it(registry.session.find("Mika").resume = ResumeHandle(kind="claude_session", id="fine", captured_at=1.0)+ existing_conversation("fine")await registry.attach("Mika", 80, 24, _noop, _noop_exit)assert registry.session.find("Mika").resumed is Truespawns_before = len(fake_pty.spawns)@@ -183,6 +260,7 @@ async def test_a_late_crash_is_reported_as_a_crash(fake_pty: FakePtyManager,tmp_path: Path,monkeypatch: pytest.MonkeyPatch,+ existing_conversation,) -> None:"""Past the window an exit is just an exit; a restart loop would be worse."""monkeypatch.setattr(ide, "RESUME_FAILED_WINDOW_S", 0.0)@@ -190,6 +268,7 @@ async def test_a_late_crash_is_reported_as_a_crash(registry.session.find("Mika").resume = ResumeHandle(kind="claude_session", id="fine", captured_at=1.0)+ existing_conversation("fine")exits: list[int] = []@@ -252,8 +331,12 @@ async def test_restore_starts_nothing_by_itself(async def test_a_restored_pane_continues_its_conversation_when_it_connects(- registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path+ registry: ide.Registry,+ fake_pty: FakePtyManager,+ tmp_path: Path,+ existing_conversation,) -> None:+ existing_conversation("kai-conv")await registry.restore(_snapshot(tmp_path))await registry.attach("Kai", 80, 24, _noop, _noop_exit)assert _argv(fake_pty)[-2:] == ("--resume", "kai-conv")diff --git a/tests/unit/agentic_ide/test_resume_store.py b/tests/unit/agentic_ide/test_resume_store.pyindex 194bc7c1f4..6637c3774e 100644--- a/tests/unit/agentic_ide/test_resume_store.py+++ b/tests/unit/agentic_ide/test_resume_store.py@@ -191,7 +191,10 @@ def test_two_threads_saving_at_once_do_not_lose_the_write(tmp_path: Path) -> Non# ------------------------------------------------------------------- offer-def test_the_offer_reports_what_will_actually_come_back(tmp_path: Path) -> None:+def test_the_offer_reports_what_will_actually_come_back(+ tmp_path: Path, existing_conversation+) -> None:+ existing_conversation("u-1")view = resume_store.offer(_snapshot(str(tmp_path)), installed={"claude"})assert view["available"] is Trueassert view["folder_exists"] is True