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): keep the restore point after closing, and remember every workspace
Ruben Lütke547d4ad73834
diff --git a/jarvis/agentic_ide/resume_store.py b/jarvis/agentic_ide/resume_store.pyindex 067db1acee..62f4d3da26 100644--- a/jarvis/agentic_ide/resume_store.py+++ b/jarvis/agentic_ide/resume_store.py@@ -1,10 +1,9 @@-"""The one workspace an Agentic-IDE user can get back.+"""What an Agentic-IDE user can get back after everything went away.-``Registry`` holds the open workspace in process memory, which means it lasts-exactly as long as the process does. Close the browser and every agent is-stopped on purpose; restart the app and even the arrangement is gone. This-module is the thin layer that makes that recoverable: a small JSON file naming-the folder, every pane's call-sign, which coding CLI ran in it, where it sat in+``Registry`` holds its workspaces in process memory, which means they last+exactly as long as the process does. This module is the thin layer that makes+that recoverable: a small JSON file naming every workspace that was open, each+pane's call-sign, which coding CLI ran in it, on which account, where it sat inthe grid, and the handle that points back at its conversation.Same shape and the same discipline as ``recents.py``, which already proved the@@ -21,10 +20,12 @@ Two rules worth stating outright:against the machine as it is NOW, so the user is told which panes will reallycome back *before* clicking, instead of finding out by asking a resumed agenta follow-up question and getting a blank stare.-* **Closing a workspace deliberately withdraws it.** The offer is meant for the- cases nobody chose — a closed window, a restarted app, a reboot. Re-offering- something the user shut down on purpose is the kind of prompt people learn to- dismiss without reading, which would cost the offer its meaning.+* **Closing does NOT withdraw the offer.** An earlier version cleared the+ snapshot when the last workspace was closed, reasoning that re-proposing+ something somebody just shut down is noise. That was wrong, and the maintainer+ said so plainly: closing for the day and picking the same folders up tomorrow+ is the main thing this is FOR. The only thing that discards a restore point is+ the user asking for it ("Start fresh" / ``DELETE /resume``)."""from __future__ import annotations@@ -50,7 +51,7 @@ _WRITE_LOCK = threading.Lock()# Bumped whenever the stored shape changes incompatibly. An unknown version# reads as "nothing to resume": half-understanding a newer build's file would# reopen a workspace with pieces missing, which is worse than offering nothing.-SCHEMA_VERSION = 1+SCHEMA_VERSION = 2@dataclass(slots=True)@@ -127,29 +128,27 @@ def _account_home(agent: str, account_id: str | None) -> Path | None:@dataclass(slots=True)-class Snapshot:- """A workspace as it stood, ready to be offered back."""+class SnapshotWorkspace:+ """One remembered workspace: a folder and the panes that were in it."""session_id: strfolder: str- saved_at: float+ # Custom tab label. Empty for snapshots written before renaming existed.+ name: str = ""terminals: list[SnapshotTerminal] = field(default_factory=list)def to_dict(self) -> dict[str, Any]:return {- "version": SCHEMA_VERSION,"session_id": self.session_id,"folder": self.folder,- "saved_at": self.saved_at,+ "name": self.name,"terminals": [t.to_dict() for t in self.terminals],}@staticmethod- def from_dict(data: Any) -> Snapshot | None:+ def from_dict(data: Any) -> SnapshotWorkspace | None:if not isinstance(data, dict):return None- if _as_int(data.get("version")) != SCHEMA_VERSION:- return Nonefolder = str(data.get("folder") or "").strip()if not folder:return None@@ -164,18 +163,84 @@ class Snapshot: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 Snapshot(+ return SnapshotWorkspace(session_id=str(data.get("session_id") or ""),folder=folder,- saved_at=saved_at,+ name=str(data.get("name") or "").strip(),terminals=terminals,)+@dataclass(slots=True)+class Snapshot:+ """Everything that was open, ready to be offered back.++ All workspaces, not just whichever was on screen. The question this answers+ is "give me back what I had", and somebody running four folders side by side+ had four — handing back one and silently dropping three is the same kind of+ lie as promising a conversation that is not there.++ Restoring them all costs nothing on its own: a restored workspace starts no+ agent. Panes only launch when a pane connects, and only the workspace on+ screen has panes mounted, so five workspaces in the bar are five folders+ waiting, not five folders' worth of coding agents.+ """++ saved_at: float+ workspaces: list[SnapshotWorkspace] = field(default_factory=list)++ @property+ def terminal_count(self) -> int:+ return sum(len(w.terminals) for w in self.workspaces)++ def to_dict(self) -> dict[str, Any]:+ return {+ "version": SCHEMA_VERSION,+ "saved_at": self.saved_at,+ "workspaces": [w.to_dict() for w in self.workspaces],+ }++ @staticmethod+ def from_dict(data: Any) -> Snapshot | None:+ if not isinstance(data, dict):+ return None+ version = _as_int(data.get("version"))+ if version == 1:+ # Written before workspaces could be held open side by side: one+ # workspace, its fields at the top level. Lifted rather than+ # discarded, so an upgrade does not cost somebody their restore+ # point on the one restart where they would most want it.+ data = {+ "version": SCHEMA_VERSION,+ "saved_at": data.get("saved_at"),+ "workspaces": [+ {+ "session_id": data.get("session_id"),+ "folder": data.get("folder"),+ "terminals": data.get("terminals"),+ }+ ],+ }+ elif version != SCHEMA_VERSION:+ return None++ raw = data.get("workspaces")+ workspaces = [+ parsed+ for parsed in (+ SnapshotWorkspace.from_dict(item) for item in (raw if isinstance(raw, list) else [])+ )+ if parsed is not None+ ]+ if not workspaces:+ return None+ try:+ 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)++def _as_int(value: Any) -> int:try:return int(value)@@ -205,7 +270,7 @@ def save(snapshot: Snapshot) -> None:conversation id this feature exists to keep. So each write gets its own tempname, and the lock keeps the last writer's file the one that lands."""- if not snapshot.terminals:+ if not snapshot.workspaces:# Nothing to come back to. Clearing beats storing an empty offer that# would render as a card with no panes in it.clear()@@ -279,50 +344,62 @@ def offer(snapshot: Snapshot | None, *, installed: set[str]) -> dict[str, Any]:if snapshot is None:return {"available": False,- "folder": "",- "folder_name": "",- "folder_exists": False,"saved_at": 0.0,- "session_id": "",+ "workspace_count": 0,+ "terminal_count": 0,"resumable_count": 0,- "terminals": [],+ "workspaces": [],}- try:- folder_exists = Path(snapshot.folder).expanduser().is_dir()- except OSError:- folder_exists = False-display = _display_names()- panes: list[dict[str, Any]] = []- for term in snapshot.terminals:- agent_available = term.agent in installed- panes.append(+ workspaces: list[dict[str, Any]] = []+ for space in snapshot.workspaces:+ try:+ folder_exists = Path(space.folder).expanduser().is_dir()+ except OSError:+ folder_exists = False++ panes: list[dict[str, Any]] = []+ for term in space.terminals:+ agent_available = term.agent in installed+ panes.append(+ {+ "key": term.key,+ "name": term.name,+ "agent": term.agent,+ "display_name": display.get(term.agent, term.agent),+ "column": term.column,+ "slot": term.slot,+ "available": agent_available,+ "resumable": agent_available+ and has_conversation(+ term.agent,+ term.resume,+ _account_home(term.agent, term.account),+ ),+ "prompts_sent": term.prompts_sent,+ }+ )++ workspaces.append({- "key": term.key,- "name": term.name,- "agent": term.agent,- "display_name": display.get(term.agent, term.agent),- "column": term.column,- "slot": term.slot,- "available": agent_available,- "resumable": agent_available- and has_conversation(- term.agent, term.resume, _account_home(term.agent, term.account)- ),- "prompts_sent": term.prompts_sent,+ "session_id": space.session_id,+ "folder": space.folder,+ "folder_name": Path(space.folder).name or space.folder,+ "folder_exists": folder_exists,+ "available": folder_exists and any(p["available"] for p in panes),+ "resumable_count": sum(1 for p in panes if p["resumable"]),+ "terminals": panes,})return {- "available": folder_exists and any(p["available"] for p in panes),- "folder": snapshot.folder,- "folder_name": Path(snapshot.folder).name or snapshot.folder,- "folder_exists": folder_exists,+ "available": any(w["available"] for w in workspaces),"saved_at": snapshot.saved_at,- "session_id": snapshot.session_id,- "resumable_count": sum(1 for p in panes if p["resumable"]),- "terminals": panes,+ "workspace_count": len(workspaces),+ "terminal_count": sum(len(w["terminals"]) for w in workspaces),+ "resumable_count": sum(w["resumable_count"] for w in workspaces),+ "workspaces": workspaces,}@@ -341,20 +418,16 @@ def _display_names() -> dict[str, str]:return {}-def snapshot_now(*, session_id: str, folder: str, terminals: list[SnapshotTerminal]) -> Snapshot:- """A snapshot stamped with the current time."""- return Snapshot(- session_id=session_id,- folder=folder,- saved_at=time.time(),- terminals=terminals,- )+def snapshot_now(workspaces: list[SnapshotWorkspace]) -> Snapshot:+ """A snapshot of every open workspace, stamped with the current time."""+ return Snapshot(saved_at=time.time(), workspaces=list(workspaces))__all__ = ["SCHEMA_VERSION","Snapshot","SnapshotTerminal",+ "SnapshotWorkspace","clear","load","offer",diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex 767b30a6b6..aa832a61b4 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -48,6 +48,7 @@ there: ``cmd.exe`` drops inherited environment variables longer than 8,191characters, so an npm batch shim cannot find Node when the app has a largePATH. Other batch shims use a one-shot ``cmd /c`` (so rule 1 above still holds)."""+from __future__ import annotationsimport asyncio@@ -373,10 +374,10 @@ def agent_argv(agent: str) -> tuple[str, ...] | None:class Terminal:"""One named pane: a call-sign, an agent, and its live PTY (if attached)."""- key: str # url-safe key, e.g. "mika"- name: str # spoken call-sign, e.g. "Mika"- agent: str # "claude" | "codex"- display_name: str # "Claude Code"+ key: str # url-safe key, e.g. "mika"+ name: str # spoken call-sign, e.g. "Mika"+ agent: str # "claude" | "codex"+ display_name: str # "Claude Code"index: int# Where the pane sits in the grid, on TWO axes: the workspace is a# left-to-right list of columns, and each column is a top-to-bottom stack.@@ -494,6 +495,10 @@ class Session:id: strfolder: str+ # The tab label is workspace identity, not project identity. Several+ # workspaces may intentionally point at the same folder, so the folder's+ # basename alone cannot distinguish them.+ name: strprofile: ProjectProfileterminals: list[Terminal]created_at: float@@ -528,6 +533,7 @@ class Session:return {"id": self.id,"folder": self.folder,+ "name": self.name,"project": self.profile.to_dict(),"created_at": self.created_at,"focus_mode": self.focus_mode,@@ -545,7 +551,7 @@ class Session:return {"id": self.id,"folder": self.folder,- "name": self.profile.name or Path(self.folder).name or self.folder,+ "name": self.name,"branch": self.profile.branch,"terminals": len(self.terminals),"live_terminals": live,@@ -556,6 +562,24 @@ class Session:}+@dataclass(slots=True)+class RestoreResult:+ """What taking a restore point actually brought back.++ ``skipped`` carries a reason per workspace that could not come back (folder+ deleted, workspace limit reached). Reported rather than swallowed: a resume+ that quietly returns three of five workspaces looks like a bug to the person+ who had five.+ """++ sessions: list[Session]+ skipped: list[tuple[str, str]]++ @property+ def terminal_count(self) -> int:+ return sum(len(s.terminals) for s in self.sessions)++class SessionError(RuntimeError):"""A request the registry refuses, with a user-facing English message."""@@ -627,19 +651,16 @@ class Registry:return self._pty# -------------------------------------------------------------- session- async def start(- self, folder: str, requested: list[dict[str, Any]]- ) -> Session:+ async def start(self, folder: str, requested: list[dict[str, Any]]) -> Session:"""Open ``folder`` as a NEW workspace with one terminal per request entry.``requested`` entries look like ``{"agent": "claude", "name": "Mika"}``;the name is optional and filled from the call-sign pool.Opening ADDS a workspace and brings it to the front; whatever was open- stays open with its agents running. A folder that already has a- workspace is brought to the front instead of opened twice — two sets of- coding agents editing the same tree is almost always a misclick, and the- one that is already there has the running conversations.+ stays open with its agents running. The same folder may be opened more+ than once deliberately: each workspace is a separate set of panes and+ conversations, with a distinct tab name."""async with self._lock:if not requested:@@ -661,16 +682,6 @@ class Registry:except OSError as exc:raise SessionError(f"Cannot open {root}: {exc}") from exc- existing = self._find_by_folder(root)- if existing is not None:- self._focus_locked(existing)- await self._persist()- logger.info(- "Agentic IDE: {} is already open — brought it to the front",- root,- )- return existing-if len(self._sessions) >= MAX_WORKSPACES:raise SessionError(f"{MAX_WORKSPACES} workspaces are already open — close one "@@ -682,11 +693,7 @@ class Registry:raise SessionError(f"Unknown agent(s): {', '.join(sorted(unknown))}")missing = sorted(- {- str(r.get("agent"))- for r in requested- if agent_argv(str(r.get("agent"))) is None- }+ {str(r.get("agent")) for r in requested if agent_argv(str(r.get("agent"))) is None})if missing:pretty = ", ".join(AGENT_DISPLAY.get(m, m) for m in missing)@@ -771,12 +778,29 @@ class Registry:for term in session.terminals}+ def _available_workspace_name(self, wanted: str) -> str:+ """Return a human-readable tab name that is unique in the bar."""+ base = wanted.strip() or "Workspace"+ used = {session.name.casefold() for session in self._sessions.values()}+ if base.casefold() not in used:+ return base+ suffix = 2+ while f"{base} {suffix}".casefold() in used:+ suffix += 1+ return f"{base} {suffix}"+def _focus_locked(self, session: Session) -> None:"""Bring ``session`` to the front. Caller holds the lock."""self._active = session.idsession.last_active_at = time.time()- async def _open_locked(self, root: Path, terminals: list[Terminal]) -> Session:+ async def _open_locked(+ self,+ root: Path,+ terminals: list[Terminal],+ *,+ name: str | None = None,+ ) -> Session:"""Turn a prepared list of panes into a NEW open workspace, at the front.Shared by ``start`` and ``restore`` on purpose. Everything a workspace@@ -792,15 +816,14 @@ class Registry:try:from jarvis.workspace.trust import ensure_trusted- await asyncio.to_thread(- ensure_trusted, root, sorted({t.agent for t in terminals})- )+ await asyncio.to_thread(ensure_trusted, root, sorted({t.agent for t in terminals}))except Exception as exc: # noqa: BLE001 - trust is a conveniencelogger.warning("Agentic IDE: pre-trust failed: {}", exc)session = Session(id=f"ide_{uuid4().hex[:12]}",folder=str(root),+ name=self._available_workspace_name(name or profile.name or root.name or str(root)),profile=profile,terminals=terminals,created_at=time.time(),@@ -821,87 +844,109 @@ class Registry:await self._persist()return session- async def restore(self, snapshot: resume_store.Snapshot) -> Session:- """Reopen the workspace a snapshot describes, without starting anything.+ async def restore(self, snapshot: resume_store.Snapshot) -> RestoreResult:+ """Reopen EVERY workspace a snapshot describes, starting nothing.The panes come back with their call-signs, their coding CLIs, their gridcoordinates 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+ 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 placewhere 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.+ the first time either changed. It is also why restoring several+ workspaces is cheap: none of them launches anything until a pane+ connects, and only the workspace on screen has panes mounted.++ All of them rather than the front one, because "resume all sessions" is+ what was asked for and somebody with four folders open had four.++ A workspace that cannot come back does not stop the others: a deleted+ folder is reported, an already-open folder is left running (reopening it+ would kill live agents to replace them with restarted ones), and the+ workspace limit stops the rest with a reason. What could not be restored+ comes back in ``skipped`` so the caller can say so out loud instead of+ quietly returning less than it promised.++ A pane whose CLI is no longer installed IS 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:- 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+ if not snapshot.workspaces:+ raise SessionError("There is nothing in that restore point.")- existing = self._find_by_folder(root)- if existing is not None:- # It never went away — the offer was stale. Showing it is the- # honest outcome; reopening would kill the running agents to- # replace them with restarted ones.- self._focus_locked(existing)- await self._persist()- return existing+ restored: list[Session] = []+ skipped: list[tuple[str, str]] = []+ 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 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.+ if restored:+ self._focus_locked(restored[0])+ await self._persist()+ logger.info(+ "Agentic IDE resumed {} workspace(s), {} terminal(s); {} skipped",+ len(restored),+ sum(len(s.terminals) for s in restored),+ len(skipped),+ )+ return RestoreResult(sessions=restored, skipped=skipped)- if len(self._sessions) >= MAX_WORKSPACES:+ async def _restore_one_locked(self, space: resume_store.SnapshotWorkspace) -> Session | None:+ """Reopen one remembered workspace. Caller holds the lock."""+ root = Path(space.folder).expanduser() # noqa: ASYNC240+ try:+ if not await asyncio.to_thread(root.is_dir):raise SessionError(- f"{MAX_WORKSPACES} workspaces are already open — close one "- "before reopening this."+ 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- 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,- # The remembered account, re-validated: a pane must come back- # on the subscription whose history holds its conversation,- # and an account deleted in the meantime falls back to the- # active one rather than failing the reopen.- account=resolve_account(entry.agent, entry.account),- )- for index, entry in enumerate(snapshot.terminals)- ]- # A snapshot remembers the call-signs it had when it was the only- # workspace. Another one may hold them now, and two panes answering- # to one name would make every spoken instruction ambiguous — so a- # collision is renamed here. Only the label moves; the resume handle- # underneath it is what continues the conversation.- self._dedupe_names(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 resumed: {} terminals in {} ({} with a "- "conversation to continue)",- len(terminals),- root,- sum(1 for t in terminals if t.resume is not None),+ if len(self._sessions) >= MAX_WORKSPACES:+ raise SessionError(+ f"{MAX_WORKSPACES} workspaces are already open — close one before reopening this.")- return session++ 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,+ # The remembered account, re-validated: a pane must come back+ # on the subscription whose history holds its conversation,+ # and an account deleted in the meantime falls back to the+ # active one rather than failing the reopen.+ account=resolve_account(entry.agent, entry.account),+ )+ for index, entry in enumerate(space.terminals)+ ]+ # A snapshot remembers the call-signs each workspace had. Another one may+ # hold them now, and two panes answering to one name would make every+ # spoken instruction ambiguous — so a collision is renamed here. Only the+ # label moves; the resume handle underneath it continues the conversation.+ self._dedupe_names(terminals)+ session = await self._open_locked(root, terminals, name=space.name or None)+ # 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)+ return sessiondef _dedupe_names(self, terminals: list[Terminal]) -> None:"""Rename any call-sign already spoken for by another open workspace."""@@ -944,55 +989,86 @@ class Registry:logger.info("Agentic IDE: switched to {}", session.folder)return session+ async def rename(self, workspace_id: str, name: str) -> Session:+ """Rename one workspace tab without changing its folder or agents."""+ cleaned = " ".join(name.split()).strip()+ if not cleaned:+ raise SessionError("Give the workspace a name.")+ if len(cleaned) > 80:+ raise SessionError("Workspace names can be at most 80 characters.")+ async with self._lock:+ session = self._sessions.get(workspace_id)+ if session is None:+ raise SessionError("That workspace is not open any more.")+ if any(+ other.id != workspace_id and other.name.casefold() == cleaned.casefold()+ for other in self._sessions.values()+ ):+ raise SessionError("Another workspace already uses that name.")+ session.name = cleaned+ await self._persist()+ return session+async def end(self, workspace_id: str | None = None) -> bool:"""Close one workspace and stop every agent in it.Without an id this closes the workspace on screen, which is what thetoolbar's Close button and the existing CLI/API callers mean. ReturnsFalse when there was nothing to close.++ Closing does NOT withdraw the restore point. Closing for the day and+ picking the same folders up tomorrow is the main thing resuming is FOR,+ so the snapshot written while these workspaces were open stays exactly+ as it is. Only the user asking to start fresh discards it."""async with self._lock:target = workspace_id if workspace_id is not None else self._activeif target is None or target not in self._sessions:- if not self._sessions:- await self._forget()return Falseawait self._close_locked(target)- if not self._sessions:- # That was the last one. Withdraw the restore point too:- # re-offering a workspace somebody deliberately shut down is- # the kind of prompt people learn to dismiss without reading.- # With others still open, ``_close_locked`` has already- # re-pointed the snapshot at whichever took the front.- await self._forget()return Trueasync def close_all(self) -> int:- """Close every open workspace. Returns how many were closed."""+ """Close every open workspace. Returns how many were closed.++ The restore point survives — see ``end``.+ """async with self._lock:count = len(self._sessions)for workspace_id in list(self._sessions):await self._close_locked(workspace_id)- if count:- await self._forget()return count# ------------------------------------------------------------- snapshotdef snapshot(self) -> resume_store.Snapshot | None:- """The FRONT workspace in the form the resume store keeps it, or None.-- One workspace, not all of them: the restore point answers "what was I- working in when this stopped?", and that is the one that was on screen.- Bringing back every open workspace after a restart would mean relaunching- a folder's worth of coding agents per tab without being asked.+ """EVERY open workspace, in the form the resume store keeps it.++ All of them, front one first. An earlier version remembered only the+ workspace on screen, on the reasoning that bringing back all of them+ would relaunch a folder's worth of coding agents per tab unasked. Both+ halves of that were wrong: the user asked for everything back, and+ restoring costs nothing — ``restore`` starts no agent, and only the+ workspace on screen has panes mounted. Five workspaces in the bar are+ five folders waiting, not five folders' worth of running agents.++ Returns None only when nothing is open at all, which leaves whatever was+ stored before untouched — closing the last workspace must not erase the+ thing the user wants back tomorrow."""- session = self.session- if session is None:+ if not self._sessions:return None+ front = self._active+ ordered = sorted(self._sessions.values(), key=lambda s: s.id != front)return resume_store.snapshot_now(- session_id=session.id,- folder=session.folder,- terminals=[t.to_snapshot() for t in session.terminals],+ [+ resume_store.SnapshotWorkspace(+ session_id=session.id,+ folder=session.folder,+ name=session.name,+ terminals=[t.to_snapshot() for t in session.terminals],+ )+ for session in ordered+ ])async def _persist(self) -> None:@@ -1053,12 +1129,15 @@ class Registry:# Drop THIS folder's codebase index. A blanket reset would take the# other open workspaces' indexes with it and silently cost them their# `@file` suggestions.- try:- from . import file_index+ # Workspaces may share a folder. Its index remains useful until the last+ # workspace using that folder closes.+ if self._find_by_folder(Path(session.folder)) is None:+ try:+ from . import file_index- file_index.forget_index(session.folder)- except Exception: # noqa: BLE001, S110 - best-effort teardown- pass+ file_index.forget_index(session.folder)+ except Exception: # noqa: BLE001, S110 - best-effort teardown+ passif self._active == workspace_id:# Hand the front to the most recently used survivor rather than to@@ -1080,18 +1159,14 @@ class Registry:session = self.sessionif session is None:if enabled:- raise SessionError(- "No Agentic-IDE session is running — open one first."- )+ raise SessionError("No Agentic-IDE session is running — open one first.")return Falsesession.focus_mode = bool(enabled)logger.info("Agentic IDE focus mode {}", "on" if enabled else "off")return session.focus_mode# ------------------------------------------------------------------ pty- def _locate(- self, key: str, workspace_id: str | None- ) -> tuple[Session, Terminal] | None:+ def _locate(self, key: str, workspace_id: str | None) -> tuple[Session, Terminal] | None:"""One pane and the workspace holding it, by call-sign.``workspace_id`` addresses a specific workspace — which every PTY-level@@ -1189,9 +1264,7 @@ class Registry:# for a conversation that is right there.home = account_home(term.agent, term.account)continuing = resume_argv(term.agent, term.resume)- if continuing is not None and not has_conversation(- term.agent, term.resume, home- ):+ if continuing is not None and not has_conversation(term.agent, term.resume, home):logger.info("Agentic IDE: {} has no conversation to continue — starting fresh",term.name,@@ -1244,13 +1317,7 @@ class Registry:# agent normally exits 0, and a pane we killed ourselves reports a# failure exit that looks identical to a crash — restarting either# of those would be its own bug.- if (- term.resumed- and not term.stopping- and not recovered- and died_young- and code != 0- ):+ if term.resumed and not term.stopping and not recovered and died_young and code != 0:recovered = Truelogger.warning("Agentic IDE: {} could not continue its previous "@@ -1270,9 +1337,7 @@ class Registry:workspace_id=session.id,)except SessionError as exc:- logger.warning(- "Agentic IDE: {} could not be restarted: {}", term.name, 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.@@ -1337,9 +1402,7 @@ class Registry:if term.resume is not None:returntaken = {- other.resume.id- for other in session.terminals- if other.resume is not None+ other.resume.id for other in session.terminals if other.resume is not None}found = await asyncio.to_thread(discover,@@ -1352,9 +1415,7 @@ class Registry:if found is None:continueterm.resume = found- logger.debug(- "Agentic IDE: {} is conversation {}", term.name, found.id- )+ logger.debug("Agentic IDE: {} is conversation {}", term.name, found.id)await self._persist()returnexcept asyncio.CancelledError:@@ -1376,9 +1437,7 @@ class Registry:return Falsereturn self._manager().write(term.pty_id, data)- def resize(- self, key: str, cols: int, rows: int, workspace_id: str | None = None- ) -> bool:+ def resize(self, key: str, cols: int, rows: int, workspace_id: str | None = None) -> bool:found = self._locate(key, workspace_id)if found is None:return False@@ -1647,8 +1706,7 @@ class Registry:_session, term = foundif term.status != "live" or not term.pty_id:raise SessionError(- f"{term.name} is not running right now "- f"(status: {term.status}) — nothing was sent."+ f"{term.name} is not running right now (status: {term.status}) — nothing was sent.")payload = sanitize_prompt(text, keep_newlines=True)if not payload:@@ -1660,8 +1718,7 @@ class Registry:submitted = await self._write_and_confirm(term, payload, manager, multiline)if not submitted and multiline:logger.warning(- "Agentic IDE: {} did not accept a multi-line prompt — "- "re-sending it on one line",+ "Agentic IDE: {} did not accept a multi-line prompt — re-sending it on one line",term.name,)payload = sanitize_prompt(payload)@@ -1701,9 +1758,7 @@ class Registry:manager.write(term.pty_id or "", "\r")return await self._confirm_submitted(term, payload, manager)- async def _confirm_submitted(- self, term: Terminal, payload: str, manager: PtyManager- ) -> bool:+ async def _confirm_submitted(self, term: Terminal, payload: str, manager: PtyManager) -> bool:"""True once ``payload`` has left the terminal's input line.The input line lives at the bottom of the screen, just above the status@@ -1775,17 +1830,11 @@ class Registry:"""The 'no such pane' error, naming every pane that DOES exist."""if not self._sessions:return SessionError("No Agentic-IDE session is running.")- known = ", ".join(- term.name for s in self._sessions.values() for term in s.terminals- )- return SessionError(- f"No terminal called {wanted!r}. Running: {known or 'none'}."- )+ known = ", ".join(term.name for s in self._sessions.values() for term in s.terminals)+ return SessionError(f"No terminal called {wanted!r}. Running: {known or 'none'}.")-def terminals_added_event(- session: Session, created: list[Terminal], *, source_layer: str-) -> Any:+def terminals_added_event(session: Session, created: list[Terminal], *, source_layer: str) -> Any:"""The bus event announcing new panes to every connected client.A free function rather than a registry call, because the registry has no bus:diff --git a/tests/unit/agentic_ide/test_resume_routes.py b/tests/unit/agentic_ide/test_resume_routes.pyindex 03b5970660..2fe498fac4 100644--- a/tests/unit/agentic_ide/test_resume_routes.py+++ b/tests/unit/agentic_ide/test_resume_routes.py@@ -41,55 +41,60 @@ def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:ide.reset_registry()-def _store(folder: Path, *, with_conversation: bool = True) -> None:+def _store(*folders: Path, with_conversation: bool = True) -> None:+ """Put a restore point on disk holding one workspace per folder."""resume_store.save(resume_store.Snapshot(- session_id="ide_old",- folder=str(folder),saved_at=100.0,- terminals=[- resume_store.SnapshotTerminal(- key="alex",- name="Alex",- agent="claude",- column=0,- slot=0,- resume=(- ResumeHandle(- kind="claude_session", id="u", captured_at=1.0- )- if with_conversation- else None- ),- prompts_sent=2,- ),- resume_store.SnapshotTerminal(- key="blake", name="Blake", agent="codex", column=1, slot=0- ),- ],+ workspaces=[_workspace(f, with_conversation=with_conversation) for f in folders],))+def _workspace(folder: Path, *, with_conversation: bool = True) -> resume_store.SnapshotWorkspace:+ return resume_store.SnapshotWorkspace(+ session_id="ide_old",+ folder=str(folder),+ terminals=[+ resume_store.SnapshotTerminal(+ key="alex",+ name="Alex",+ agent="claude",+ column=0,+ slot=0,+ resume=(+ ResumeHandle(kind="claude_session", id="u", captured_at=1.0)+ if with_conversation+ else None+ ),+ prompts_sent=2,+ ),+ resume_store.SnapshotTerminal(+ key="blake", name="Blake", agent="codex", column=1, slot=0+ ),+ ],+ )++# ------------------------------------------------------------------- offerdef test_no_snapshot_means_no_offer(client: TestClient) -> None:"""A fresh install: an empty answer, never an error."""body = client.get("/api/agentic-ide/resume").json()assert body["available"] is False- assert body["terminals"] == []+ assert body["workspaces"] == []-def test_the_offer_names_the_panes_and_where_they_sat(- client: TestClient, tmp_path: Path-) -> None:+def test_the_offer_names_the_panes_and_where_they_sat(client: TestClient, tmp_path: Path) -> None:_store(tmp_path)body = client.get("/api/agentic-ide/resume").json()assert body["available"] is True- assert body["folder"] == str(tmp_path)- assert body["folder_name"] == tmp_path.name- assert [t["name"] for t in body["terminals"]] == ["Alex", "Blake"]- assert [(t["column"], t["slot"]) for t in body["terminals"]] == [(0, 0), (1, 0)]- assert [t["display_name"] for t in body["terminals"]] == ["Claude Code", "Codex"]+ space = body["workspaces"][0]+ assert space["folder"] == str(tmp_path)+ assert space["folder_name"] == tmp_path.name+ panes = space["terminals"]+ assert [t["name"] for t in panes] == ["Alex", "Blake"]+ assert [(t["column"], t["slot"]) for t in panes] == [(0, 0), (1, 0)]+ assert [t["display_name"] for t in panes] == ["Claude Code", "Codex"]def test_the_offer_says_which_conversations_come_back(@@ -98,7 +103,7 @@ def test_the_offer_says_which_conversations_come_back(_store(tmp_path)existing_conversation("u")body = client.get("/api/agentic-ide/resume").json()- panes = {t["name"]: t for t in body["terminals"]}+ panes = {t["name"]: t for t in body["workspaces"][0]["terminals"]}assert panes["Alex"]["resumable"] is Trueassert panes["Blake"]["resumable"] is False # never got a conversation idassert body["resumable_count"] == 1@@ -114,7 +119,8 @@ def test_the_offer_survives_a_machine_with_no_coding_cli(_store(tmp_path)body = client.get("/api/agentic-ide/resume").json()assert body["available"] is False- assert all(t["available"] is False for t in body["terminals"])+ panes = body["workspaces"][0]["terminals"]+ assert all(t["available"] is False for t in panes)def test_a_broken_agent_probe_does_not_take_the_screen_down(@@ -135,7 +141,7 @@ def test_a_broken_agent_probe_does_not_take_the_screen_down(body = res.json()# Honest rather than optimistic: nothing is promised that cannot be checked.assert body["available"] is False- assert [t["name"] for t in body["terminals"]] == ["Alex", "Blake"]+ assert [t["name"] for t in body["workspaces"][0]["terminals"]] == ["Alex", "Blake"]# ------------------------------------------------------------------ resume@@ -144,8 +150,10 @@ def test_resuming_reopens_the_workspace(client: TestClient, tmp_path: Path) -> Nres = client.post("/api/agentic-ide/resume")assert res.status_code == 200body = res.json()- assert [t["name"] for t in body["session"]["terminals"]] == ["Alex", "Blake"]- assert body["session"]["folder"] == str(tmp_path)+ session = body["state"]["session"]+ assert [t["name"] for t in session["terminals"]] == ["Alex", "Blake"]+ assert session["folder"] == str(tmp_path)+ assert body["workspace_count"] == 1# The running state agrees, so a client may read either.assert client.get("/api/agentic-ide/state").json()["active"] is True@@ -169,28 +177,23 @@ def test_resuming_without_a_snapshot_is_a_conflict_not_a_crash(assert "no previous workspace" in res.json()["detail"]-def test_resuming_a_deleted_folder_says_so_plainly(- client: TestClient, tmp_path: Path-) -> None:+def test_resuming_a_deleted_folder_says_so_plainly(client: TestClient, tmp_path: Path) -> None:_store(tmp_path / "gone")res = client.post("/api/agentic-ide/resume")assert res.status_code == 422assert "no longer" in res.json()["detail"]-def test_resuming_starts_no_agent_by_itself(- client: TestClient, tmp_path: Path-) -> None:+def test_resuming_starts_no_agent_by_itself(client: TestClient, tmp_path: Path) -> None:"""The panes connect as they always do; that is what starts them."""_store(tmp_path)body = client.post("/api/agentic-ide/resume").json()- assert all(t["status"] == "pending" for t in body["session"]["terminals"])+ panes = body["state"]["session"]["terminals"]+ assert all(t["status"] == "pending" for t in panes)# ------------------------------------------------------------- start fresh-def test_starting_fresh_withdraws_the_offer(- client: TestClient, tmp_path: Path-) -> None:+def test_starting_fresh_withdraws_the_offer(client: TestClient, tmp_path: Path) -> None:_store(tmp_path)assert client.delete("/api/agentic-ide/resume").json()["removed"] is Trueassert client.get("/api/agentic-ide/resume").json()["available"] is False@@ -211,9 +214,7 @@ def test_discarding_a_restore_point_is_declared_dangerous() -> None:assert route.openapi_extra == {"x-jarvis-dangerous": True}-def test_resuming_counts_conversations_not_handles(- client: TestClient, tmp_path: Path-) -> None:+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@@ -224,3 +225,49 @@ def test_resuming_counts_conversations_not_handles(body = client.post("/api/agentic-ide/resume").json()assert body["resumable_count"] == 0assert body["started_fresh"] == 2+++def test_resuming_brings_back_every_workspace(+ client: TestClient, tmp_path: Path+) -> None:+ """"Resume all sessions" means all of them, not whichever was on screen."""+ first, second = tmp_path / "one", tmp_path / "two"+ first.mkdir()+ second.mkdir()+ _store(first, second)++ body = client.post("/api/agentic-ide/resume").json()+ assert body["workspace_count"] == 2+ assert body["terminal_count"] == 4+ folders = {w["folder"] for w in body["state"]["workspaces"]}+ assert folders == {str(first), str(second)}+ # The first remembered workspace is the one on screen again.+ assert body["state"]["session"]["folder"] == str(first)+++def test_a_workspace_that_cannot_come_back_does_not_fail_the_rest(+ client: TestClient, tmp_path: Path+) -> None:+ """Three folders, one deleted: two come back and the third is NAMED."""+ alive, gone = tmp_path / "alive", tmp_path / "deleted"+ alive.mkdir()+ _store(alive, gone)++ body = client.post("/api/agentic-ide/resume").json()+ assert body["workspace_count"] == 1+ assert [s["folder"] for s in body["skipped"]] == [str(gone)]+ assert "no longer" in body["skipped"][0]["detail"]+++def test_the_offer_lists_each_workspace_it_remembers(+ client: TestClient, tmp_path: Path+) -> None:+ first, second = tmp_path / "one", tmp_path / "two"+ first.mkdir()+ second.mkdir()+ _store(first, second)++ body = client.get("/api/agentic-ide/resume").json()+ assert body["workspace_count"] == 2+ assert body["terminal_count"] == 4+ assert [w["folder_name"] for w in body["workspaces"]] == ["one", "two"]diff --git a/tests/unit/agentic_ide/test_resume_session.py b/tests/unit/agentic_ide/test_resume_session.pyindex ad11bbc20e..57158bd13a 100644--- a/tests/unit/agentic_ide/test_resume_session.py+++ b/tests/unit/agentic_ide/test_resume_session.py@@ -26,9 +26,7 @@ def fake_pty() -> FakePtyManager:@pytest.fixture-def registry(- fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch-) -> ide.Registry:+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)@@ -69,9 +67,7 @@ async def test_a_pane_with_a_handle_continues_instead_of_starting_over() -> None:await registry.start(str(tmp_path), [{"agent": "claude", "name": "Alex"}])term = registry.session.find("Alex")- term.resume = ResumeHandle(- kind="claude_session", id="known-id", captured_at=1.0- )+ term.resume = ResumeHandle(kind="claude_session", id="known-id", captured_at=1.0)existing_conversation("known-id")await registry.attach("Alex", 80, 24, _noop, _noop_exit)@@ -151,9 +147,7 @@ async def test_a_handle_with_no_conversation_behind_it_starts_fresh("""await registry.start(str(tmp_path), [{"agent": "claude", "name": "Alex"}])term = registry.session.find("Alex")- term.resume = ResumeHandle(- kind="claude_session", id="never-written", captured_at=1.0- )+ term.resume = ResumeHandle(kind="claude_session", id="never-written", captured_at=1.0)# Deliberately no conversation on disk.await registry.attach("Alex", 80, 24, _noop, _noop_exit)@@ -172,23 +166,28 @@ async def test_the_offer_does_not_promise_a_conversation_that_is_not_there() -> 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="alex",- name="Alex",- agent="claude",- resume=ResumeHandle(- kind="claude_session", id="never-written", captured_at=1.0- ),+ workspaces=[+ resume_store.SnapshotWorkspace(+ session_id="ide_old",+ folder=str(tmp_path),+ terminals=[+ resume_store.SnapshotTerminal(+ key="alex",+ name="Alex",+ 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+ panes = view["workspaces"][0]["terminals"]+ assert panes[0]["available"] is True # the pane comes back+ assert panes[0]["resumable"] is False # the conversation does notassert view["resumable_count"] == 0@@ -329,11 +328,18 @@ async def test_a_late_crash_is_reported_as_a_crash(# ------------------------------------------------------------------ restore-def _snapshot(folder: Path) -> resume_store.Snapshot:+def _snapshot(*folders: Path) -> resume_store.Snapshot:+ """A restore point holding one workspace per folder."""return resume_store.Snapshot(+ saved_at=1.0,+ workspaces=[_workspace(f) for f in folders],+ )+++def _workspace(folder: Path) -> resume_store.SnapshotWorkspace:+ return resume_store.SnapshotWorkspace(session_id="ide_old",folder=str(folder),- saved_at=1.0,terminals=[resume_store.SnapshotTerminal(key="dana",@@ -341,9 +347,7 @@ def _snapshot(folder: Path) -> resume_store.Snapshot:agent="claude",column=1,slot=1,- resume=ResumeHandle(- kind="claude_session", id="dana-conv", captured_at=1.0- ),+ resume=ResumeHandle(kind="claude_session", id="dana-conv", captured_at=1.0),prompts_sent=2,),resume_store.SnapshotTerminal(@@ -356,7 +360,7 @@ def _snapshot(folder: Path) -> resume_store.Snapshot:async def test_restore_rebuilds_titles_agents_and_positions(registry: ide.Registry, tmp_path: Path) -> None:- restored = await registry.restore(_snapshot(tmp_path))+ restored = (await registry.restore(_snapshot(tmp_path))).sessions[0]# Reading order, not snapshot order: left to right, top to bottom.assert [t.name for t in restored.terminals] == ["Alex", "Dana"]@@ -371,7 +375,7 @@ 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))+ restored = (await registry.restore(_snapshot(tmp_path))).sessions[0]assert all(t.status == "pending" for t in restored.terminals)assert fake_pty.spawns == []@@ -400,34 +404,25 @@ async def test_restore_refuses_a_folder_that_is_gone(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=[]- )+async def test_restore_refuses_an_empty_workspace(registry: ide.Registry, tmp_path: Path) -> None:+ empty = resume_store.Snapshot(saved_at=1.0, workspaces=[])with pytest.raises(ide.SessionError):await registry.restore(empty)-async def test_restoring_a_folder_that_is_still_open_switches_to_it(+async def test_restoring_a_folder_that_is_still_open_adds_the_remembered_workspace(registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path) -> None:- """A stale offer must not trade a running workspace for a restarted one.-- The offer describes a folder; if that folder is open right now, the honest- outcome is to show it. Reopening would kill agents that are working to- replace them with agents that have to be resumed.- """+ """Two remembered pane groups may intentionally share one folder."""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- restored = await registry.restore(_snapshot(tmp_path))+ restored = (await registry.restore(_snapshot(tmp_path))).sessions[0]assert live not in fake_pty.closed, "the running agent must survive"- assert [t.name for t in restored.terminals] == ["Old"]- assert len(registry.sessions) == 1+ assert [t.name for t in restored.terminals] == ["Alex", "Dana"]+ assert len(registry.sessions) == 2async def test_restoring_another_folder_opens_it_beside_the_running_one(@@ -453,8 +448,8 @@ async def test_opening_a_workspace_makes_it_resumable(await registry.start(str(tmp_path), [{"agent": "claude", "name": "Alex"}])saved = resume_store.load()assert saved is not None- assert [t.name for t in saved.terminals] == ["Alex"]- assert saved.folder == str(tmp_path)+ assert [t.name for t in saved.workspaces[0].terminals] == ["Alex"]+ assert saved.workspaces[0].folder == str(tmp_path)async def test_the_conversation_id_reaches_the_snapshot(@@ -465,8 +460,8 @@ async def test_the_conversation_id_reaches_the_snapshot(await registry.attach("Alex", 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("Alex").resume.id+ assert saved is not None and saved.workspaces[0].terminals[0].resume is not None+ assert saved.workspaces[0].terminals[0].resume.id == registry.session.find("Alex").resume.idasync def test_splitting_and_closing_keep_the_offer_current(@@ -475,32 +470,75 @@ async def test_splitting_and_closing_keep_the_offer_current(await registry.start(str(tmp_path), [{"agent": "claude", "name": "Alex"}])await registry.add_terminal(anchor="Alex", direction="right", name="Blake")saved = resume_store.load()- assert saved is not None and [t.name for t in saved.terminals] == ["Alex", "Blake"]+ assert saved is not None and [t.name for t in saved.workspaces[0].terminals] == [+ "Alex",+ "Blake",+ ]await registry.close_terminal("Blake")saved = resume_store.load()- assert saved is not None and [t.name for t in saved.terminals] == ["Alex"]+ assert saved is not None and [t.name for t in saved.workspaces[0].terminals] == ["Alex"]-async def test_closing_the_workspace_deliberately_withdraws_the_offer(+async def test_closing_the_workspace_keeps_it_resumable(registry: ide.Registry, tmp_path: Path) -> None:- """An explicit close means "I am done" — re-offering it would be noise."""+ """Closing for the day and picking it up tomorrow is the point of this.++ An earlier version withdrew the offer on an explicit close, reasoning that+ re-proposing something somebody just shut down is noise. The maintainer+ reported the opposite: they close the workspace, come back, and want it back.+ Only asking to start fresh discards a restore point.+ """await registry.start(str(tmp_path), [{"agent": "claude", "name": "Alex"}])assert resume_store.load() is not Noneawait registry.end()++ saved = resume_store.load()+ assert saved is not None, "closing must not erase what the user wants back"+ assert saved.workspaces[0].folder == str(tmp_path)+ assert [t.name for t in saved.workspaces[0].terminals] == ["Alex"]+++async def test_closing_every_workspace_still_keeps_them_resumable(+ registry: ide.Registry, tmp_path: Path+) -> None:+ """Shutting everything down for the evening is the main case, not an edge."""+ first, second = tmp_path / "one", tmp_path / "two"+ first.mkdir()+ second.mkdir()+ await registry.start(str(first), [{"agent": "claude", "name": "Alex"}])+ await registry.start(str(second), [{"agent": "claude", "name": "Blake"}])++ assert await registry.close_all() == 2++ saved = resume_store.load()+ assert saved is not None+ assert {w.folder for w in saved.workspaces} == {str(first), str(second)}+++async def test_only_starting_fresh_discards_the_restore_point(+ registry: ide.Registry, tmp_path: Path+) -> None:+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Alex"}])+ await registry.end()+ assert resume_store.load() is not None++ assert resume_store.clear() is Trueassert resume_store.load() is None-async def test_the_offer_follows_the_workspace_on_screen(+async def test_every_open_workspace_is_remembered_front_one_first(registry: ide.Registry, tmp_path: Path) -> None:- """The restore point answers "what was I working in", so it tracks the front.+ """All of them, and the one on screen leads.- With several workspaces open it is the one being LOOKED at that comes back- after a restart — restoring all of them would relaunch a folder's worth of- coding agents per tab without being asked.+ 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."""first = tmp_path / "first"second = tmp_path / "second"@@ -510,11 +548,13 @@ async def test_the_offer_follows_the_workspace_on_screen(await registry.start(str(second), [{"agent": "claude", "name": "Blake"}])saved = resume_store.load()- assert saved is not None and saved.folder == str(second)+ assert saved is not None+ assert [w.folder for w in saved.workspaces] == [str(second), str(first)]await registry.activate(one.id)saved = resume_store.load()- assert saved is not None and saved.folder == str(first)+ assert saved is not None+ assert [w.folder for w in saved.workspaces] == [str(first), str(second)]async def test_closing_one_of_two_leaves_the_survivor_resumable(@@ -531,7 +571,10 @@ async def test_closing_one_of_two_leaves_the_survivor_resumable(await registry.end(two.id)saved = resume_store.load()- assert saved is not None and saved.folder == str(first)+ assert saved is not None+ # The closed one is no longer open, so it is no longer remembered as open —+ # the survivor is, and it is the one on screen.+ assert [w.folder for w in saved.workspaces] == [str(first)]assert registry.active_id == one.id@@ -542,9 +585,7 @@ async def test_a_broken_snapshot_write_never_breaks_the_workspace(raise OSError("disk full")monkeypatch.setattr(resume_store, "save", _boom)- workspace = await registry.start(- str(tmp_path), [{"agent": "claude", "name": "Alex"}]- )+ workspace = await registry.start(str(tmp_path), [{"agent": "claude", "name": "Alex"}])assert [t.name for t in workspace.terminals] == ["Alex"]@@ -565,7 +606,7 @@ async def test_a_cli_that_cannot_be_told_its_id_gets_looked_up(await asyncio.sleep(0.05)assert registry.session.find("Cody").resume == foundsaved = resume_store.load()- assert saved is not None and saved.terminals[0].resume == found+ assert saved is not None and saved.workspaces[0].terminals[0].resume == foundasync def test_a_lookup_offers_the_ids_other_panes_already_hold(diff --git a/tests/unit/agentic_ide/test_resume_store.py b/tests/unit/agentic_ide/test_resume_store.pyindex 78dc7e7b94..e7533afe2b 100644--- a/tests/unit/agentic_ide/test_resume_store.py+++ b/tests/unit/agentic_ide/test_resume_store.py@@ -21,10 +21,18 @@ from jarvis.agentic_ide.agent_sessions import ResumeHandledef _snapshot(folder: str) -> resume_store.Snapshot:- return resume_store.Snapshot(+ return _snapshot_of(_workspace(folder))+++def _snapshot_of(*workspaces: resume_store.SnapshotWorkspace) -> resume_store.Snapshot:+ return resume_store.Snapshot(saved_at=100.0, workspaces=list(workspaces))+++def _workspace(folder: str) -> resume_store.SnapshotWorkspace:+ return resume_store.SnapshotWorkspace(session_id="ide_test",folder=folder,- saved_at=100.0,+ name="Release review",terminals=[resume_store.SnapshotTerminal(key="alex",@@ -32,9 +40,7 @@ def _snapshot(folder: str) -> resume_store.Snapshot:agent="claude",column=0,slot=0,- resume=ResumeHandle(- kind="claude_session", id="u-1", captured_at=1.0- ),+ resume=ResumeHandle(kind="claude_session", id="u-1", captured_at=1.0),prompts_sent=3,),resume_store.SnapshotTerminal(@@ -49,12 +55,13 @@ def test_a_saved_snapshot_comes_back_intact(tmp_path: Path) -> None:resume_store.save(_snapshot(str(tmp_path)))loaded = resume_store.load()assert loaded is not None- assert [t.name for t in loaded.terminals] == ["Alex", "Blake"]- assert [(t.column, t.slot) for t in loaded.terminals] == [(0, 0), (1, 0)]- assert [t.agent for t in loaded.terminals] == ["claude", "codex"]- assert loaded.terminals[0].resume is not None- assert loaded.terminals[0].resume.id == "u-1"- assert loaded.terminals[1].resume is None+ assert [t.name for t in loaded.workspaces[0].terminals] == ["Alex", "Blake"]+ assert [(t.column, t.slot) for t in loaded.workspaces[0].terminals] == [(0, 0), (1, 0)]+ assert [t.agent for t in loaded.workspaces[0].terminals] == ["claude", "codex"]+ assert loaded.workspaces[0].terminals[0].resume is not None+ assert loaded.workspaces[0].terminals[0].resume.id == "u-1"+ assert loaded.workspaces[0].terminals[1].resume is None+ assert loaded.workspaces[0].name == "Release review"def test_nothing_saved_means_nothing_to_resume() -> None:@@ -73,12 +80,69 @@ def test_a_snapshot_from_a_future_version_is_ignored(tmp_path: Path) -> None:resume_store.save(_snapshot(str(tmp_path)))path = resume_store._store_path()path.write_text(- path.read_text(encoding="utf-8").replace('"version": 1', '"version": 99'),+ path.read_text(encoding="utf-8").replace('"version": 2', '"version": 99'),encoding="utf-8",)assert resume_store.load() is None+def test_a_snapshot_from_the_one_workspace_era_still_resumes(tmp_path: Path) -> None:+ """An upgrade must not cost the restore point on the very restart that needs it.++ Version 1 was written when only one workspace could be open, with its folder+ and panes at the top level. It is lifted into a single workspace rather than+ discarded.+ """+ import json++ legacy = {+ "version": 1,+ "session_id": "ide_old",+ "folder": str(tmp_path),+ "saved_at": 42.0,+ "terminals": [{"key": "alex", "name": "Alex", "agent": "claude", "column": 0, "slot": 0}],+ }+ target = resume_store._store_path()+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(json.dumps(legacy), encoding="utf-8")++ loaded = resume_store.load()+ assert loaded is not None+ assert len(loaded.workspaces) == 1+ assert loaded.workspaces[0].folder == str(tmp_path)+ assert [t.name for t in loaded.workspaces[0].terminals] == ["Alex"]+ assert loaded.saved_at == 42.0+++def test_every_open_workspace_is_remembered(tmp_path: Path) -> None:+ """Somebody with four folders open had four — one is not an answer."""+ first, second = tmp_path / "one", tmp_path / "two"+ first.mkdir()+ second.mkdir()+ resume_store.save(_snapshot_of(_workspace(str(first)), _workspace(str(second))))++ loaded = resume_store.load()+ assert loaded is not None+ assert [w.folder for w in loaded.workspaces] == [str(first), str(second)]+ assert loaded.terminal_count == 4+++def test_the_offer_reports_each_workspace_separately(tmp_path: Path) -> None:+ alive, gone = tmp_path / "alive", tmp_path / "deleted"+ alive.mkdir()+ view = resume_store.offer(+ _snapshot_of(_workspace(str(alive)), _workspace(str(gone))),+ installed={"claude", "codex"},+ )+ # One can come back, one cannot — and the whole offer is still usable.+ assert view["available"] is True+ assert view["workspace_count"] == 2+ assert view["terminal_count"] == 4+ assert view["workspaces"][0]["available"] is True+ assert view["workspaces"][1]["available"] is False+ assert view["workspaces"][1]["folder_exists"] is False++def test_a_pane_without_a_name_is_dropped_not_fatal(tmp_path: Path) -> None:"""One damaged entry must not cost the whole workspace."""resume_store.save(_snapshot(str(tmp_path)))@@ -88,25 +152,18 @@ def test_a_pane_without_a_name_is_dropped_not_fatal(tmp_path: Path) -> None:encoding="utf-8",)loaded = resume_store.load()- assert loaded is not None and [t.name for t in loaded.terminals] == ["Alex"]+ assert loaded is not None and [t.name for t in loaded.workspaces[0].terminals] == ["Alex"]def test_a_snapshot_without_terminals_is_not_an_offer(tmp_path: Path) -> None:- empty = resume_store.Snapshot(- session_id="ide_x", folder=str(tmp_path), saved_at=1.0, terminals=[]- )- resume_store.save(empty)+ resume_store.save(resume_store.Snapshot(saved_at=1.0, workspaces=[]))assert resume_store.load() is Nonedef test_saving_an_empty_workspace_withdraws_the_old_offer(tmp_path: Path) -> None:"""Closing the last pane must not leave yesterday's workspace on offer."""resume_store.save(_snapshot(str(tmp_path)))- resume_store.save(- resume_store.Snapshot(- session_id="ide_x", folder=str(tmp_path), saved_at=2.0, terminals=[]- )- )+ resume_store.save(resume_store.Snapshot(saved_at=2.0, workspaces=[]))assert resume_store.load() is None@@ -130,13 +187,12 @@ def test_a_failed_write_leaves_the_previous_snapshot_readable(monkeypatch.setattr(resume_store.os, "replace", _fail)resume_store.save(- resume_store.Snapshot(- session_id="ide_other",- folder=str(tmp_path),- saved_at=999.0,- terminals=[- resume_store.SnapshotTerminal(key="x", name="X", agent="claude")- ],+ _snapshot_of(+ resume_store.SnapshotWorkspace(+ session_id="ide_other",+ folder=str(tmp_path),+ terminals=[resume_store.SnapshotTerminal(key="x", name="X", agent="claude")],+ )))assert target.read_text(encoding="utf-8") == before@@ -164,12 +220,18 @@ def test_two_threads_saving_at_once_do_not_lose_the_write(tmp_path: Path) -> Nonfor _ in range(10):resume_store.save(resume_store.Snapshot(- session_id=f"ide_{index}",- folder=str(tmp_path),saved_at=float(index),- terminals=[- resume_store.SnapshotTerminal(- key=f"t{index}", name=f"T{index}", agent="claude"+ workspaces=[+ resume_store.SnapshotWorkspace(+ session_id=f"ide_{index}",+ folder=str(tmp_path),+ terminals=[+ resume_store.SnapshotTerminal(+ key=f"t{index}",+ name=f"T{index}",+ agent="claude",+ )+ ],)],)@@ -186,7 +248,7 @@ def test_two_threads_saving_at_once_do_not_lose_the_write(tmp_path: Path) -> Nonassert errors == []# Whoever won, the file is a COMPLETE snapshot and not a torn one.loaded = resume_store.load()- assert loaded is not None and len(loaded.terminals) == 1+ assert loaded is not None and len(loaded.workspaces[0].terminals) == 1assert list(resume_store._store_path().parent.glob("*.tmp-*")) == []@@ -197,9 +259,10 @@ def test_the_offer_reports_what_will_actually_come_back(existing_conversation("u-1")view = resume_store.offer(_snapshot(str(tmp_path)), installed={"claude"})assert view["available"] is True- assert view["folder_exists"] is True- assert view["folder_name"] == tmp_path.name- panes = {p["name"]: p for p in view["terminals"]}+ space = view["workspaces"][0]+ assert space["folder_exists"] is True+ assert space["folder_name"] == tmp_path.name+ panes = {p["name"]: p for p in space["terminals"]}# Alex has a handle and its CLI is here -> the conversation comes back.assert panes["Alex"]["resumable"] is Trueassert panes["Alex"]["available"] is True@@ -212,26 +275,26 @@ def test_the_offer_reports_what_will_actually_come_back(def test_the_offer_keeps_the_grid_coordinates(tmp_path: Path) -> None:view = resume_store.offer(_snapshot(str(tmp_path)), installed={"claude", "codex"})- assert [(p["column"], p["slot"]) for p in view["terminals"]] == [(0, 0), (1, 0)]+ panes = view["workspaces"][0]["terminals"]+ assert [(p["column"], p["slot"]) for p in panes] == [(0, 0), (1, 0)]def test_a_vanished_folder_is_reported_not_raised(tmp_path: Path) -> None:- view = resume_store.offer(- _snapshot(str(tmp_path / "deleted")), installed={"claude", "codex"}- )+ view = resume_store.offer(_snapshot(str(tmp_path / "deleted")), installed={"claude", "codex"})assert view["available"] is False- assert view["folder_exists"] is False+ assert view["workspaces"][0]["folder_exists"] is Falsedef test_a_machine_without_any_coding_cli_is_told_so(tmp_path: Path) -> None:"""A fresh install elsewhere: never a crash, never a false promise."""view = resume_store.offer(_snapshot(str(tmp_path)), installed=set())assert view["available"] is False- assert all(p["available"] is False for p in view["terminals"])+ panes = view["workspaces"][0]["terminals"]+ assert all(p["available"] is False for p in panes)assert view["resumable_count"] == 0def test_no_snapshot_yields_an_empty_offer() -> None:view = resume_store.offer(None, installed={"claude"})assert view["available"] is False- assert view["terminals"] == []+ assert view["workspaces"] == []