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(agentic-ide): resume a pane's conversation instead of starting over

Ruben Lütke49d26d63b6f5
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 91ec19da71..27dc184f9f 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -50,6 +50,14 @@ from uuid import uuid4
from loguru import logger
+from . import resume_store
+from .agent_sessions import (
+ ResumeHandle,
+ can_resume,
+ discover,
+ launch_extra,
+ resume_argv,
+)
from .folders import ProjectProfile, probe_project
from .names import default_names, normalize, resolve
from .transcript import Transcript
@@ -88,6 +96,18 @@ _SUBMIT_RETRY_AFTER_S = 1.0
# Glyphs an agent TUI draws in front of its input line.
_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
+
+# 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
+# nothing; two attempts cover a slow machine without turning into polling.
+DISCOVERY_DELAYS_S = (4.0, 12.0)
+
# Bracketed paste. A TUI that has enabled it receives everything between these
# markers as ONE pasted block rather than as keystrokes, which is the only way
# a structured prompt survives the trip: a bare "\n" written to a PTY IS the
@@ -274,6 +294,14 @@ class Terminal:
# rejected the pasted block and the single-line fallback carried it — worth
# seeing in the log, because it silently costs prompt readability.
sent_multiline: bool = False
+ # Where this pane's conversation lives inside the coding CLI's own history.
+ # The pane is the window; this is what the window looks at, and it is the
+ # only reason a closed browser is survivable (see .agent_sessions).
+ resume: ResumeHandle | None = None
+ # Did the CURRENT agent process continue that conversation, or start empty?
+ # Reported honestly rather than assumed: a resume can fail, and a user who
+ # is told "resumed" and gets an amnesiac agent has been lied to.
+ resumed: bool = False
transcript: Transcript = field(default_factory=Transcript)
def to_dict(self) -> dict[str, Any]:
@@ -297,8 +325,24 @@ class Terminal:
"last_prompt": self.last_prompt,
"submitted": self.submitted,
"lines_captured": len(self.transcript.lines()),
+ "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.
+ "has_resume": self.resume is not None,
}
+ def to_snapshot(self) -> resume_store.SnapshotTerminal:
+ """This pane as the resume store remembers it."""
+ return resume_store.SnapshotTerminal(
+ key=self.key,
+ name=self.name,
+ agent=self.agent,
+ column=self.column,
+ slot=self.slot,
+ resume=self.resume,
+ prompts_sent=self.prompts_sent,
+ )
+
@dataclass(slots=True)
class Session:
@@ -352,6 +396,9 @@ class Registry:
# without a real pseudo-terminal (and without a coding agent installed).
self._pty: PtyManager | None = pty_manager
self._lock = asyncio.Lock()
+ # Background session-id lookups. Held so the loop cannot garbage-collect
+ # a task mid-flight, and cancelled when the workspace closes.
+ self._lookups: set[asyncio.Task[None]] = set()
# ---------------------------------------------------------------- state
@property
@@ -421,7 +468,9 @@ class Registry:
)
# Close a previous session before replacing it, or its PTYs leak.
- await self._close_locked()
+ # It is replaced, not abandoned, so its resume offer stays until
+ # this workspace writes its own a moment from now.
+ await self._close_locked(forget=False)
pool = default_names(len(requested))
used: set[str] = set()
@@ -448,56 +497,178 @@ class Registry:
)
)
- profile = await asyncio.to_thread(probe_project, root)
+ session = await self._open_locked(root, terminals)
+ logger.info(
+ "Agentic IDE session started: {} terminals in {}",
+ len(terminals),
+ root,
+ )
+ return session
- # Pre-seed agent trust for this folder so no terminal stops on a
- # "do you trust this directory?" dialog the user cannot see coming.
- try:
- from jarvis.workspace.trust import ensure_trusted
+ async def _open_locked(self, root: Path, terminals: list[Terminal]) -> Session:
+ """Turn a prepared list of panes into THE open session.
- await asyncio.to_thread(
- ensure_trusted, root, sorted({t.agent for t in terminals})
- )
- except Exception as exc: # noqa: BLE001 - trust is a convenience
- logger.warning("Agentic IDE: pre-trust failed: {}", exc)
-
- session = Session(
- id=f"ide_{uuid4().hex[:12]}",
- folder=str(root),
- profile=profile,
- terminals=terminals,
- created_at=time.time(),
+ Shared by ``start`` and ``restore`` on purpose. Everything a workspace
+ needs before its first pane connects lives here exactly once — the
+ project probe, the trust pre-seed, the codebase index — so a resumed
+ workspace can never quietly differ from a freshly opened one. Both
+ callers hold ``self._lock`` and have already closed any predecessor.
+ """
+ profile = await asyncio.to_thread(probe_project, root)
+
+ # Pre-seed agent trust for this folder so no terminal stops on a
+ # "do you trust this directory?" dialog the user cannot see coming.
+ try:
+ from jarvis.workspace.trust import ensure_trusted
+
+ await asyncio.to_thread(
+ ensure_trusted, root, sorted({t.agent for t in terminals})
)
- self._session = session
- # Start indexing the codebase NOW, in a background thread, so the
- # first spoken instruction can already point the agent at real files
- # (@path). Deliberately fire-and-forget: nothing waits for it, and a
- # workspace whose walk is still running just gets a prompt without
- # file references (AP-26 — no heavy work on an interactive path).
+ except Exception as exc: # noqa: BLE001 - trust is a convenience
+ logger.warning("Agentic IDE: pre-trust failed: {}", exc)
+
+ session = Session(
+ id=f"ide_{uuid4().hex[:12]}",
+ folder=str(root),
+ profile=profile,
+ terminals=terminals,
+ created_at=time.time(),
+ )
+ self._session = session
+ # Start indexing the codebase NOW, in a background thread, so the
+ # first spoken instruction can already point the agent at real files
+ # (@path). Deliberately fire-and-forget: nothing waits for it, and a
+ # workspace whose walk is still running just gets a prompt without
+ # file references (AP-26 — no heavy work on an interactive path).
+ try:
+ from . import file_index
+
+ file_index.prime_index(str(root))
+ except Exception as exc: # noqa: BLE001 - the index is a convenience
+ logger.warning("Agentic IDE: file index not primed: {}", exc)
+ await self._persist()
+ return session
+
+ async def restore(self, snapshot: resume_store.Snapshot) -> Session:
+ """Reopen the workspace a snapshot describes, without starting anything.
+
+ The panes come back with their call-signs, their coding CLIs, their grid
+ coordinates and their resume handles — and in ``pending``, because
+ spawning is not this method's job. The grid attaches its panes the way
+ it always does, and ``attach`` spends the handles. That keeps ONE place
+ where an agent is started; a second spawn path here would drift from it
+ the first time either changed.
+
+ A pane whose CLI is no longer installed is still restored. It shows up
+ as an error the moment it tries to connect, which is a far better
+ outcome than silently dropping a terminal the user expects to see.
+ """
+ async with self._lock:
+ if not snapshot.terminals:
+ raise SessionError("That workspace has no terminals to reopen.")
+
+ root = Path(snapshot.folder).expanduser() # noqa: ASYNC240
try:
- from . import file_index
+ if not await asyncio.to_thread(root.is_dir):
+ raise SessionError(
+ f"{root} is no longer on this machine — that workspace "
+ "cannot be reopened."
+ )
+ except OSError as exc:
+ raise SessionError(f"Cannot open {root}: {exc}") from exc
- file_index.prime_index(str(root))
- except Exception as exc: # noqa: BLE001 - the index is a convenience
- logger.warning("Agentic IDE: file index not primed: {}", exc)
+ await self._close_locked(forget=False)
+
+ terminals = [
+ Terminal(
+ key=entry.key or normalize(entry.name) or f"t{index}",
+ name=entry.name,
+ agent=entry.agent,
+ display_name=AGENT_DISPLAY.get(entry.agent, entry.agent),
+ index=index,
+ column=entry.column,
+ slot=entry.slot,
+ resume=entry.resume,
+ prompts_sent=entry.prompts_sent,
+ )
+ for index, entry in enumerate(snapshot.terminals)
+ ]
+ session = await self._open_locked(root, terminals)
+ # Pack the grid: a snapshot can carry gaps if it was written between
+ # a close and its renumbering, and a gap renders as a blank stripe.
+ self._renumber(session)
+ await self._persist()
logger.info(
- "Agentic IDE session started: {} terminals in {}",
+ "Agentic IDE session resumed: {} terminals in {} ({} with a "
+ "conversation to continue)",
len(terminals),
root,
+ sum(1 for t in terminals if t.resume is not None),
)
return session
async def end(self) -> bool:
async with self._lock:
existed = self._session is not None
- await self._close_locked()
+ await self._close_locked(forget=True)
return existed
- async def _close_locked(self) -> None:
+ # ------------------------------------------------------------- snapshot
+ def snapshot(self) -> resume_store.Snapshot | None:
+ """The open workspace in the form the resume store keeps it, or None."""
+ session = self._session
+ if session is None:
+ return None
+ return resume_store.snapshot_now(
+ session_id=session.id,
+ folder=session.folder,
+ terminals=[t.to_snapshot() for t in session.terminals],
+ )
+
+ async def _persist(self) -> None:
+ """Record the workspace so it can be offered back later.
+
+ Best-effort and off the event loop. A resume point is a convenience;
+ failing to write one must never break the workspace that is running
+ perfectly well right now.
+ """
+ snapshot = self.snapshot()
+ if snapshot is None:
+ return
+ try:
+ await asyncio.to_thread(resume_store.save, snapshot)
+ except Exception as exc: # noqa: BLE001 - the workspace comes first
+ logger.warning("Agentic IDE: resume snapshot not written: {}", exc)
+
+ async def _forget(self) -> None:
+ """Withdraw the resume offer, best-effort."""
+ try:
+ await asyncio.to_thread(resume_store.clear)
+ except Exception as exc: # noqa: BLE001 - closing must always succeed
+ logger.warning("Agentic IDE: resume snapshot not cleared: {}", exc)
+
+ async def _close_locked(self, *, forget: bool) -> None:
+ """Tear the workspace down. ``forget`` also withdraws the resume offer.
+
+ The two callers want opposite things. Ending a session is the user
+ saying "I am done", so the offer goes with it — re-offering something
+ somebody deliberately closed is the kind of prompt people learn to click
+ away. Replacing a session (opening or resuming another workspace) must
+ NOT withdraw anything: the new workspace writes its own snapshot a
+ moment later, and clearing in between would lose the offer if that write
+ never happened.
+ """
+ for task in list(self._lookups):
+ task.cancel()
+ self._lookups.clear()
session = self._session
self._session = None
if session is None:
+ if forget:
+ await self._forget()
return
+ if forget:
+ await self._forget()
manager = self._pty
if manager is not None:
for term in session.terminals:
@@ -538,6 +709,21 @@ class Registry:
``on_output(text)`` / ``on_exit(code)`` are awaited in this loop. The
transcript is fed here, so it keeps filling even if the UI pane is
closed and reconnects later.
+
+ **This is also where a conversation is continued rather than restarted.**
+ A pane holding a resume handle launches its CLI with the arguments that
+ reopen that conversation; a pane without one starts fresh and keeps
+ whatever handle the launch minted. Putting it here rather than in a
+ dedicated "resume" path is deliberate — every way a pane can come back
+ (reopening the browser, restoring a snapshot, pressing restart on a dead
+ pane) already goes through this one method, so all three continue the
+ conversation and none of them can drift from the others.
+
+ A resume can fail: the CLI may have pruned that conversation, or it may
+ never have had a first message. The agent then prints an error and dies
+ within a second, so an early non-zero exit after a resume drops the
+ handle and starts the pane fresh — once. The pane comes back empty
+ instead of dead, and ``resumed`` says which of the two happened.
"""
session = self._session
if session is None:
@@ -559,7 +745,22 @@ class Registry:
term.error = f"{term.display_name} is not on PATH."
raise SessionError(term.error)
+ continuing = resume_argv(term.agent, term.resume)
+ if continuing is not None:
+ argv = (*argv, *continuing)
+ term.resumed = True
+ else:
+ extra, minted = launch_extra(term.agent)
+ argv = (*argv, *extra)
+ term.resumed = False
+ if minted is not None:
+ term.resume = minted
+
term.transcript.resize(cols, rows)
+ # Monotonic: a wall clock can jump (NTP, a laptop waking up) and would
+ # then mis-measure how long the agent survived.
+ spawned_at = time.monotonic()
+ recovered = False
async def _output(_tid: str, text: str) -> None:
term.transcript.feed(text)
@@ -567,9 +768,34 @@ class Registry:
await on_output(text)
async def _closed(_tid: str, code: int) -> None:
+ nonlocal recovered
+ term.pty_id = None
+ died_young = time.monotonic() - spawned_at < RESUME_FAILED_WINDOW_S
+ # Only a FAILED early exit is blamed on the resume. Quitting an
+ # agent normally exits 0, and restarting a pane the user just closed
+ # would be its own bug.
+ if term.resumed and not recovered and died_young and code != 0:
+ recovered = True
+ logger.warning(
+ "Agentic IDE: {} could not continue its previous "
+ "conversation (exit {}) — starting it fresh instead",
+ term.name,
+ code,
+ )
+ term.resume = None
+ term.resumed = False
+ try:
+ await self.attach(key, cols, rows, on_output, on_exit)
+ except SessionError as exc:
+ logger.warning(
+ "Agentic IDE: {} could not be restarted: {}", term.name, exc
+ )
+ else:
+ # The pane is alive again; telling the viewer it exited
+ # would flash a dead pane for no reason.
+ return
term.status = "exited"
term.exit_code = code
- term.pty_id = None
await on_exit(code)
try:
@@ -593,8 +819,55 @@ class Registry:
term.exit_code = None
term.started_at = time.time()
term.last_output_at = time.time()
+ if term.resume is None and can_resume(term.agent):
+ # A CLI that cannot be told its session id (Codex): find out which
+ # one it just created, shortly from now.
+ self._schedule_lookup(term, session.folder, term.started_at)
+ await self._persist()
return term
+ def _schedule_lookup(self, term: Terminal, folder: str, started_at: float) -> None:
+ """Find a pane's session id a moment after its CLI created it.
+
+ Fire-and-forget, and deliberately not awaited by ``attach``: the pane is
+ already usable, and making the user wait for a filesystem scan to learn
+ something only needed after a restart would be the wrong trade.
+ """
+
+ async def _look() -> None:
+ try:
+ for delay in DISCOVERY_DELAYS_S:
+ await asyncio.sleep(delay)
+ session = self._session
+ if session is None or term not in session.terminals:
+ return # the pane (or the workspace) is gone
+ if term.resume is not None:
+ return
+ taken = {
+ other.resume.id
+ for other in session.terminals
+ if other.resume is not None
+ }
+ found = await asyncio.to_thread(
+ discover, term.agent, folder, started_at, taken
+ )
+ if found is None:
+ continue
+ term.resume = found
+ logger.debug(
+ "Agentic IDE: {} is conversation {}", term.name, found.id
+ )
+ await self._persist()
+ return
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001 - a convenience, never fatal
+ logger.debug("Agentic IDE: session lookup for {} failed: {}", term.name, exc)
+
+ task = asyncio.ensure_future(_look())
+ self._lookups.add(task)
+ task.add_done_callback(self._lookups.discard)
+
def write(self, key: str, data: str) -> bool:
"""Raw keystrokes from the pane's own xterm (not the injection path)."""
session = self._session
@@ -720,6 +993,7 @@ class Registry:
)
session.terminals.append(term)
self._renumber(session)
+ await self._persist()
logger.info(
"Agentic IDE: added terminal {} ({}) {} of {}",
term.name,
@@ -787,6 +1061,7 @@ class Registry:
term.status = "exited"
session.terminals.remove(term)
self._renumber(session)
+ await self._persist()
logger.info("Agentic IDE: closed terminal {}", term.name)
return term
diff --git a/tests/unit/agentic_ide/conftest.py b/tests/unit/agentic_ide/conftest.py
new file mode 100644
index 0000000000..d58809e9cc
--- /dev/null
+++ b/tests/unit/agentic_ide/conftest.py
@@ -0,0 +1,50 @@
+"""Shared safety net for the Agentic-IDE tests.
+
+Opening a workspace touches two things that live OUTSIDE the repository, and a
+test must reach neither of them. Both are redirected here for the whole package,
+whether or not an individual test knows they exist — a per-test opt-in is a
+guarantee that only holds until somebody writes the next test.
+
+1. **The resume snapshot.** Every workspace change now records one. Left
+ unredirected, a test would write into the developer's real data directory and
+ leave the app offering to reopen a workspace that pytest invented in a
+ temporary folder.
+2. **The trust pre-seed.** Opening a workspace marks its folder as trusted in
+ Claude Code's and Codex's own config files so no pane stops on a "do you
+ trust this directory?" dialog. Against a real home that means every test run
+ permanently added its throwaway folders to the developer's CLI configs. That
+ is not hypothetical: it is why one such config had grown to 71 KB of dead
+ entries, which the trust check then had to parse before every workspace open.
+ The trust logic itself is covered where it belongs, in
+ ``tests/unit/workspace/test_trust.py``, against a temporary home.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.agentic_ide import resume_store
+
+
[email protected](autouse=True)
+def _resume_store_in_tmp(
+ tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch
+) -> Path:
+ """Point the resume snapshot at a throwaway file for the duration of a test."""
+ target = tmp_path_factory.mktemp("resume") / "last_session.json"
+ monkeypatch.setattr(resume_store, "_store_path", lambda: target)
+ return target
+
+
[email protected](autouse=True)
+def _never_touch_real_agent_configs(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Keep the trust pre-seed away from the developer's own CLI configuration."""
+ from jarvis.workspace import trust
+
+ def _skip(*_args: Any, **_kwargs: Any) -> list[trust.TrustResult]:
+ return []
+
+ monkeypatch.setattr(trust, "ensure_trusted", _skip)
diff --git a/tests/unit/agentic_ide/test_agent_sessions.py b/tests/unit/agentic_ide/test_agent_sessions.py
index ec9db05796..0caf7b329f 100644
--- a/tests/unit/agentic_ide/test_agent_sessions.py
+++ b/tests/unit/agentic_ide/test_agent_sessions.py
@@ -275,9 +275,9 @@ def test_discovery_without_a_home_directory_returns_nothing(
assert sessions.discover("codex", str(tmp_path), 0.0) is None
-def test_claude_needs_no_discovery() -> None:
+def test_claude_needs_no_discovery(tmp_path: Path) -> None:
"""It was told its id at launch, so there is nothing to look for."""
- assert sessions.discover("claude", "/tmp", 0.0) is None
+ assert sessions.discover("claude", str(tmp_path), 0.0) is None
# ------------------------------------------------------------------ storage
diff --git a/tests/unit/agentic_ide/test_resume_session.py b/tests/unit/agentic_ide/test_resume_session.py
new file mode 100644
index 0000000000..782fec3bc9
--- /dev/null
+++ b/tests/unit/agentic_ide/test_resume_session.py
@@ -0,0 +1,398 @@
+"""Resuming a workspace: the registry side.
+
+The contract these pin down is that ``attach`` is the ONLY place an agent is
+started, and therefore the only place that has to know about continuing a
+conversation. Every way a pane can come back — reopening the browser, restoring
+a snapshot, restarting a dead pane — goes through it, so all three behave the
+same and none of them can drift.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import resume_store
+from jarvis.agentic_ide import session as ide
+from jarvis.agentic_ide.agent_sessions import ResumeHandle
+from tests.fakes.fake_pty_manager import FakePtyManager
+
+
+def fake_pty() -> FakePtyManager:
+ return FakePtyManager()
+
+
+def registry(
+ fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch
+) -> ide.Registry:
+ monkeypatch.setattr(ide, "agent_argv", lambda name: (f"/usr/bin/{name}",))
+ return ide.Registry(pty_manager=fake_pty)
+
+
+async def _noop(_text: str) -> None:
+ return None
+
+
+async def _noop_exit(_code: int) -> None:
+ return None
+
+
+def _argv(fake_pty: FakePtyManager) -> tuple[str, ...]:
+ return fake_pty.spawns[-1]["argv"]
+
+
+# ------------------------------------------------------------------ minting
+async def test_a_fresh_pane_is_launched_with_an_id_it_can_be_found_by(
+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Mika"}])
+ await registry.attach("Mika", 80, 24, _noop, _noop_exit)
+
+ term = registry.session.find("Mika")
+ assert term.resume is not None and term.resume.kind == "claude_session"
+ # The id went to the CLI, which is what makes the conversation findable.
+ argv = _argv(fake_pty)
+ assert "--session-id" in argv and term.resume.id in argv
+ # A first start is not a resume, and must not be reported as one.
+ assert term.resumed is False
+
+
+async def test_a_pane_with_a_handle_continues_instead_of_starting_over(
+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> 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
+ )
+
+ await registry.attach("Mika", 80, 24, _noop, _noop_exit)
+ assert _argv(fake_pty)[-2:] == ("--resume", "known-id")
+ assert registry.session.find("Mika").resumed is True
+
+
+async def test_reopening_a_pane_keeps_the_same_conversation(
+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> 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").resume
+ assert minted is not None
+
+ registry.detach("Mika") # the viewer went away, the agent was stopped
+ await registry.attach("Mika", 80, 24, _noop, _noop_exit)
+
+ assert _argv(fake_pty)[-2:] == ("--resume", minted.id)
+ assert registry.session.find("Mika").resumed is True
+
+
+async def test_a_pane_running_a_cli_that_cannot_resume_just_starts(
+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """A coding CLI added later must degrade, never break the pane."""
+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Mika"}])
+ term = registry.session.find("Mika")
+ term.agent = "some-future-cli"
+
+ await registry.attach("Mika", 80, 24, _noop, _noop_exit)
+ assert _argv(fake_pty) == ("/usr/bin/some-future-cli",)
+ assert registry.session.find("Mika").resume is None
+ assert registry.session.find("Mika").resumed is False
+
+
+# ------------------------------------------------------------- self-healing
+async def test_a_dead_conversation_falls_back_to_a_fresh_agent(
+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """A conversation the CLI has pruned must not leave a dead pane behind."""
+ 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)
+
+ exits: list[int] = []
+
+ async def _record_exit(code: int) -> None:
+ exits.append(code)
+
+ await registry.attach("Mika", 80, 24, _noop, _record_exit)
+ # The CLI printed "no such conversation" and died right away.
+ await fake_pty.spawns[-1]["on_closed"]("fake-pty-1", 1)
+
+ argv = _argv(fake_pty)
+ assert "--resume" not in argv, "a stale handle must not be spent twice"
+ assert registry.session.find("Mika").resumed is False
+ assert registry.session.find("Mika").status == "live"
+ # The viewer was never told the pane died — it did not, it restarted.
+ assert exits == []
+
+
+async def test_a_clean_exit_after_a_resume_is_not_second_guessed(
+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> 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)
+
+ exits: list[int] = []
+
+ async def _record_exit(code: int) -> None:
+ exits.append(code)
+
+ await registry.attach("Mika", 80, 24, _noop, _record_exit)
+ await fake_pty.spawns[-1]["on_closed"]("fake-pty-1", 0)
+
+ assert exits == [0]
+ assert registry.session.find("Mika").status == "exited"
+
+
+async def test_a_late_crash_is_reported_as_a_crash(
+ registry: ide.Registry,
+ fake_pty: FakePtyManager,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> 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)
+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Mika"}])
+ registry.session.find("Mika").resume = ResumeHandle(
+ kind="claude_session", id="fine", captured_at=1.0
+ )
+
+ exits: list[int] = []
+
+ async def _record_exit(code: int) -> None:
+ exits.append(code)
+
+ await registry.attach("Mika", 80, 24, _noop, _record_exit)
+ await fake_pty.spawns[-1]["on_closed"]("fake-pty-1", 3)
+
+ assert exits == [3]
+ assert registry.session.find("Mika").status == "exited"
+
+
+# ------------------------------------------------------------------ restore
+def _snapshot(folder: Path) -> resume_store.Snapshot:
+ return resume_store.Snapshot(
+ session_id="ide_old",
+ folder=str(folder),
+ saved_at=1.0,
+ terminals=[
+ resume_store.SnapshotTerminal(
+ key="kai",
+ name="Kai",
+ agent="claude",
+ column=1,
+ slot=1,
+ resume=ResumeHandle(
+ kind="claude_session", id="kai-conv", captured_at=1.0
+ ),
+ prompts_sent=2,
+ ),
+ resume_store.SnapshotTerminal(
+ key="mika", name="Mika", agent="claude", column=0, slot=0
+ ),
+ ],
+ )
+
+
+async def test_restore_rebuilds_titles_agents_and_positions(
+ registry: ide.Registry, tmp_path: Path
+) -> None:
+ restored = await registry.restore(_snapshot(tmp_path))
+
+ # Reading order, not snapshot order: left to right, top to bottom.
+ assert [t.name for t in restored.terminals] == ["Mika", "Kai"]
+ assert [(t.column, t.slot) for t in restored.terminals] == [(0, 0), (1, 0)]
+ assert [t.agent for t in restored.terminals] == ["claude", "claude"]
+ assert restored.folder == str(tmp_path)
+ assert restored.find("Kai").resume.id == "kai-conv"
+ assert restored.find("Kai").prompts_sent == 2
+
+
+async def test_restore_starts_nothing_by_itself(
+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """The grid attaches its panes as it always does — one spawn path only."""
+ restored = await registry.restore(_snapshot(tmp_path))
+ assert all(t.status == "pending" for t in restored.terminals)
+ assert fake_pty.spawns == []
+
+
+async def test_a_restored_pane_continues_its_conversation_when_it_connects(
+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ await registry.restore(_snapshot(tmp_path))
+ await registry.attach("Kai", 80, 24, _noop, _noop_exit)
+ assert _argv(fake_pty)[-2:] == ("--resume", "kai-conv")
+
+ await registry.attach("Mika", 80, 24, _noop, _noop_exit)
+ # Mika never had one, so it starts fresh — and says so.
+ assert "--resume" not in _argv(fake_pty)
+ assert registry.session.find("Mika").resumed is False
+
+
+async def test_restore_refuses_a_folder_that_is_gone(
+ registry: ide.Registry, tmp_path: Path
+) -> None:
+ with pytest.raises(ide.SessionError, match="no longer"):
+ await registry.restore(_snapshot(tmp_path / "deleted"))
+
+
+async def test_restore_refuses_an_empty_workspace(
+ registry: ide.Registry, tmp_path: Path
+) -> None:
+ empty = resume_store.Snapshot(
+ session_id="ide_old", folder=str(tmp_path), saved_at=1.0, terminals=[]
+ )
+ with pytest.raises(ide.SessionError):
+ await registry.restore(empty)
+
+
+async def test_restore_replaces_a_running_workspace_cleanly(
+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Old"}])
+ await registry.attach("Old", 80, 24, _noop, _noop_exit)
+ live = registry.session.find("Old").pty_id
+
+ await registry.restore(_snapshot(tmp_path))
+ assert live in fake_pty.closed, "the previous workspace's agent must be stopped"
+ assert [t.name for t in registry.session.terminals] == ["Mika", "Kai"]
+
+
+# ---------------------------------------------------------------- snapshots
+async def test_opening_a_workspace_makes_it_resumable(
+ registry: ide.Registry, tmp_path: Path
+) -> None:
+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Mika"}])
+ saved = resume_store.load()
+ assert saved is not None
+ assert [t.name for t in saved.terminals] == ["Mika"]
+ assert saved.folder == str(tmp_path)
+
+
+async def test_the_conversation_id_reaches_the_snapshot(
+ registry: ide.Registry, tmp_path: Path
+) -> None:
+ """Without this the layout would come back and the conversations would not."""
+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Mika"}])
+ await registry.attach("Mika", 80, 24, _noop, _noop_exit)
+
+ saved = resume_store.load()
+ assert saved is not None and saved.terminals[0].resume is not None
+ assert saved.terminals[0].resume.id == registry.session.find("Mika").resume.id
+
+
+async def test_splitting_and_closing_keep_the_offer_current(
+ registry: ide.Registry, tmp_path: Path
+) -> None:
+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Mika"}])
+ await registry.add_terminal(anchor="Mika", direction="right", name="Nova")
+ saved = resume_store.load()
+ assert saved is not None and [t.name for t in saved.terminals] == ["Mika", "Nova"]
+
+ await registry.close_terminal("Nova")
+ saved = resume_store.load()
+ assert saved is not None and [t.name for t in saved.terminals] == ["Mika"]
+
+
+async def test_closing_the_workspace_deliberately_withdraws_the_offer(
+ registry: ide.Registry, tmp_path: Path
+) -> None:
+ """An explicit close means "I am done" — re-offering it would be noise."""
+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Mika"}])
+ assert resume_store.load() is not None
+
+ await registry.end()
+ assert resume_store.load() is None
+
+
+async def test_opening_another_workspace_does_not_leave_a_gap(
+ registry: ide.Registry, tmp_path: Path
+) -> None:
+ """Replacing a workspace must always leave SOMETHING resumable behind."""
+ first = tmp_path / "first"
+ second = tmp_path / "second"
+ first.mkdir()
+ second.mkdir()
+ await registry.start(str(first), [{"agent": "claude", "name": "Mika"}])
+ await registry.start(str(second), [{"agent": "claude", "name": "Nova"}])
+
+ saved = resume_store.load()
+ assert saved is not None and saved.folder == str(second)
+
+
+async def test_a_broken_snapshot_write_never_breaks_the_workspace(
+ registry: ide.Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ def _boom(_snapshot: object) -> None:
+ raise OSError("disk full")
+
+ monkeypatch.setattr(resume_store, "save", _boom)
+ workspace = await registry.start(
+ str(tmp_path), [{"agent": "claude", "name": "Mika"}]
+ )
+ assert [t.name for t in workspace.terminals] == ["Mika"]
+
+
+# ------------------------------------------------------------------ lookups
+async def test_a_cli_that_cannot_be_told_its_id_gets_looked_up(
+ registry: ide.Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Codex writes its session file after launching, so we ask a moment later."""
+ monkeypatch.setattr(ide, "DISCOVERY_DELAYS_S", (0.0,))
+ found = ResumeHandle(kind="codex_rollout", id="found-it", captured_at=2.0)
+ monkeypatch.setattr(ide, "discover", lambda *_args, **_kw: found)
+
+ await registry.start(str(tmp_path), [{"agent": "codex", "name": "Cody"}])
+ # Nothing is known at launch — Codex chooses the id, and only afterwards.
+ await registry.attach("Cody", 80, 24, _noop, _noop_exit)
+ assert "resume" not in " ".join(registry._pty.spawns[-1]["argv"])
+
+ await asyncio.sleep(0.05)
+ assert registry.session.find("Cody").resume == found
+ saved = resume_store.load()
+ assert saved is not None and saved.terminals[0].resume == found
+
+
+async def test_a_lookup_offers_the_ids_other_panes_already_hold(
+ registry: ide.Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Otherwise two Codex panes in one folder would share a conversation."""
+ monkeypatch.setattr(ide, "DISCOVERY_DELAYS_S", (0.0,))
+ seen: list[set[str]] = []
+
+ def _spy(_agent: str, _cwd: str, _started: float, taken: set[str]):
+ seen.append(set(taken))
+ return None
+
+ monkeypatch.setattr(ide, "discover", _spy)
+ await registry.start(str(tmp_path), [{"agent": "codex", "name": "Cody"}])
+ registry.session.terminals[0].resume = None
+ await registry.add_terminal(name="Dana", agent="codex")
+ registry.session.find("Cody").resume = ResumeHandle(
+ kind="codex_rollout", id="cody-conv", captured_at=1.0
+ )
+
+ await registry.attach("Dana", 80, 24, _noop, _noop_exit)
+ await asyncio.sleep(0.05)
+ assert seen and "cody-conv" in seen[-1]
+
+
+async def test_closing_the_workspace_stops_pending_lookups(
+ registry: ide.Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A lookup outliving its workspace would write a snapshot for a ghost."""
+ monkeypatch.setattr(ide, "DISCOVERY_DELAYS_S", (5.0,))
+ await registry.start(str(tmp_path), [{"agent": "codex", "name": "Cody"}])
+ await registry.attach("Cody", 80, 24, _noop, _noop_exit)
+ assert registry._lookups
+
+ await registry.end()
+ assert not registry._lookups
diff --git a/tests/unit/agentic_ide/test_resume_store.py b/tests/unit/agentic_ide/test_resume_store.py
index b63b5a75bc..ad12f41237 100644
--- a/tests/unit/agentic_ide/test_resume_store.py
+++ b/tests/unit/agentic_ide/test_resume_store.py
@@ -11,18 +11,11 @@ from __future__ import annotations
from pathlib import Path
-import pytest
-
from jarvis.agentic_ide import resume_store
from jarvis.agentic_ide.agent_sessions import ResumeHandle
-
[email protected](autouse=True)
-def _isolated_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- """Never touch the real per-user data directory from a test."""
- monkeypatch.setattr(
- resume_store, "_store_path", lambda: tmp_path / "store" / "last_session.json"
- )
+# The store itself is redirected to a throwaway file by the package conftest,
+# so nothing here can reach the developer's real data directory.
def _snapshot(folder: str) -> resume_store.Snapshot: