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.

fix(agentic-ide): a new workspace no longer erases the folders you closed

Ruben Lütkeab40239f8dfa
diff --git a/jarvis/agentic_ide/resume_store.py b/jarvis/agentic_ide/resume_store.py
index 62f4d3da26..ccaefdf1fa 100644
--- a/jarvis/agentic_ide/resume_store.py
+++ b/jarvis/agentic_ide/resume_store.py
@@ -136,12 +136,17 @@ class SnapshotWorkspace:
# Custom tab label. Empty for snapshots written before renaming existed.
name: str = ""
terminals: list[SnapshotTerminal] = field(default_factory=list)
+ # When this workspace was last recorded. Its own stamp rather than the
+ # file's, because the file holds workspaces that closed at different times
+ # and the merge in `save` has to know which record is the newer one.
+ saved_at: float = 0.0
def to_dict(self) -> dict[str, Any]:
return {
"session_id": self.session_id,
"folder": self.folder,
"name": self.name,
+ "saved_at": self.saved_at,
"terminals": [t.to_dict() for t in self.terminals],
}
@@ -163,11 +168,16 @@ class SnapshotWorkspace:
if not terminals:
# A workspace with no panes is not an offer, it is an empty screen.
return None
+ try:
+ saved_at = float(data.get("saved_at") or 0.0)
+ except (TypeError, ValueError):
+ saved_at = 0.0
return SnapshotWorkspace(
session_id=str(data.get("session_id") or ""),
folder=folder,
name=str(data.get("name") or "").strip(),
terminals=terminals,
+ saved_at=saved_at,
)
@@ -188,6 +198,11 @@ class Snapshot:
saved_at: float
workspaces: list[SnapshotWorkspace] = field(default_factory=list)
+ # Which workspace was on screen, by its id at the time. Recorded rather than
+ # implied by position, because the list is in TAB order — the bar must come
+ # back in the arrangement it had, and the tab you were working in is not
+ # necessarily the first one.
+ active_session_id: str = ""
@property
def terminal_count(self) -> int:
@@ -197,6 +212,7 @@ class Snapshot:
return {
"version": SCHEMA_VERSION,
"saved_at": self.saved_at,
+ "active_session_id": self.active_session_id,
"workspaces": [w.to_dict() for w in self.workspaces],
}
@@ -238,7 +254,11 @@ class Snapshot:
saved_at = float(data.get("saved_at") or 0.0)
except (TypeError, ValueError):
saved_at = 0.0
- return Snapshot(saved_at=saved_at, workspaces=workspaces)
+ return Snapshot(
+ saved_at=saved_at,
+ workspaces=workspaces,
+ active_session_id=str(data.get("active_session_id") or ""),
+ )
def _as_int(value: Any) -> int:
@@ -276,6 +296,7 @@ def save(snapshot: Snapshot) -> None:
clear()
return
target = _store_path()
+ snapshot = _merged_with_stored(snapshot)
tmp = target.with_name(f"{target.name}.tmp-{os.getpid()}-{uuid4().hex[:8]}")
with _WRITE_LOCK:
try:
@@ -291,6 +312,73 @@ def save(snapshot: Snapshot) -> None:
pass
+# How many workspaces one restore point may remember. Above the number that can
+# be open at once, so folders you closed earlier survive alongside what is open
+# now — and bounded, so the offer stays a screen rather than an archive.
+MAX_REMEMBERED_WORKSPACES = 10
+
+
+def _merged_with_stored(snapshot: Snapshot) -> Snapshot:
+ """Fold the live workspaces into what is already remembered, keyed by folder.
+
+ **The failure this exists for.** A save used to replace the file outright, so
+ the restore point only ever held what happened to be open at that moment.
+ Work twelve panes in one folder, close them, then open a single pane
+ somewhere to check one thing — and the twelve were gone for good, with no way
+ to notice until the offer came back holding one pane. Reported as "it only
+ resumed one".
+
+ So a save UPDATES rather than replaces: a folder that is open now overwrites
+ its own record (the newest arrangement of that folder is the truth), and
+ every other remembered folder is left exactly as it was. Only the user
+ asking to start fresh throws any of it away.
+
+ Ordered newest-first and trimmed, so the file cannot grow without limit and
+ the offer leads with what was most recently worked in.
+ """
+ stamped = [
+ w if w.saved_at else _restamp(w, snapshot.saved_at) for w in snapshot.workspaces
+ ]
+ live_folders = {_folder_key(w.folder) for w in stamped}
+ try:
+ stored = load()
+ except Exception: # noqa: BLE001 - a broken file must not block the write
+ stored = None
+ kept = (
+ [w for w in stored.workspaces if _folder_key(w.folder) not in live_folders]
+ if stored is not None
+ else []
+ )
+ # The open ones keep the bar's order — that arrangement is what comes back.
+ # Folders remembered from earlier follow, most recently used first, and the
+ # trim falls on the oldest of those rather than on anything open now.
+ kept.sort(key=lambda w: w.saved_at, reverse=True)
+ merged = [*stamped, *kept][:MAX_REMEMBERED_WORKSPACES]
+ return Snapshot(
+ saved_at=snapshot.saved_at,
+ workspaces=merged,
+ active_session_id=snapshot.active_session_id,
+ )
+
+
+def _restamp(workspace: SnapshotWorkspace, when: float) -> SnapshotWorkspace:
+ return SnapshotWorkspace(
+ session_id=workspace.session_id,
+ folder=workspace.folder,
+ name=workspace.name,
+ terminals=workspace.terminals,
+ saved_at=when,
+ )
+
+
+def _folder_key(folder: str) -> str:
+ """Comparable form of a folder path — the same one twice must not be two."""
+ try:
+ return os.path.normcase(str(Path(folder).expanduser().resolve()))
+ except OSError:
+ return os.path.normcase(folder)
+
+
def load() -> Snapshot | None:
"""The stored workspace, or None when there is nothing usable to offer."""
path = _store_path()
@@ -418,12 +506,20 @@ def _display_names() -> dict[str, str]:
return {}
-def snapshot_now(workspaces: list[SnapshotWorkspace]) -> Snapshot:
+def snapshot_now(
+ workspaces: list[SnapshotWorkspace], *, active_session_id: str = ""
+) -> Snapshot:
"""A snapshot of every open workspace, stamped with the current time."""
- return Snapshot(saved_at=time.time(), workspaces=list(workspaces))
+ now = time.time()
+ return Snapshot(
+ saved_at=now,
+ workspaces=[_restamp(w, now) for w in workspaces],
+ active_session_id=active_session_id,
+ )
__all__ = [
+ "MAX_REMEMBERED_WORKSPACES",
"SCHEMA_VERSION",
"Snapshot",
"SnapshotTerminal",
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index dc8af69756..6b9a6df92b 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -612,6 +612,9 @@ class Registry:
# without a real pseudo-terminal (and without a coding agent installed).
self._pty: PtyManager | None = pty_manager
self._lock = asyncio.Lock()
+ # Held across reading the state AND writing it — see `_persist` for the
+ # interleaving that otherwise loses a freshly discovered conversation id.
+ self._persist_lock = asyncio.Lock()
# ---------------------------------------------------------------- state
@property
@@ -885,23 +888,30 @@ class Registry:
restored: list[Session] = []
skipped: list[tuple[str, str]] = []
+ was_on_screen: Session | None = None
for space in snapshot.workspaces:
try:
session = await self._restore_one_locked(space)
except SessionError as exc:
skipped.append((space.folder, str(exc)))
continue
- if session is not None:
- restored.append(session)
+ if session is None:
+ continue
+ restored.append(session)
+ if space.session_id and space.session_id == snapshot.active_session_id:
+ was_on_screen = session
if not restored and skipped:
# Nothing at all came back: that is a failure the caller must be
# able to report as one, not a success with an empty list.
raise SessionError(skipped[0][1])
- # The first workspace in the snapshot was the one on screen.
+ # Back to the tab that was being worked in, not simply the leftmost
+ # one. Falls back to the first when the snapshot predates recording
+ # it, or when that workspace was one of the ones that could not come
+ # back.
if restored:
- self._focus_locked(restored[0])
+ self._focus_locked(was_on_screen or restored[0])
await self._persist()
logger.info(
"Agentic IDE resumed {} workspace(s), {} terminal(s); {} skipped",
@@ -1066,8 +1076,10 @@ class Registry:
"""
if not self._sessions:
return None
- front = self._active
- ordered = sorted(self._sessions.values(), key=lambda s: s.id != front)
+ # TAB ORDER, not front-first. The bar has to come back arranged the way
+ # it was left, and the tab somebody was working in is not necessarily the
+ # leftmost one — so which was on screen is recorded separately instead of
+ # being implied by position.
return resume_store.snapshot_now(
[
resume_store.SnapshotWorkspace(
@@ -1076,8 +1088,9 @@ class Registry:
name=session.name,
terminals=[t.to_snapshot() for t in session.terminals],
)
- for session in ordered
- ]
+ for session in self._sessions.values()
+ ],
+ active_session_id=self._active or "",
)
async def _persist(self) -> None:
@@ -1086,14 +1099,23 @@ class Registry:
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.
+
+ **Reading the state and writing it are one indivisible step.** Without
+ that they interleave, and the interleaving loses exactly the valuable
+ part: a pane connecting collects the state and then hands it to a thread,
+ and if the background lookup finds a Codex conversation id in that gap and
+ writes it, the older collected state lands afterwards and erases it.
+ Serialising build-and-write means a later save always reads a state newer
+ than the one the previous save stored.
"""
- 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 with self._persist_lock:
+ 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."""
diff --git a/tests/unit/agentic_ide/test_resume_session.py b/tests/unit/agentic_ide/test_resume_session.py
index 5aef3ef124..d41e677db1 100644
--- a/tests/unit/agentic_ide/test_resume_session.py
+++ b/tests/unit/agentic_ide/test_resume_session.py
@@ -545,21 +545,63 @@ async def test_closing_workspaces_one_by_one_keeps_all_of_them_on_offer(
assert {w.folder for w in saved.workspaces} == {str(f) for f in folders}
-async def test_opening_something_new_refreshes_what_is_on_offer(
+async def test_a_new_workspace_does_not_erase_the_folders_you_closed(
registry: ide.Registry, tmp_path: Path
) -> None:
- """The other side of that coin: the offer must not accumulate forever."""
- old, new = tmp_path / "old", tmp_path / "new"
- old.mkdir()
- new.mkdir()
- await registry.start(str(old), [{"agent": "claude", "name": "Alex"}])
+ """The reported loss, in miniature.
+
+ Work twelve panes in one folder, close them, then open a single pane
+ somewhere to check one thing — and the twelve used to be gone for good,
+ because a save replaced the file outright. A save UPDATES: the folder that is
+ open now overwrites its own record, every other remembered folder is left
+ alone.
+ """
+ big, quick = tmp_path / "big", tmp_path / "quick"
+ big.mkdir()
+ quick.mkdir()
+ await registry.start(
+ str(big), [{"agent": "claude"} for _ in range(12)]
+ )
await registry.end()
- await registry.start(str(new), [{"agent": "claude", "name": "Blake"}])
+ await registry.start(str(quick), [{"agent": "claude", "name": "Solo"}])
+
+ saved = resume_store.load()
+ assert saved is not None
+ folders = {w.folder: len(w.terminals) for w in saved.workspaces}
+ assert folders == {str(quick): 1, str(big): 12}
+
+
+async def test_reopening_the_same_folder_replaces_its_own_record(
+ registry: ide.Registry, tmp_path: Path
+) -> None:
+ """The newest arrangement of a folder is the truth about that folder."""
+ await registry.start(str(tmp_path), [{"agent": "claude"} for _ in range(5)])
+ await registry.end()
+
+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Solo"}])
+
+ saved = resume_store.load()
+ assert saved is not None
+ assert [len(w.terminals) for w in saved.workspaces] == [1]
+
+
+async def test_the_remembered_list_stays_bounded(
+ registry: ide.Registry, tmp_path: Path
+) -> None:
+ """A restore point is a screen, not an archive."""
+ for index in range(resume_store.MAX_REMEMBERED_WORKSPACES + 4):
+ folder = tmp_path / f"repo{index}"
+ folder.mkdir()
+ await registry.start(str(folder), [{"agent": "claude"}])
+ await registry.end()
saved = resume_store.load()
assert saved is not None
- assert [w.folder for w in saved.workspaces] == [str(new)]
+ assert len(saved.workspaces) == resume_store.MAX_REMEMBERED_WORKSPACES
+ # The newest survive; the oldest fall off.
+ assert any("repo13" in w.folder for w in saved.workspaces)
+ assert not any(w.folder.endswith("repo0") for w in saved.workspaces)
async def test_only_starting_fresh_discards_the_restore_point(
@@ -573,32 +615,36 @@ async def test_only_starting_fresh_discards_the_restore_point(
assert resume_store.load() is None
-async def test_every_open_workspace_is_remembered_front_one_first(
+async def test_every_open_workspace_is_remembered_in_tab_order(
registry: ide.Registry, tmp_path: Path
) -> None:
- """All of them, and the one on screen leads.
+ """All of them, arranged as the bar was, with the working tab named.
An earlier version stored only the front workspace, on the reasoning that
restoring all would relaunch a folder's worth of agents per tab. Restoring
- starts nothing, so the reasoning was wrong on both counts — and somebody
- with two folders open wants two back. Order still matters: the front one is
- first so it is the one on screen again afterwards.
+ starts nothing, so that was wrong on both counts — and somebody with two
+ folders open wants two back. The order is the BAR's, because that is the
+ arrangement that has to come back; which tab was being worked in is recorded
+ separately rather than implied by position.
"""
first = tmp_path / "first"
second = tmp_path / "second"
first.mkdir()
second.mkdir()
one = await registry.start(str(first), [{"agent": "claude", "name": "Alex"}])
- await registry.start(str(second), [{"agent": "claude", "name": "Blake"}])
+ two = await registry.start(str(second), [{"agent": "claude", "name": "Blake"}])
saved = resume_store.load()
assert saved is not None
- assert [w.folder for w in saved.workspaces] == [str(second), str(first)]
+ assert [w.folder for w in saved.workspaces] == [str(first), str(second)]
+ assert saved.active_session_id == two.id
+ # Working in the other tab must not renumber the bar.
await registry.activate(one.id)
saved = resume_store.load()
assert saved is not None
assert [w.folder for w in saved.workspaces] == [str(first), str(second)]
+ assert saved.active_session_id == one.id
async def test_closing_one_of_two_leaves_both_on_offer(
@@ -715,3 +761,34 @@ async def test_closing_one_workspace_leaves_the_others_lookups_alone(
assert not close_me.lookups
assert keep.lookups, "the surviving workspace must keep looking"
+
+
+async def test_a_discovered_conversation_id_is_not_overwritten_by_an_older_save(
+ registry: ide.Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The race that silently cost a Codex pane its conversation.
+
+ Saving reads the state and then writes it. A pane connecting starts that,
+ and the background lookup that finds a Codex conversation id can land its own
+ save in the gap — after which the connecting pane's older reading lands on
+ top and erases the id. It only ever showed up under a shuffled test order,
+ which is exactly how a race announces itself.
+
+ Build-and-write is one step now, so whatever is written last was read last.
+ """
+ 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"}])
+ # Attach and the lookup both persist; the order they finish in must not
+ # decide whether the id survives.
+ await registry.attach("Cody", 80, 24, _noop, _noop_exit)
+ for _ in range(20):
+ await asyncio.sleep(0.01)
+
+ assert registry.session.find("Cody").resume == found
+ saved = resume_store.load()
+ assert saved is not None
+ stored = saved.workspaces[0].terminals[0].resume
+ assert stored == found, "the discovered id must survive every other save"