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): keep several workspaces open at once

Ruben Lütke32347f6a5b47
diff --git a/jarvis/agentic_ide/file_index.py b/jarvis/agentic_ide/file_index.py
index ebc3d47da9..45d8ac430d 100644
--- a/jarvis/agentic_ide/file_index.py
+++ b/jarvis/agentic_ide/file_index.py
@@ -262,8 +262,11 @@ def build_index(root: str | Path) -> FileIndex:
return index
-# One cached index per folder. Small on purpose: a session opens one workspace,
-# and holding a stale index for every folder ever browsed would be a slow leak.
+# One cached index per folder. Keyed rather than global because several
+# workspaces can be open at once, and each one's `@file` suggestions must come
+# from ITS tree — a shared slot would hand the agent in one workspace the file
+# list of another. Small on purpose: entries are dropped when their workspace
+# closes, so this never grows into a stale index of every folder ever browsed.
_CACHE: dict[str, FileIndex] = {}
_BUILDING: set[str] = set()
_LOCK = threading.Lock()
@@ -301,8 +304,22 @@ def prime_index(root: str | Path) -> None:
threading.Thread(target=_run, name="agentic-ide-file-index", daemon=True).start()
+def forget_index(root: str | Path) -> None:
+ """Drop the cached index for ONE folder — its workspace just closed.
+
+ Per-folder rather than a blanket reset, because closing one workspace must
+ leave the others' suggestions intact. A build still in flight is left to
+ finish and re-populate the cache; it is a few kilobytes of index for a
+ folder nobody is looking at, and interrupting a worker thread to save that
+ is the worse trade.
+ """
+ key = str(Path(root).expanduser())
+ with _LOCK:
+ _CACHE.pop(key, None)
+
+
def reset_cache() -> None:
- """Drop every cached index — tests, and when a workspace closes."""
+ """Drop EVERY cached index — tests, and when the last workspace closes."""
with _LOCK:
_CACHE.clear()
_BUILDING.clear()
@@ -312,6 +329,7 @@ __all__ = [
"FileIndex",
"build_index",
"cached_index",
+ "forget_index",
"prime_index",
"reset_cache",
"tokenize",
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index d7099f9b03..d75b1e67e4 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -1,10 +1,10 @@
-"""In-process state of the Agentic-IDE workspace.
+"""In-process state of the Agentic-IDE workspaces.
-One registry holds at most one *session*: a chosen folder plus N named
-terminals, each running a coding-agent CLI (Claude Code / Codex) in a real
-pseudo-terminal rooted in that folder. The registry is what makes the feature
-more than an embedded terminal grid — it is the thing Jarvis reads from and
-writes to:
+One registry holds several *sessions*, one of which is *active*. A session is a
+chosen folder plus N named terminals, each running a coding-agent CLI (Claude
+Code / Codex) in a real pseudo-terminal rooted in that folder. The registry is
+what makes the feature more than an embedded terminal grid — it is the thing
+Jarvis reads from and writes to:
* **reads** — every terminal keeps a sanitized transcript, so "what is Mika
doing?" is answered from what Mika actually printed, not from a guess,
@@ -12,6 +12,19 @@ writes to:
(voice, chat, CLI), which is how you talk to an agent without touching the
keyboard.
+Only one workspace is on screen at a time, and ``session`` — the property every
+other layer reads — is always that one. Voice, the brain's context, the prompt
+composer and the CLI therefore keep asking exactly one question ("the workspace
+I am looking at") and never had to learn that there are others.
+
+**A workspace lives until it is closed.** Looking away is not closing: the panes
+of a workspace you switched off stay attached to their running agents, which is
+the entire point of having more than one. Only ``end`` (and app shutdown) stops
+an agent, and every open workspace is visible in the UI's workspace bar — so
+nothing runs unwatched in a way the user cannot see. Coming back re-binds the
+running PTY instead of restarting it, and replays the pane's raw output so the
+screen is the one you left (see ``attach`` and ``ReplayBuffer``).
+
Security posture of the write path (this is a keystroke channel into a running
process, so it is bounded deliberately):
@@ -61,7 +74,7 @@ from .agent_sessions import (
)
from .folders import ProjectProfile, probe_project
from .names import default_names, normalize, resolve
-from .transcript import Transcript
+from .transcript import ReplayBuffer, Transcript
if TYPE_CHECKING: # pragma: no cover - typing only
from jarvis.terminal.pty_manager import PtyManager
@@ -72,14 +85,30 @@ if TYPE_CHECKING: # pragma: no cover - typing only
AGENT_BINARIES: dict[str, str] = {"claude": "claude", "codex": "codex"}
AGENT_DISPLAY: dict[str, str] = {"claude": "Claude Code", "codex": "Codex"}
-MAX_TERMINALS = 12
+# How many panes one workspace may hold.
+#
+# Raised from 12 on maintainer directive (2026-07-26): "you can open as many as
+# you want". 12 was a product opinion dressed up as a limit, and it was wrong —
+# how many agents are useful is the user's call, not this module's.
+#
+# A number remains, and it is deliberately far above any real use: this is a
+# RUNAWAY GUARD, not a product ceiling. Every pane is a real coding-agent
+# process with its own memory, CPU and API spend, so a mistyped "500" in the
+# count field must not take the machine down before anyone can click away.
+# Nobody reaches 100 deliberately; anyone who mistypes their way past it gets a
+# sentence instead of a frozen desktop.
+MAX_TERMINALS = 100
# Transport ceiling for one injected prompt. Raised from 4000 once composed
-# prompts became structured briefs that describe the code they point at:
-# measured live at 2865-3713 characters, so 4000 meant the cap - not the
-# writer - was deciding where a brief ended. Bracketed paste delivers the whole
-# block in one write, so length costs nothing on this channel; the real limit
-# is the pane's readability.
+# prompts became structured briefs that describe the code they point at: at
+# 4000 the cap, not the writer, was deciding where a brief ended. Bracketed
+# paste delivers the whole block in one write, so length costs nothing here —
+# the real limit is the pane's readability, not the channel.
MAX_PROMPT_CHARS = 6000
+# How many workspaces may be open at once. Not a technical ceiling — a real one
+# costs a folder's worth of running coding agents, so the cap exists to keep an
+# accidental click from spawning them, and the number is what still fits in a
+# row of tabs the user can read.
+MAX_WORKSPACES = 6
# Delay between the prompt text and the Enter keystroke. Agent TUIs debounce
# fast bursts as a paste; ~120 ms is past every debounce window measured while
# still feeling instant.
@@ -317,7 +346,25 @@ class Terminal:
# 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
+ # Did the last viewer re-join an agent that never stopped (rather than
+ # starting one)? A different claim from `resumed`, and both are worth
+ # telling apart on screen: "continued its conversation" means a NEW process
+ # picked up an old transcript, "still running" means the same process has
+ # been working the whole time you were looking somewhere else.
+ reattached: bool = False
transcript: Transcript = field(default_factory=Transcript)
+ # The RAW output stream, kept so the next viewer can be handed the screen
+ # this pane is actually showing. Cleared on a fresh spawn, so what a viewer
+ # replays always belongs to the process it is now watching.
+ replay: ReplayBuffer = field(default_factory=ReplayBuffer)
+ # Where this pane's output currently goes, or None while nobody is looking.
+ #
+ # A mutable slot rather than a closure captured at spawn time, and that is
+ # what makes switching workspaces survivable: the agent keeps running with
+ # no viewer, and a new viewer takes the slot without the PTY ever noticing.
+ # Bound at spawn, cleared on detach, replaced on re-attach.
+ viewer_output: Any = None
+ viewer_exit: Any = None
def to_dict(self) -> dict[str, Any]:
return {
@@ -373,6 +420,14 @@ class Session:
# current session, and a restart should land the user back in normal mode
# rather than silently keeping a narrowed assistant.
focus_mode: bool = False
+ # When this workspace was last brought to the front. Orders the "most
+ # recently used" answer the resume snapshot and the UI both want, which is
+ # NOT the order the workspaces were opened in.
+ last_active_at: float = 0.0
+ # Background session-id lookups belonging to THIS workspace. Held so the
+ # loop cannot garbage-collect one mid-flight, and per session rather than
+ # per registry so closing one workspace cannot cancel another's.
+ lookups: set[asyncio.Task[None]] = field(default_factory=set)
def find(self, wanted: str) -> Terminal | None:
"""Terminal by key, call-sign, or a spoken phrase containing one."""
@@ -397,34 +452,88 @@ class Session:
"terminals": [t.to_dict() for t in self.terminals],
}
+ def to_card(self, *, active: bool) -> dict[str, Any]:
+ """This workspace as one tab in the workspace bar.
+
+ Deliberately not ``to_dict``: a bar of six tabs would otherwise carry
+ six full project profiles and every pane's transcript statistics on
+ every poll, to render a name and a number.
+ """
+ live = sum(1 for t in self.terminals if t.status == "live")
+ return {
+ "id": self.id,
+ "folder": self.folder,
+ "name": self.profile.name or Path(self.folder).name or self.folder,
+ "branch": self.profile.branch,
+ "terminals": len(self.terminals),
+ "live_terminals": live,
+ "focus_mode": self.focus_mode,
+ "created_at": self.created_at,
+ "last_active_at": self.last_active_at,
+ "active": active,
+ }
+
class SessionError(RuntimeError):
"""A request the registry refuses, with a user-facing English message."""
class Registry:
- """Process-wide holder of the single active Agentic-IDE session."""
+ """Process-wide holder of the open Agentic-IDE workspaces.
+
+ Several may be open; exactly one (or none) is *active*, and that is the one
+ on screen. ``session`` is always the active one, so every layer that only
+ ever cared about "the workspace" keeps working unchanged — the others are
+ reachable through ``sessions`` and are only ever addressed by id.
+ """
def __init__(self, pty_manager: PtyManager | None = None) -> None:
- self._session: Session | None = None
+ # Insertion-ordered: this is also the left-to-right order of the tabs,
+ # so a workspace never jumps position because something about it
+ # changed.
+ self._sessions: dict[str, Session] = {}
+ self._active: str | None = None
# Injectable so tests can drive the registry against a fake PTY pool
# 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
def session(self) -> Session | None:
- return self._session
+ """The workspace on screen, or None while the wizard is showing."""
+ if self._active is None:
+ return None
+ return self._sessions.get(self._active)
+
+ @property
+ def sessions(self) -> list[Session]:
+ """Every open workspace, in tab order."""
+ return list(self._sessions.values())
+
+ @property
+ def active_id(self) -> str | None:
+ return self._active
+
+ def get(self, workspace_id: str | None) -> Session | None:
+ """One workspace by id; without an id, the active one."""
+ if workspace_id is None:
+ return self.session
+ return self._sessions.get(workspace_id)
+
+ def workspaces(self) -> list[dict[str, Any]]:
+ """Every open workspace as a tab card, in tab order."""
+ return [s.to_card(active=s.id == self._active) for s in self._sessions.values()]
def state(self) -> dict[str, Any]:
+ session = self.session
return {
- "active": self._session is not None,
- "session": self._session.to_dict() if self._session else None,
+ "active": session is not None,
+ "session": session.to_dict() if session else None,
"max_terminals": MAX_TERMINALS,
+ "max_workspaces": MAX_WORKSPACES,
+ "active_id": self._active,
+ "workspaces": self.workspaces(),
}
def _manager(self) -> PtyManager:
@@ -439,10 +548,16 @@ class Registry:
async def start(
self, folder: str, requested: list[dict[str, Any]]
) -> Session:
- """Create a session for ``folder`` with one terminal per request entry.
+ """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.
"""
async with self._lock:
if not requested:
@@ -464,6 +579,22 @@ 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 "
+ "before opening another."
+ )
+
unknown = {str(r.get("agent")) for r in requested} - set(AGENT_BINARIES)
if unknown:
raise SessionError(f"Unknown agent(s): {', '.join(sorted(unknown))}")
@@ -482,17 +613,21 @@ class Registry:
"Install it from the CLIs page, then try again."
)
- # Close a previous session before replacing it, or its PTYs leak.
- # 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()
+ # Call-signs are unique across ALL open workspaces, not just within
+ # this one. A name is how the user addresses a pane out loud, and a
+ # second "Mika" two tabs over would make "tell Mika to run the
+ # tests" a question rather than an instruction. So the pool skips
+ # every name already spoken for, and this workspace simply starts
+ # further down it.
+ taken = self._reserved_names()
+ offered = default_names(len(requested) + len(taken))
+ pool = [n for n in offered if normalize(n) not in taken]
+ used: set[str] = set(taken)
terminals: list[Terminal] = []
for index, entry in enumerate(requested):
agent = str(entry.get("agent"))
- wanted = str(entry.get("name") or "").strip() or pool[index]
+ fallback = pool[index] if index < len(pool) else f"T{index + 1}"
+ wanted = str(entry.get("name") or "").strip() or fallback
name = wanted
suffix = 2
while normalize(name) in used:
@@ -520,14 +655,52 @@ class Registry:
)
return session
+ # ------------------------------------------------------- workspace helpers
+ def _find_by_folder(self, root: Path) -> Session | None:
+ """An open workspace on ``root``, or None.
+
+ Compared on the resolved path so ``~/code/app`` and ``/home/me/code/app``
+ are recognised as one folder, and case-insensitively on the platforms
+ where the filesystem itself is (Windows, and macOS by default) — asking
+ the OS rather than assuming, so a case-sensitive mac volume still gets
+ the right answer.
+ """
+ try:
+ wanted = root.expanduser().resolve()
+ except OSError:
+ wanted = root
+ for session in self._sessions.values():
+ try:
+ candidate = Path(session.folder).resolve()
+ except OSError:
+ candidate = Path(session.folder)
+ if candidate == wanted:
+ return session
+ if os.path.normcase(str(candidate)) == os.path.normcase(str(wanted)):
+ return session
+ return None
+
+ def _reserved_names(self) -> set[str]:
+ """Every call-sign in use across all open workspaces, normalized."""
+ return {
+ normalize(term.name)
+ for session in self._sessions.values()
+ for term in session.terminals
+ }
+
+ def _focus_locked(self, session: Session) -> None:
+ """Bring ``session`` to the front. Caller holds the lock."""
+ self._active = session.id
+ session.last_active_at = time.time()
+
async def _open_locked(self, root: Path, terminals: list[Terminal]) -> Session:
- """Turn a prepared list of panes into THE open 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
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.
+ callers hold ``self._lock``.
"""
profile = await asyncio.to_thread(probe_project, root)
@@ -549,7 +722,8 @@ class Registry:
terminals=terminals,
created_at=time.time(),
)
- self._session = session
+ self._sessions[session.id] = session
+ self._focus_locked(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
@@ -592,7 +766,20 @@ class Registry:
except OSError as exc:
raise SessionError(f"Cannot open {root}: {exc}") from exc
- await self._close_locked(forget=False)
+ 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
+
+ if len(self._sessions) >= MAX_WORKSPACES:
+ raise SessionError(
+ f"{MAX_WORKSPACES} workspaces are already open — close one "
+ "before reopening this."
+ )
terminals = [
Terminal(
@@ -608,6 +795,12 @@ class Registry:
)
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.
@@ -622,16 +815,90 @@ class Registry:
)
return session
- async def end(self) -> bool:
+ def _dedupe_names(self, terminals: list[Terminal]) -> None:
+ """Rename any call-sign already spoken for by another open workspace."""
+ used = self._reserved_names()
+ for term in terminals:
+ if normalize(term.name) not in used:
+ used.add(normalize(term.name))
+ continue
+ base, suffix = term.name, 2
+ while normalize(f"{base} {suffix}") in used:
+ suffix += 1
+ term.name = f"{base} {suffix}"
+ term.key = normalize(term.name) or term.key
+ used.add(normalize(term.name))
+
+ async def activate(self, workspace_id: str | None) -> Session | None:
+ """Bring one workspace to the front, or clear the front entirely.
+
+ ``None`` means "no workspace is on screen" — what the UI is in while the
+ wizard is open for an ADDITIONAL workspace. It is a real state, not a
+ close: every workspace stays open with its agents running, and the panes
+ that go off screen simply let go of their viewers.
+
+ Answering before the panes come down is what makes a switch safe: the
+ panes of the outgoing workspace disconnect *after* this call, by which
+ time it is no longer the front one, and nothing treats their departure
+ as a reason to stop an agent.
+ """
+ async with self._lock:
+ if workspace_id is None:
+ self._active = None
+ return None
+ session = self._sessions.get(workspace_id)
+ if session is None:
+ raise SessionError("That workspace is not open any more.")
+ self._focus_locked(session)
+ # The front workspace is the one worth offering back after a
+ # restart, so switching re-points the restore snapshot at it.
+ await self._persist()
+ logger.info("Agentic IDE: switched to {}", session.folder)
+ 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 the
+ toolbar's Close button and the existing CLI/API callers mean. Returns
+ False when there was nothing to close.
+ """
+ async with self._lock:
+ target = workspace_id if workspace_id is not None else self._active
+ if target is None or target not in self._sessions:
+ if not self._sessions:
+ await self._forget()
+ return False
+ await 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 True
+
+ async def close_all(self) -> int:
+ """Close every open workspace. Returns how many were closed."""
async with self._lock:
- existed = self._session is not None
- await self._close_locked(forget=True)
- return existed
+ count = len(self._sessions)
+ for workspace_id in list(self._sessions):
+ await self._close_locked(workspace_id)
+ if count:
+ await self._forget()
+ return count
# ------------------------------------------------------------- snapshot
def snapshot(self) -> resume_store.Snapshot | None:
- """The open workspace in the form the resume store keeps it, or None."""
- session = self._session
+ """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.
+ """
+ session = self.session
if session is None:
return None
return resume_store.snapshot_now(
@@ -662,31 +929,32 @@ class Registry:
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.
+ async def _close_locked(self, workspace_id: str) -> None:
+ """Tear ONE workspace down: stop its agents and drop it from the bar.
+
+ This is the only place an agent is stopped on the user's behalf, and
+ that is deliberate. Panes come and go constantly — a switch to another
+ workspace, a browser reload, a closed tab — and none of those mean "stop
+ working". Closing does.
- 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.
+ The restore point is re-pointed rather than withdrawn: whatever is still
+ open moves to the front and writes its own snapshot, so the next restart
+ offers a workspace that actually exists. Closing the LAST one withdraws
+ it (in ``end``), because re-offering something deliberately shut down is
+ the kind of prompt people learn to dismiss without reading.
"""
- for task in list(self._lookups):
- task.cancel()
- self._lookups.clear()
- session = self._session
- self._session = None
+ session = self._sessions.pop(workspace_id, None)
if session is None:
- if forget:
- await self._forget()
return
- if forget:
- await self._forget()
+ for task in list(session.lookups):
+ task.cancel()
+ session.lookups.clear()
+
manager = self._pty
for term in session.terminals:
term.stopping = True # deliberate kills, not crashed resumes
+ term.viewer_output = None
+ term.viewer_exit = None
if manager is not None:
for term in session.terminals:
if term.pty_id:
@@ -694,19 +962,34 @@ class Registry:
manager.close(term.pty_id)
except Exception: # noqa: BLE001, S110 - best-effort teardown
pass
- # Drop the codebase index with the workspace: keeping it would hand the
- # next session a snapshot of a folder that may have changed since.
+ # 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
- file_index.reset_cache()
+ file_index.forget_index(session.folder)
except Exception: # noqa: BLE001, S110 - best-effort teardown
pass
+
+ if self._active == workspace_id:
+ # Hand the front to the most recently used survivor rather than to
+ # whatever happens to be first: closing the tab you were in should
+ # land you on the one you were in before it, not at the far end.
+ survivor = max(
+ self._sessions.values(),
+ key=lambda s: s.last_active_at,
+ default=None,
+ )
+ self._active = survivor.id if survivor else None
+ if survivor is not None:
+ self._focus_locked(survivor)
+ await self._persist()
logger.info("Agentic IDE session ended: {}", session.id)
def set_focus_mode(self, enabled: bool) -> bool:
"""Turn the focused coding mode on/off. Returns the resulting state."""
- session = self._session
+ session = self.session
if session is None:
if enabled:
raise SessionError(
@@ -718,15 +1001,45 @@ class Registry:
return session.focus_mode
# ------------------------------------------------------------------ pty
+ 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
+ caller passes, because its socket belongs to the workspace it opened in
+ and not to whichever one happens to be at the front by the time a
+ message arrives. Without one, the front workspace answers.
+ """
+ session = self.get(workspace_id)
+ if session is None:
+ return None
+ term = session.find(key)
+ return None if term is None else (session, term)
+
async def attach(
- self, key: str, cols: int, rows: int, on_output: Any, on_exit: Any
+ self,
+ key: str,
+ cols: int,
+ rows: int,
+ on_output: Any,
+ on_exit: Any,
+ workspace_id: str | None = None,
) -> Terminal:
- """Spawn the agent for terminal ``key`` and stream it to the caller.
+ """Point a viewer at terminal ``key``, starting its agent if needed.
``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.
+ **A running agent is re-joined, never restarted.** A pane whose PTY is
+ still alive — the normal case after switching workspaces, reloading the
+ browser, or coming back to the section — hands its output to the new
+ viewer and replays what it has been printing meanwhile, so the screen
+ comes back as it was. Restarting instead would throw away work in
+ progress every time somebody looked away, which is precisely what having
+ several workspaces would otherwise cost.
+
**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
@@ -742,19 +1055,33 @@ class Registry:
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:
- raise SessionError("No Agentic-IDE session is running.")
- term = session.find(key)
- if term is None:
+ found = self._locate(key, workspace_id)
+ if found is None:
+ if self.get(workspace_id) is None:
+ raise SessionError("No Agentic-IDE session is running.")
raise SessionError(f"Unknown terminal: {key}")
+ session, term = found
manager = self._manager()
if term.pty_id and manager.has(term.pty_id):
- # A second viewer for a pane that is already running: close the old
- # PTY rather than silently running two agents for one call-sign.
- manager.close(term.pty_id)
- term.pty_id = None
+ # The agent never stopped. Take over the viewer slot — the previous
+ # viewer, if any, is gone by definition (a socket that closed) or is
+ # being replaced by this one, so there is still exactly one.
+ term.viewer_output = on_output
+ term.viewer_exit = on_exit
+ term.reattached = True
+ term.stopping = False
+ term.transcript.resize(cols, rows)
+ manager.resize(term.pty_id, cols, rows)
+ replay = term.replay.text()
+ if replay:
+ # Hand over the raw stream that drew the current screen. A
+ # coding agent's TUI is a painted surface, not a log: without
+ # this the pane comes back blank until the agent happens to
+ # repaint, which looks exactly like a dead terminal.
+ await on_output(replay)
+ logger.debug("Agentic IDE: {} re-joined a running agent", term.name)
+ return term
argv = agent_argv(term.agent)
if argv is None:
@@ -787,6 +1114,13 @@ class Registry:
term.resume = minted
term.transcript.resize(cols, rows)
+ # A fresh process draws a fresh screen: anything the previous one left
+ # in the replay buffer belongs to a terminal that no longer exists, and
+ # replaying it to the next viewer would show output from a dead agent.
+ term.replay.clear()
+ term.viewer_output = on_output
+ term.viewer_exit = on_exit
+ term.reattached = False
# This pane is wanted again, so the last deliberate kill is history.
term.stopping = False
# Monotonic: a wall clock can jump (NTP, a laptop waking up) and would
@@ -794,10 +1128,18 @@ class Registry:
spawned_at = time.monotonic()
recovered = False
+ # Both callbacks go through the pane's viewer SLOT rather than through
+ # the on_output/on_exit captured here. The PTY outlives its viewers —
+ # that is what makes switching workspaces safe — so a closure pinned to
+ # the viewer that happened to start the agent would keep writing into a
+ # dead socket forever, and the viewer that came later would see nothing.
async def _output(_tid: str, text: str) -> None:
term.transcript.feed(text)
+ term.replay.feed(text)
term.last_output_at = time.time()
- await on_output(text)
+ viewer = term.viewer_output
+ if viewer is not None:
+ await viewer(text)
async def _closed(_tid: str, code: int) -> None:
nonlocal recovered
@@ -824,7 +1166,14 @@ class Registry:
term.resume = None
term.resumed = False
try:
- await self.attach(key, cols, rows, on_output, on_exit)
+ await self.attach(
+ key,
+ cols,
+ rows,
+ term.viewer_output or on_output,
+ term.viewer_exit or on_exit,
+ workspace_id=session.id,
+ )
except SessionError as exc:
logger.warning(
"Agentic IDE: {} could not be restarted: {}", term.name, exc
@@ -835,7 +1184,9 @@ class Registry:
return
term.status = "exited"
term.exit_code = code
- await on_exit(code)
+ viewer = term.viewer_exit
+ if viewer is not None:
+ await viewer(code)
try:
pty_session = await manager.spawn(
@@ -861,25 +1212,32 @@ class Registry:
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)
+ self._schedule_lookup(session, term, session.folder, term.started_at)
await self._persist()
return term
- def _schedule_lookup(self, term: Terminal, folder: str, started_at: float) -> None:
+ def _schedule_lookup(
+ self, owner: Session, 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.
+
+ Bound to the workspace that owns the pane rather than to "the current
+ one": with several open, the front workspace can change twice while this
+ is sleeping, and a lookup that then read the front one would write a
+ Codex conversation id onto a pane in a different folder.
"""
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:
+ if term not in owner.terminals or owner.id not in self._sessions:
return # the pane (or the workspace) is gone
+ session = owner
if term.resume is not None:
return
taken = {
@@ -904,47 +1262,53 @@ class Registry:
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)
+ owner.lookups.add(task)
+ task.add_done_callback(owner.lookups.discard)
- def write(self, key: str, data: str) -> bool:
+ def write(self, key: str, data: str, workspace_id: str | None = None) -> bool:
"""Raw keystrokes from the pane's own xterm (not the injection path)."""
- session = self._session
- if session is None:
+ found = self._locate(key, workspace_id)
+ if found is None:
return False
- term = session.find(key)
- if term is None or not term.pty_id:
+ term = found[1]
+ if not term.pty_id:
return False
return self._manager().write(term.pty_id, data)
- def resize(self, key: str, cols: int, rows: int) -> bool:
- session = self._session
- if session is None:
+ 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
- term = session.find(key)
- if term is None or not term.pty_id:
+ term = found[1]
+ if not term.pty_id:
return False
# The replayed screen has to follow the real one; otherwise the
# transcript keeps wrapping at the old width.
term.transcript.resize(cols, rows)
return self._manager().resize(term.pty_id, cols, rows)
- def detach(self, key: str) -> None:
- """Close the PTY behind a pane (the viewer went away)."""
- session = self._session
- if session is None:
- return
- term = session.find(key)
- if term is None or not term.pty_id:
+ def detach(self, key: str, workspace_id: str | None = None) -> None:
+ """Let go of a pane's viewer. The agent behind it keeps running.
+
+ Detaching used to kill the PTY, on the reasoning that an agent nobody
+ watches burns tokens invisibly. With several workspaces that reasoning
+ inverts: a viewer disappears every time you switch tab, reload the page
+ or walk over to the chat view, and none of those mean "stop working" —
+ killing there would throw away work in progress several times an hour.
+
+ So the lifetime rule is the one a user can actually predict: **an agent
+ runs until its workspace is closed.** Nothing is invisible about it —
+ every open workspace is a tab with a live-pane count on it, and closing
+ one stops its agents immediately (see ``_close_locked``).
+ """
+ found = self._locate(key, workspace_id)
+ if found is None:
return
- # Announce the kill before making it, or the exit it causes reads as a
- # crashed resume and the pane gets helpfully restarted behind the back
- # of the person who just closed it.
- term.stopping = True
- self._manager().close(term.pty_id)
- term.pty_id = None
- if term.status == "live":
- term.status = "exited"
+ term = found[1]
+ term.viewer_output = None
+ term.viewer_exit = None
# ------------------------------------------------------------- panes
async def add_terminal(
@@ -968,7 +1332,7 @@ class Registry:
installed agent, which is how the UI offers a choice of coding CLI.
"""
async with self._lock:
- session = self._session
+ session = self.session
if session is None:
raise SessionError("No Agentic-IDE session is running.")
if len(session.terminals) >= MAX_TERMINALS:
@@ -991,12 +1355,14 @@ class Registry:
pretty = AGENT_DISPLAY.get(chosen, chosen)
raise SessionError(f"{pretty} is not installed or not on this machine's PATH.")
- used = {normalize(t.name) for t in session.terminals}
+ # Unused ACROSS every open workspace: a split must not hand this
+ # pane a call-sign another tab already answers to.
+ used = self._reserved_names()
wanted = (name or "").strip()
if not wanted:
# Next unused call-sign from the pool, so names stay speakable
# however many times the user splits.
- pool = default_names(MAX_TERMINALS * 2)
+ pool = default_names(MAX_TERMINALS * MAX_WORKSPACES)
wanted = next(
(n for n in pool if normalize(n) not in used),
f"T{len(session.terminals) + 1}",
@@ -1065,7 +1431,7 @@ class Registry:
A failure with NOTHING opened is — an unknown agent or a vanished binary
must not be reported as "nothing to do".
"""
- if self._session is None:
+ if self.session is None:
raise SessionError("No Agentic-IDE session is running.")
wanted = max(1, int(count))
created: list[Terminal] = []
@@ -1087,7 +1453,7 @@ class Registry:
async def close_terminal(self, wanted: str) -> Terminal:
"""Stop one terminal's agent and remove its pane from the workspace."""
async with self._lock:
- session = self._session
+ session = self.session
if session is None:
raise SessionError("No Agentic-IDE session is running.")
term = session.find(wanted)
@@ -1103,6 +1469,8 @@ class Registry:
pass
term.pty_id = None
term.status = "exited"
+ term.viewer_output = None
+ term.viewer_exit = None
session.terminals.remove(term)
self._renumber(session)
await self._persist()
@@ -1161,13 +1529,10 @@ class Registry:
prompt sanitizes down to nothing. A prompt that was typed but refused to
submit is NOT an error — the text is in the box and the caller is told.
"""
- session = self._session
- if session is None:
- raise SessionError("No Agentic-IDE session is running.")
- term = session.find(wanted)
- if term is None:
- known = ", ".join(t.name for t in session.terminals) or "none"
- raise SessionError(f"No terminal called {wanted!r}. Running: {known}.")
+ found = self.find_terminal(wanted)
+ if found is None:
+ raise self._unknown_terminal(wanted)
+ _session, term = found
if term.status != "live" or not term.pty_id:
raise SessionError(
f"{term.name} is not running right now "
@@ -1256,18 +1621,55 @@ class Registry:
def report(self, wanted: str, lines: int = 40) -> dict[str, Any]:
"""What one terminal has been up to — the answer to "what is X doing?"."""
- session = self._session
- if session is None:
- raise SessionError("No Agentic-IDE session is running.")
- term = session.find(wanted)
- if term is None:
- known = ", ".join(t.name for t in session.terminals) or "none"
- raise SessionError(f"No terminal called {wanted!r}. Running: {known}.")
+ found = self.find_terminal(wanted)
+ if found is None:
+ raise self._unknown_terminal(wanted)
+ session, term = found
data = term.to_dict()
data["folder"] = session.folder
+ # Which workspace answered. With several open, "Kai is running the
+ # tests" is only half an answer if Kai lives in a different folder than
+ # the one on screen.
+ data["workspace_id"] = session.id
+ data["workspace"] = session.profile.name or Path(session.folder).name
data["transcript"] = term.transcript.tail(max(1, min(lines, 300)))
return data
+ # -------------------------------------------------------- name resolution
+ def find_terminal(self, wanted: str) -> tuple[Session, Terminal] | None:
+ """A pane by call-sign, anywhere — the front workspace answering first.
+
+ Call-signs are unique across open workspaces (see ``start``), so a name
+ identifies exactly one pane and searching beyond the front one cannot be
+ ambiguous. It is also what a user means: "tell Kai to run the tests" is
+ an instruction to Kai, not a request to first go and find which tab Kai
+ is in. The front workspace is still tried first, so the common case
+ never depends on iteration order.
+ """
+ session = self.session
+ if session is not None:
+ term = session.find(wanted)
+ if term is not None:
+ return session, term
+ for other in self._sessions.values():
+ if session is not None and other.id == session.id:
+ continue
+ term = other.find(wanted)
+ if term is not None:
+ return other, term
+ return None
+
+ def _unknown_terminal(self, wanted: str) -> SessionError:
+ """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'}."
+ )
+
def terminals_added_event(
session: Session, created: list[Terminal], *, source_layer: str
@@ -1314,6 +1716,7 @@ __all__ = [
"ENTER_DELAY_S",
"MAX_PROMPT_CHARS",
"MAX_TERMINALS",
+ "MAX_WORKSPACES",
"Registry",
"Session",
"SessionError",
diff --git a/jarvis/agentic_ide/transcript.py b/jarvis/agentic_ide/transcript.py
index 7621b91be9..80f132e80d 100644
--- a/jarvis/agentic_ide/transcript.py
+++ b/jarvis/agentic_ide/transcript.py
@@ -25,6 +25,7 @@ is this agent working on?", and both keep the module dependency-free.
from __future__ import annotations
import re
+from collections import deque
from dataclasses import dataclass, field
from .screen import ScreenBuffer
@@ -124,4 +125,63 @@ class Transcript:
self.raw_chars = 0
-__all__ = ["Transcript", "strip_ansi", "is_noise"]
+"""How much raw PTY output a pane keeps for its next viewer.
+
+Enough to cover several full repaints of a coding agent's TUI, so a pane that
+is looked at again shows what it was showing rather than a black rectangle —
+and small enough that a dozen panes across a handful of workspaces stay a
+rounding error in memory (12 panes x 6 workspaces x 128 KB is under 10 MB).
+"""
+REPLAY_LIMIT_CHARS = 128 * 1024
+
+
+@dataclass(slots=True)
+class ReplayBuffer:
+ """The tail of a terminal's RAW output, kept for a viewer that comes back.
+
+ Separate from :class:`Transcript` because the two answer different
+ questions. The transcript is for a *reader*: escape sequences replayed onto
+ a screen and turned into readable rows. This is for a *terminal*: the exact
+ bytes, in order, so xterm on the other side can be handed them verbatim and
+ end up in the state the pane was in.
+
+ That distinction is load-bearing for switching workspaces. The agent keeps
+ running while nobody watches, so reconnecting has to reconstruct the screen
+ from something — and the only thing that reconstructs a full-screen TUI is
+ the stream that drew it. Cleaned-up text would come back as a wall of
+ prose where a framed, coloured interface used to be.
+
+ Bounded by total characters, dropping whole chunks from the front. A TUI
+ repaints itself constantly, so an old partial escape sequence at the very
+ front is overwritten within a frame; cutting mid-sequence instead would
+ leave the terminal in a broken colour/cursor state.
+ """
+
+ limit: int = REPLAY_LIMIT_CHARS
+ _chunks: deque[str] = field(default_factory=deque, init=False)
+ _size: int = field(default=0, init=False)
+
+ def feed(self, chunk: str) -> None:
+ if not chunk:
+ return
+ self._chunks.append(chunk)
+ self._size += len(chunk)
+ while self._size > self.limit and len(self._chunks) > 1:
+ self._size -= len(self._chunks.popleft())
+
+ def text(self) -> str:
+ """Everything kept, oldest first — ready to be written to a terminal."""
+ return "".join(self._chunks)
+
+ def clear(self) -> None:
+ self._chunks.clear()
+ self._size = 0
+
+
+__all__ = [
+ "REPLAY_LIMIT_CHARS",
+ "ReplayBuffer",
+ "Transcript",
+ "is_noise",
+ "strip_ansi",
+]
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index c57dad18e1..2bf37ea10e 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -6,11 +6,16 @@ routes, so a pane's behaviour and a spoken command can never drift apart.
Endpoints (prefix ``/api/agentic-ide``):
-* ``GET /state`` → current session (or none) + limits
+* ``GET /state`` → front workspace + every open one + limits
* ``GET /agents`` → Claude Code / Codex install status
* ``GET /folders`` → browse folders (no path = start points)
-* ``POST /session`` → open a workspace (folder + terminals)
-* ``DELETE /session`` → close it and stop every agent
+* ``GET /folders/native`` → can this machine show the OS folder window?
+* ``POST /folders/native`` → open it and return what was picked
+* ``GET /workspaces`` → every open workspace, in tab order
+* ``PUT /workspaces/active`` → bring one to the front (null = wizard)
+* ``DELETE /workspaces/{workspace_id}`` → close that one and stop its agents
+* ``POST /session`` → open ANOTHER workspace (folder + terminals)
+* ``DELETE /session`` → close the front one and stop every agent
* ``GET /resume`` → the last workspace, offered back
* ``POST /resume`` → reopen it (same panes, same places)
* ``DELETE /resume`` → forget it and start fresh
@@ -44,7 +49,7 @@ from fastapi import (
)
from pydantic import BaseModel, Field
-from jarvis.agentic_ide import recents, resume_store
+from jarvis.agentic_ide import native_picker, recents, resume_store
from jarvis.agentic_ide.agent_sessions import has_conversation
from jarvis.agentic_ide.device import device_name
from jarvis.agentic_ide.folders import list_dir, search_folders, start_points
@@ -53,18 +58,22 @@ from jarvis.agentic_ide.session import (
AGENT_DISPLAY,
MAX_PROMPT_CHARS,
MAX_TERMINALS,
+ MAX_WORKSPACES,
SessionError,
agent_argv,
get_registry,
terminals_added_event,
)
-from .surface_security import credentials_valid
+from .surface_security import credentials_valid, is_loopback_request
log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/agentic-ide", tags=["agentic-ide"])
+# One system folder window at a time — see ``open_native_picker``.
+_native_picker_lock = asyncio.Lock()
+
# --------------------------------------------------------------------------- #
# Models #
@@ -128,6 +137,42 @@ class ModeRequest(BaseModel):
)
+class ActivateWorkspaceRequest(BaseModel):
+ """Which workspace should be on screen."""
+
+ id: str | None = Field(
+ default=None,
+ description=(
+ "Workspace to bring to the front. Null means no workspace is shown "
+ "— what the UI is in while the wizard opens an additional one. "
+ "Nothing is closed either way."
+ ),
+ )
+
+
+class WorkspaceCard(BaseModel):
+ """One open workspace, as the workspace bar shows it."""
+
+ id: str
+ folder: str
+ name: str
+ branch: str | None = None
+ terminals: int
+ live_terminals: int = Field(
+ description="Panes whose agent is running right now, not just placed."
+ )
+ focus_mode: bool
+ created_at: float
+ last_active_at: float
+ active: bool
+
+
+class WorkspacesResponse(BaseModel):
+ workspaces: list[WorkspaceCard]
+ active_id: str | None = None
+ max_workspaces: int
+
+
class PromptRequest(BaseModel):
prompt: str = Field(
max_length=MAX_PROMPT_CHARS,
@@ -200,6 +245,33 @@ class RecentsResponse(BaseModel):
recents: list[RecentItem]
+class NativePickerSupport(BaseModel):
+ available: bool = Field(
+ description="Whether this machine can show the operating system's folder window."
+ )
+ backend: str | None = Field(
+ default=None, description="Which program would draw it (powershell, osascript, zenity, …)."
+ )
+ reason: str | None = Field(
+ default=None, description="Plain-language explanation when it is not available."
+ )
+
+
+class NativePickRequest(BaseModel):
+ start: str | None = Field(
+ default=None,
+ description="Folder the window should open at; ignored when it no longer exists.",
+ )
+
+
+class NativePickResponse(BaseModel):
+ path: str | None = Field(default=None, description="The chosen folder, if one was chosen.")
+ cancelled: bool = Field(
+ default=False, description="True when the user closed the window without choosing."
+ )
+ error: str | None = Field(default=None, description="Why no folder came back.")
+
+
class ResolveRequest(BaseModel):
path: str | None = Field(
default=None,
@@ -338,6 +410,73 @@ async def search(q: str, limit: int = 40) -> SearchResponse:
)
+ "/folders/native",
+ response_model=NativePickerSupport,
+ summary="Can this machine show the system folder window?",
+)
+async def native_picker_support(request: Request) -> NativePickerSupport:
+ """Whether ``POST /folders/native`` would actually put a window on a screen.
+
+ Asked before the button is offered, because a button that cannot work is
+ worse than no button. Two independent conditions, and the caller is told
+ which one failed:
+
+ * the machine has a desktop session and a program that can draw a dialog,
+ * the request came from this machine — the window opens where the SERVER
+ runs, so from another device it would appear on a screen nobody is
+ looking at and quietly wait there.
+ """
+ if not is_loopback_request(request.scope):
+ return NativePickerSupport(
+ available=False,
+ reason=(
+ "The folder window would open on the computer running Jarvis, not on "
+ "this one. Browse or paste a path instead."
+ ),
+ )
+ probe = await asyncio.to_thread(native_picker.support)
+ return NativePickerSupport(
+ available=probe.available, backend=probe.backend, reason=probe.reason
+ )
+
+
+ "/folders/native",
+ response_model=NativePickResponse,
+ summary="Open the system folder window",
+)
+async def open_native_picker(request: Request, req: NativePickRequest) -> NativePickResponse:
+ """Show the operating system's own folder dialog and return what was picked.
+
+ Cancelling is a normal outcome, not an error — the response says
+ ``cancelled`` and the wizard simply keeps whatever was selected before.
+
+ Only one window at a time: the dialog is modal to the person, not to the
+ process, so a second request while one is open would stack invisible windows
+ on the desktop and leave the user clicking through dialogs they never asked
+ for. The second caller is told to finish the first one (409).
+ """
+ if not is_loopback_request(request.scope):
+ raise HTTPException(
+ status_code=403,
+ detail=(
+ "The folder window can only be opened from the computer running Jarvis. "
+ "Browse to the folder or paste its path instead."
+ ),
+ )
+ if _native_picker_lock.locked():
+ raise HTTPException(
+ status_code=409,
+ detail="A folder window is already open — finish that one first.",
+ )
+ async with _native_picker_lock:
+ result = await asyncio.to_thread(native_picker.choose_folder, start=req.start)
+ return NativePickResponse(
+ path=result.path, cancelled=result.cancelled, error=result.error
+ )
+
+
@router.get("/recents", response_model=RecentsResponse, summary="Recently opened workspaces")
async def get_recents() -> RecentsResponse:
"""Workspaces opened before, newest first, with their previous layout."""
@@ -428,9 +567,59 @@ def _unwrap_file_uri(value: str) -> str:
return path
+ "/workspaces",
+ response_model=WorkspacesResponse,
+ summary="Open Agentic-IDE workspaces",
+)
+async def get_workspaces() -> WorkspacesResponse:
+ """Every open workspace, in tab order, with the front one marked.
+
+ Several can be open at once — a workspace is a folder plus its running
+ coding agents, and switching between them neither stops nor restarts
+ anything. This is the list the workspace bar renders; the full contents of
+ the front one come from ``GET /state``.
+ """
+ registry = get_registry()
+ return WorkspacesResponse(
+ workspaces=[WorkspaceCard(**card) for card in registry.workspaces()],
+ active_id=registry.active_id,
+ max_workspaces=MAX_WORKSPACES,
+ )
+
+
[email protected]("/workspaces/active", summary="Switch to another workspace")
+async def activate_workspace(req: ActivateWorkspaceRequest) -> dict:
+ """Bring one workspace to the front, or clear the front entirely.
+
+ Nothing starts, stops or restarts: the agents in every open workspace keep
+ working, and the one that comes forward reconnects its panes to the
+ processes that were running all along.
+
+ ``id: null`` means "show no workspace" — the state the UI is in while the
+ wizard opens an ADDITIONAL one. It is not a close, and the workspaces stay
+ in the bar.
+
+ ``404`` when that workspace is not open (any more).
+ """
+ try:
+ session = await get_registry().activate(req.id)
+ except SessionError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ return {
+ "ok": True,
+ "active_id": session.id if session else None,
+ "state": get_registry().state(),
+ }
+
+
@router.post("/session", summary="Open an Agentic-IDE workspace")
async def start_session(req: StartSessionRequest) -> dict:
- """Open ``folder`` with one named terminal per requested agent.
+ """Open ``folder`` as another workspace, with one terminal per request entry.
+
+ Whatever is already open STAYS open with its agents running — this adds a
+ workspace and brings it to the front. Opening a folder that already has one
+ switches to it instead of starting a second set of agents on the same tree.
The recent-folder history is updated here, at the user-facing open action,
rather than inside ``Registry.start``. Internal callers (especially unit
@@ -456,7 +645,7 @@ async def start_session(req: StartSessionRequest) -> dict:
)
except Exception: # noqa: BLE001 - history must never block opening a folder
log.warning("Agentic IDE recent-folder history was not updated", exc_info=True)
- return {"ok": True, "session": session.to_dict()}
+ return {"ok": True, "session": session.to_dict(), "state": get_registry().state()}
@router.delete(
@@ -465,9 +654,36 @@ async def start_session(req: StartSessionRequest) -> dict:
openapi_extra={"x-jarvis-dangerous": True},
)
async def end_session() -> dict:
- """Close the workspace and stop every agent running in it."""
+ """Close the workspace on screen and stop every agent running in it.
+
+ Other open workspaces are untouched; the most recently used of them takes
+ the front. Use ``DELETE /workspaces/{workspace_id}`` to close a specific
+ one instead of whichever is showing.
+ """
closed = await get_registry().end()
- return {"ok": True, "closed": closed}
+ return {"ok": True, "closed": closed, "state": get_registry().state()}
+
+
+ "/workspaces/{workspace_id}",
+ summary="Close one Agentic-IDE workspace",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def close_workspace(workspace_id: str) -> dict:
+ """Close the workspace with this id and stop every agent inside it.
+
+ The only action that stops an agent on the user's behalf. Switching away
+ from a workspace, reloading the page or closing the browser do NOT — an
+ agent runs until its workspace is closed, which is what makes the panes
+ still be there (still working) when you come back.
+
+ ``404`` when no workspace has that id.
+ """
+ registry = get_registry()
+ if registry.get(workspace_id) is None:
+ raise HTTPException(status_code=404, detail="That workspace is not open.")
+ await registry.end(workspace_id)
+ return {"ok": True, "closed": workspace_id, "state": registry.state()}
async def _installed_agents() -> set[str]:
@@ -719,17 +935,22 @@ async def terminal_attach(
from jarvis.agentic_ide import drops
registry = get_registry()
- session = registry.session
- if session is None:
- raise HTTPException(
- status_code=409, detail="No Agentic-IDE session is running."
- )
- term = session.find(name)
- if term is None:
- known = ", ".join(t.name for t in session.terminals) or "none"
+ # Resolved across every open workspace, not just the front one: call-signs
+ # are unique across them, and a file dropped on a pane belongs to THAT
+ # pane's folder — which is also where a copied file has to land.
+ found = registry.find_terminal(name)
+ if found is None:
+ if not registry.sessions:
+ raise HTTPException(
+ status_code=409, detail="No Agentic-IDE session is running."
+ )
+ known = ", ".join(
+ t.name for s in registry.sessions for t in s.terminals
+ ) or "none"
raise HTTPException(
status_code=404, detail=f"No terminal called {name!r}. Running: {known}."
)
+ session, term = found
references: list[str] = []
stored_names: list[str] = []
@@ -832,8 +1053,7 @@ async def terminal_prompt(name: str, req: PromptRequest) -> dict:
can show it for approval first.
"""
registry = get_registry()
- session = registry.session
- if session is None:
+ if not registry.sessions:
raise HTTPException(
status_code=409, detail="No Agentic-IDE session is running."
)
@@ -844,13 +1064,20 @@ async def terminal_prompt(name: str, req: PromptRequest) -> dict:
if req.compose:
from jarvis.agentic_ide.prompt_composer import compose as compose_prompt
- term_for_compose = session.find(name)
- if term_for_compose is None:
- known = ", ".join(t.name for t in session.terminals) or "none"
+ # The pane decides which workspace composes the prompt. Composition
+ # reads the codebase to attach `@file` references, and taking those
+ # from the front workspace while sending to a pane in another one would
+ # point the agent at files that are not in its tree.
+ found = registry.find_terminal(name)
+ if found is None:
+ known = ", ".join(
+ t.name for s in registry.sessions for t in s.terminals
+ ) or "none"
raise HTTPException(
status_code=404,
detail=f"No terminal called {name!r}. Running: {known}.",
)
+ session, term_for_compose = found
result = await compose_prompt(
req.prompt,
session=session,
@@ -913,6 +1140,13 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
Wire protocol (JSON both ways) — client: ``{t:"i",d}`` input,
``{t:"r",cols,rows}`` resize; server: ``{t:"o",d}`` output, ``{t:"ready"}``,
``{t:"exit",code}``, ``{t:"error",message}``.
+
+ The optional ``workspace`` query parameter names the workspace this pane
+ belongs to. It matters because several can be open and the front one changes
+ while sockets are alive: without it a keystroke arriving mid-switch would be
+ resolved against whichever workspace happens to be showing, and could land
+ in a pane in a different folder. Omitted, the front workspace answers (the
+ single-workspace case, and what older clients send).
"""
await ws.accept()
if not credentials_valid(ws.scope):
@@ -922,6 +1156,7 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
qp = ws.query_params
cols = _safe_int(qp.get("cols"), 80)
rows = _safe_int(qp.get("rows"), 24)
+ workspace_id = (qp.get("workspace") or "").strip() or None
registry = get_registry()
send_lock = asyncio.Lock()
@@ -940,8 +1175,18 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
except Exception: # noqa: BLE001, S110 - viewer gone
pass
+ # Pin the workspace ONCE, before anything is attached. A client that sent no
+ # id means "the one showing right now", and that has to be resolved here
+ # rather than on every later message: the front workspace can change while
+ # this socket is open, and a keystroke must keep going to the pane it was
+ # typed into.
+ pinned = registry.get(workspace_id)
+ pane_workspace = pinned.id if pinned is not None else None
+
try:
- term = await registry.attach(name, cols, rows, on_output, on_exit)
+ term = await registry.attach(
+ name, cols, rows, on_output, on_exit, workspace_id=pane_workspace
+ )
except SessionError as exc:
await ws.send_json({"t": "error", "message": str(exc)})
await ws.close(code=4404, reason="attach failed")
@@ -955,6 +1200,11 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
# Did this pane pick up its previous conversation, or start empty?
# The pane looks identical either way, so it has to be told.
"resumed": term.resumed,
+ # Or did nothing restart at all? A pane that re-joined an agent that
+ # never stopped is a third state, and the most common one once
+ # workspaces are switched between — saying "started a new
+ # conversation" there would be plainly false.
+ "reattached": term.reattached,
}
)
@@ -972,18 +1222,20 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
continue
kind = msg.get("t")
if kind == "i":
- registry.write(term.key, str(msg.get("d", "")))
+ registry.write(term.key, str(msg.get("d", "")), pane_workspace)
elif kind == "r":
registry.resize(
term.key,
_safe_int(msg.get("cols"), cols),
_safe_int(msg.get("rows"), rows),
+ pane_workspace,
)
finally:
- # The viewer closed the pane: stop the agent with it. Leaving an
- # orphaned agent running with nobody watching would burn tokens
- # invisibly, which is worse than having to restart the pane.
- registry.detach(term.key)
+ # The viewer went away — switched tab, reloaded, closed the browser.
+ # None of those mean "stop working", so the agent keeps running and
+ # only the viewer is released; the next viewer re-joins it. What stops
+ # an agent is closing its workspace (DELETE /workspaces/{id}).
+ registry.detach(term.key, pane_workspace)
def _safe_int(value: object, default: int) -> int:
diff --git a/tests/fakes/fake_pty_manager.py b/tests/fakes/fake_pty_manager.py
index eca0f98b42..058978367f 100644
--- a/tests/fakes/fake_pty_manager.py
+++ b/tests/fakes/fake_pty_manager.py
@@ -33,6 +33,9 @@ class FakePtyManager:
spawn_error: str | None = None
_live: set[str] = field(default_factory=set)
_counter: int = 0
+ # Callbacks per live terminal, so a test can make an agent SPEAK (see
+ # ``emit``) rather than only observe what was typed at it.
+ _callbacks: dict[str, tuple[Any, Any]] = field(default_factory=dict)
async def spawn(
self,
@@ -60,6 +63,7 @@ class FakePtyManager:
}
)
self._live.add(terminal_id)
+ self._callbacks[terminal_id] = (on_output, on_closed)
return FakePtySession(terminal_id=terminal_id, shell_id=shell_id)
def write(self, terminal_id: str, data: str) -> bool:
@@ -76,6 +80,7 @@ class FakePtyManager:
def close(self, terminal_id: str) -> bool:
self.closed.append(terminal_id)
+ self._callbacks.pop(terminal_id, None)
return self._live.discard(terminal_id) is None and True
def has(self, terminal_id: str) -> bool:
@@ -91,5 +96,25 @@ class FakePtyManager:
"""Everything written, in order (handy for asserting one prompt)."""
return [data for _tid, data in self.writes]
+ async def emit(self, terminal_id: str | None, text: str) -> None:
+ """Make the agent in this terminal print ``text``.
+
+ The real reader thread calls the registry's output callback; this is the
+ same call, so everything downstream of it — transcript, replay buffer,
+ the viewer — is exercised exactly as it is in production.
+ """
+ callbacks = self._callbacks.get(terminal_id or "")
+ if callbacks is None:
+ raise AssertionError(f"no live terminal {terminal_id!r} to emit from")
+ await callbacks[0](terminal_id, text)
+
+ async def die(self, terminal_id: str | None, code: int = 1) -> None:
+ """Make the agent in this terminal exit with ``code``."""
+ callbacks = self._callbacks.pop(terminal_id or "", None)
+ if callbacks is None:
+ raise AssertionError(f"no live terminal {terminal_id!r} to kill")
+ self._live.discard(terminal_id or "")
+ await callbacks[1](terminal_id, code)
+
__all__ = ["FakePtyManager", "FakePtySession"]
diff --git a/tests/unit/agentic_ide/test_resume_session.py b/tests/unit/agentic_ide/test_resume_session.py
index e90b85733f..ff4963360f 100644
--- a/tests/unit/agentic_ide/test_resume_session.py
+++ b/tests/unit/agentic_ide/test_resume_session.py
@@ -85,7 +85,7 @@ async def test_reopening_a_pane_keeps_the_same_conversation(
tmp_path: Path,
existing_conversation,
) -> None:
- """The browser-close case: the pane reconnects and picks up where it was."""
+ """After the agent really died, the pane comes back with its conversation."""
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
@@ -93,13 +93,35 @@ async def test_reopening_a_pane_keeps_the_same_conversation(
# The pane was used, so the CLI now has a conversation under that id.
existing_conversation(minted.id)
- registry.detach("Mika") # the viewer went away, the agent was stopped
+ # The agent is gone — quit from inside, machine restarted, process killed.
+ # THAT is what makes the next attach a restart rather than a re-join.
+ await fake_pty.die(registry.session.find("Mika").pty_id, 0)
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_letting_go_of_a_pane_does_not_stop_its_agent(
+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """A viewer leaving is not an instruction to stop working.
+
+ Panes are released constantly — switching workspace, reloading the page,
+ walking over to the chat view. An agent runs until its WORKSPACE is closed,
+ so none of those may cost the work in progress.
+ """
+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Mika"}])
+ await registry.attach("Mika", 80, 24, _noop, _noop_exit)
+ pty_id = registry.session.find("Mika").pty_id
+
+ registry.detach("Mika")
+
+ assert pty_id not in fake_pty.closed, "the agent must still be running"
+ assert registry.session.find("Mika").status == "live"
+ assert registry.session.find("Mika").pty_id == pty_id
+
+
async def test_a_pane_running_a_cli_that_cannot_resume_just_starts(
registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path
) -> None:
@@ -232,11 +254,11 @@ async def test_closing_a_resumed_pane_does_not_resurrect_it(
) -> None:
"""The trap the self-healing walks into if it is not told about the kill.
- Stopping a pane kills its agent, and a killed process reports a failure exit
+ Closing a pane kills its agent, and a killed process reports a failure exit
that looks exactly like a crashed resume. Without knowing the kill was
deliberate, the recovery would restart an agent the user had just closed —
and it would then run on with nobody watching, which is precisely what
- stopping it prevents.
+ closing it prevents.
"""
await registry.start(str(tmp_path), [{"agent": "claude", "name": "Mika"}])
registry.session.find("Mika").resume = ResumeHandle(
@@ -247,12 +269,36 @@ async def test_closing_a_resumed_pane_does_not_resurrect_it(
assert registry.session.find("Mika").resumed is True
spawns_before = len(fake_pty.spawns)
- # The browser tab closed a second after the pane came back.
- registry.detach("Mika")
+ # The user closed the pane a second after it came back, and the kill is
+ # reported by the PTY as a failure exit.
+ await registry.close_terminal("Mika")
await fake_pty.spawns[-1]["on_closed"]("fake-pty-1", 1)
assert len(fake_pty.spawns) == spawns_before, "the agent must stay stopped"
- assert registry.session.find("Mika").status == "exited"
+ assert registry.session.find("Mika") is None, "and its pane must be gone"
+
+
+async def test_closing_the_workspace_does_not_resurrect_a_resumed_pane(
+ registry: ide.Registry,
+ fake_pty: FakePtyManager,
+ tmp_path: Path,
+ existing_conversation,
+) -> None:
+ """Same trap, reached by closing the whole workspace instead of one pane."""
+ 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
+ )
+ existing_conversation("fine")
+ await registry.attach("Mika", 80, 24, _noop, _noop_exit)
+ term = registry.session.find("Mika")
+ spawns_before = len(fake_pty.spawns)
+
+ await registry.end()
+ await fake_pty.spawns[-1]["on_closed"]("fake-pty-1", 1)
+
+ assert len(fake_pty.spawns) == spawns_before, "the agent must stay stopped"
+ assert term.status != "live"
async def test_a_late_crash_is_reported_as_a_crash(
@@ -364,16 +410,40 @@ async def test_restore_refuses_an_empty_workspace(
await registry.restore(empty)
-async def test_restore_replaces_a_running_workspace_cleanly(
+async def test_restoring_a_folder_that_is_still_open_switches_to_it(
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.
+ """
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"
+ restored = await registry.restore(_snapshot(tmp_path))
+
+ 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
+
+
+async def test_restoring_another_folder_opens_it_beside_the_running_one(
+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ other = tmp_path / "elsewhere"
+ other.mkdir()
+ 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(other))
+
+ assert live not in fake_pty.closed, "the first workspace must keep running"
assert [t.name for t in registry.session.terminals] == ["Mika", "Kai"]
+ assert len(registry.sessions) == 2
# ---------------------------------------------------------------- snapshots
@@ -423,20 +493,47 @@ async def test_closing_the_workspace_deliberately_withdraws_the_offer(
assert resume_store.load() is None
-async def test_opening_another_workspace_does_not_leave_a_gap(
+async def test_the_offer_follows_the_workspace_on_screen(
registry: ide.Registry, tmp_path: Path
) -> None:
- """Replacing a workspace must always leave SOMETHING resumable behind."""
+ """The restore point answers "what was I working in", so it tracks the front.
+
+ 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.
+ """
first = tmp_path / "first"
second = tmp_path / "second"
first.mkdir()
second.mkdir()
- await registry.start(str(first), [{"agent": "claude", "name": "Mika"}])
+ one = 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)
+ await registry.activate(one.id)
+ saved = resume_store.load()
+ assert saved is not None and saved.folder == str(first)
+
+
+async def test_closing_one_of_two_leaves_the_survivor_resumable(
+ registry: ide.Registry, tmp_path: Path
+) -> None:
+ """Closing must never leave a restore point pointing at nothing."""
+ first = tmp_path / "first"
+ second = tmp_path / "second"
+ first.mkdir()
+ second.mkdir()
+ one = await registry.start(str(first), [{"agent": "claude", "name": "Mika"}])
+ two = await registry.start(str(second), [{"agent": "claude", "name": "Nova"}])
+
+ await registry.end(two.id)
+
+ saved = resume_store.load()
+ assert saved is not None and saved.folder == str(first)
+ assert registry.active_id == one.id
+
async def test_a_broken_snapshot_write_never_breaks_the_workspace(
registry: ide.Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
@@ -500,9 +597,33 @@ async def test_closing_the_workspace_stops_pending_lookups(
) -> 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"}])
+ session = await registry.start(str(tmp_path), [{"agent": "codex", "name": "Cody"}])
await registry.attach("Cody", 80, 24, _noop, _noop_exit)
- assert registry._lookups
+ assert session.lookups
await registry.end()
- assert not registry._lookups
+ assert not session.lookups
+
+
+async def test_closing_one_workspace_leaves_the_others_lookups_alone(
+ registry: ide.Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Lookups belong to a workspace, not to the process.
+
+ A shared set would mean closing one tab cancels the pending conversation-id
+ discovery of every other one — and those panes would silently lose the only
+ thing that lets them be resumed later.
+ """
+ monkeypatch.setattr(ide, "DISCOVERY_DELAYS_S", (5.0,))
+ other = tmp_path / "second"
+ other.mkdir()
+ keep = await registry.start(str(tmp_path), [{"agent": "codex", "name": "Cody"}])
+ await registry.attach("Cody", 80, 24, _noop, _noop_exit)
+ close_me = await registry.start(str(other), [{"agent": "codex"}])
+ await registry.attach(close_me.terminals[0].name, 80, 24, _noop, _noop_exit)
+ assert keep.lookups and close_me.lookups
+
+ await registry.end(close_me.id)
+
+ assert not close_me.lookups
+ assert keep.lookups, "the surviving workspace must keep looking"
diff --git a/tests/unit/agentic_ide/test_session.py b/tests/unit/agentic_ide/test_session.py
index 75ef94ccbe..ab381b3c6f 100644
--- a/tests/unit/agentic_ide/test_session.py
+++ b/tests/unit/agentic_ide/test_session.py
@@ -154,14 +154,141 @@ async def test_missing_agent_binary_is_reported_in_plain_language(
await registry.start(str(tmp_path), [{"agent": "claude"}])
-async def test_starting_again_closes_the_previous_session(
+async def test_opening_the_same_folder_again_switches_to_it(
registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
) -> None:
- await _open(registry, tmp_path, [{"agent": "claude"}])
+ """A folder that is already open is brought forward, not opened twice.
+
+ Two sets of coding agents editing one tree is almost always a misclick, and
+ the workspace that is already there holds the running conversations — so
+ reopening must not stop them to start a second set.
+ """
+ first = await _open(registry, tmp_path, [{"agent": "claude"}])
await registry.attach("Mika", 80, 24, _noop_output, _noop_exit)
live_id = registry.session.terminals[0].pty_id
- await _open(registry, tmp_path, [{"agent": "codex"}])
- assert live_id in fake_pty.closed, "the old PTY must not survive a restart"
+
+ again = await _open(registry, tmp_path, [{"agent": "codex"}])
+
+ assert again.id == first.id, "the same folder must not open a second workspace"
+ assert live_id not in fake_pty.closed, "the running agent must survive"
+ assert len(registry.sessions) == 1
+
+
+async def test_a_second_folder_opens_beside_the_first(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """Opening another folder ADDS a workspace; the first keeps its agents."""
+ other = tmp_path / "second"
+ other.mkdir()
+ first = await _open(registry, tmp_path, [{"agent": "claude"}])
+ await registry.attach("Mika", 80, 24, _noop_output, _noop_exit)
+ live_id = registry.session.terminals[0].pty_id
+
+ second = await _open(registry, other, [{"agent": "claude"}])
+
+ assert second.id != first.id
+ assert live_id not in fake_pty.closed, "the first workspace must keep running"
+ assert [s.id for s in registry.sessions] == [first.id, second.id]
+ assert registry.active_id == second.id, "the new workspace comes to the front"
+
+
+async def test_call_signs_do_not_repeat_across_workspaces(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """A name addresses exactly one pane, however many workspaces are open.
+
+ "Tell Mika to run the tests" has to be an instruction, not a question about
+ which tab was meant.
+ """
+ other = tmp_path / "second"
+ other.mkdir()
+ first = await _open(registry, tmp_path, [{"agent": "claude"}, {"agent": "claude"}])
+ second = await _open(registry, other, [{"agent": "claude"}])
+
+ names = [t.name for t in first.terminals] + [t.name for t in second.terminals]
+ assert len(set(names)) == len(names), f"call-signs collided: {names}"
+
+
+async def test_switching_workspaces_leaves_every_agent_running(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """The whole point of several workspaces: looking away is not closing."""
+ other = tmp_path / "second"
+ other.mkdir()
+ first = await _open(registry, tmp_path, [{"agent": "claude"}])
+ await registry.attach(first.terminals[0].name, 80, 24, _noop_output, _noop_exit)
+ first_pty = first.terminals[0].pty_id
+
+ second = await _open(registry, other, [{"agent": "claude"}])
+ await registry.attach(second.terminals[0].name, 80, 24, _noop_output, _noop_exit)
+ # The pane of the workspace that went to the back lets go of its viewer.
+ registry.detach(first.terminals[0].key, first.id)
+
+ assert first_pty not in fake_pty.closed, "a backgrounded agent must keep running"
+ assert first.terminals[0].pty_id == first_pty
+ assert first.terminals[0].status == "live"
+
+
+async def test_coming_back_rejoins_the_running_agent_and_replays_its_screen(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """Re-attaching must not respawn — and must not come back to a blank pane."""
+ session = await _open(registry, tmp_path, [{"agent": "claude"}])
+ term = session.terminals[0]
+ await registry.attach(term.name, 80, 24, _noop_output, _noop_exit)
+ original_pty = term.pty_id
+ spawns_before = len(fake_pty.spawns)
+
+ # The agent prints while nobody is watching.
+ await fake_pty.emit(original_pty, "\x1b[32mbuilding…\x1b[0m")
+ registry.detach(term.key, session.id)
+
+ seen: list[str] = []
+
+ async def _capture(text: str) -> None:
+ seen.append(text)
+
+ back = await registry.attach(term.name, 100, 30, _capture, _noop_exit)
+
+ assert back.pty_id == original_pty, "the same agent process must be re-joined"
+ assert len(fake_pty.spawns) == spawns_before, "nothing may be respawned"
+ assert back.reattached is True
+ assert "building…" in "".join(seen), "the screen must come back with the pane"
+
+
+async def test_closing_a_workspace_stops_only_its_own_agents(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ other = tmp_path / "second"
+ other.mkdir()
+ first = await _open(registry, tmp_path, [{"agent": "claude"}])
+ await registry.attach(first.terminals[0].name, 80, 24, _noop_output, _noop_exit)
+ first_pty = first.terminals[0].pty_id
+
+ second = await _open(registry, other, [{"agent": "claude"}])
+ await registry.attach(second.terminals[0].name, 80, 24, _noop_output, _noop_exit)
+ second_pty = second.terminals[0].pty_id
+
+ await registry.end(second.id)
+
+ assert second_pty in fake_pty.closed, "closing must stop that workspace's agents"
+ assert first_pty not in fake_pty.closed, "and only that workspace's"
+ assert [s.id for s in registry.sessions] == [first.id]
+ assert registry.active_id == first.id, "the survivor takes the front"
+
+
+async def test_the_workspace_cap_is_refused_in_plain_language(
+ registry: Registry, tmp_path: Path
+) -> None:
+ for index in range(session_mod.MAX_WORKSPACES):
+ folder = tmp_path / f"ws{index}"
+ folder.mkdir()
+ await _open(registry, folder, [{"agent": "claude"}])
+
+ one_too_many = tmp_path / "overflow"
+ one_too_many.mkdir()
+ with pytest.raises(SessionError, match="already open"):
+ await _open(registry, one_too_many, [{"agent": "claude"}])
# --------------------------------------------------------------------- attach
diff --git a/tests/unit/web/test_agentic_ide_recents.py b/tests/unit/web/test_agentic_ide_recents.py
index 00c37fd49d..bc2730cf1d 100644
--- a/tests/unit/web/test_agentic_ide_recents.py
+++ b/tests/unit/web/test_agentic_ide_recents.py
@@ -29,6 +29,12 @@ async def test_open_route_remembers_the_user_selected_folder(
assert len(terminals) == 3
return session
+ def state(self) -> dict:
+ # Opening answers with the workspace bar too, so the client that
+ # just added a workspace does not need a second round-trip to
+ # discover it is there.
+ return {"active": True, "workspaces": [], "active_id": "ide_fake"}
+
remembered: list[tuple[str, int, dict[str, int]]] = []
monkeypatch.setattr(routes, "get_registry", lambda: FakeRegistry())
monkeypatch.setattr(
diff --git a/tests/unit/web/test_agentic_ide_workspaces.py b/tests/unit/web/test_agentic_ide_workspaces.py
new file mode 100644
index 0000000000..3fc672dc90
--- /dev/null
+++ b/tests/unit/web/test_agentic_ide_workspaces.py
@@ -0,0 +1,251 @@
+"""The workspace bar's endpoints: list, switch, close one.
+
+What these defend is a single promise the UI makes and the backend has to keep:
+**switching workspaces neither starts nor stops anything.** Everything else in
+the feature follows from it — the tab that shows a live-pane count is telling
+the truth, the pane you come back to is the process you left, and the only
+button that stops an agent is the one labelled close.
+
+Driven through the route functions against a real ``Registry`` (with a fake PTY
+pool), so a change that satisfies the registry but forgets the route — or the
+other way round — still fails here.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import session as session_mod
+from jarvis.agentic_ide.session import Registry
+from jarvis.ui.web import agentic_ide_routes as routes
+from tests.fakes.fake_pty_manager import FakePtyManager
+
+
[email protected](autouse=True)
+def _agents_installed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Both coding CLIs are "on PATH" — this suite is about workspaces.
+
+ Never asks what the developer happens to have installed (AP-23).
+ """
+ monkeypatch.setattr(session_mod, "agent_argv", lambda agent: ("/usr/bin/" + agent,))
+
+
[email protected](autouse=True)
+def _isolated_stores(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Keep the resume snapshot and the recents list out of the real profile.
+
+ A test that opens a workspace must not rewrite the user's own recent-folder
+ list — it happened, and every entry in the live app became a pytest path.
+ """
+ from jarvis.agentic_ide import recents, resume_store
+
+ store = tmp_path / "store"
+ store.mkdir()
+ monkeypatch.setattr(resume_store, "_store_path", lambda: store / "last.json")
+ monkeypatch.setattr(recents, "remember", lambda *a, **k: None)
+
+
+def fake_pty() -> FakePtyManager:
+ return FakePtyManager()
+
+
+def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> Registry:
+ """A real registry the routes reach through ``get_registry``."""
+ instance = Registry(pty_manager=fake_pty)
+ monkeypatch.setattr(routes, "get_registry", lambda: instance)
+ return instance
+
+
+async def _noop(_text: str) -> None:
+ return None
+
+
+async def _noop_exit(_code: int) -> None:
+ return None
+
+
+async def _open(registry: Registry, folder: Path, panes: int = 1) -> object:
+ folder.mkdir(parents=True, exist_ok=True)
+ return await routes.start_session(
+ routes.StartSessionRequest(
+ folder=str(folder),
+ terminals=[routes.TerminalRequest(agent="claude") for _ in range(panes)],
+ )
+ )
+
+
+# ------------------------------------------------------------------- listing
+async def test_the_bar_lists_every_open_workspace_with_the_front_one_marked(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path / "alpha")
+ await _open(registry, tmp_path / "beta", panes=2)
+
+ listed = await routes.get_workspaces()
+
+ assert [w.name for w in listed.workspaces] == ["alpha", "beta"]
+ assert [w.active for w in listed.workspaces] == [False, True]
+ assert listed.active_id == registry.active_id
+ assert listed.workspaces[1].terminals == 2
+ assert listed.max_workspaces == session_mod.MAX_WORKSPACES
+
+
+async def test_a_tab_counts_the_panes_that_are_really_running(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """``live_terminals`` is what makes a background workspace honest.
+
+ A tab claiming two running agents while both are dead would be worse than
+ no count at all — the point of the number is to tell the user what is still
+ burning tokens somewhere they cannot see.
+ """
+ await _open(registry, tmp_path / "alpha", panes=2)
+ session = registry.session
+ assert session is not None
+ await registry.attach(session.terminals[0].name, 80, 24, _noop, _noop_exit)
+
+ card = (await routes.get_workspaces()).workspaces[0]
+
+ assert card.terminals == 2
+ assert card.live_terminals == 1
+
+
+# ----------------------------------------------------------------- switching
+async def test_switching_starts_and_stops_nothing(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ first = await _open(registry, tmp_path / "alpha")
+ first_id = first["session"]["id"]
+ first_pane = registry.get(first_id).terminals[0]
+ await registry.attach(first_pane.name, 80, 24, _noop, _noop_exit, first_id)
+ first_pty = first_pane.pty_id
+ spawns = len(fake_pty.spawns)
+
+ await _open(registry, tmp_path / "beta")
+ result = await routes.activate_workspace(routes.ActivateWorkspaceRequest(id=first_id))
+
+ assert result["active_id"] == first_id
+ assert first_pty not in fake_pty.closed, "switching must not stop an agent"
+ assert len(fake_pty.spawns) == spawns, "switching must not start one either"
+ assert len(registry.sessions) == 2
+
+
+async def test_the_wizard_state_keeps_every_workspace_open(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """"Add a workspace" clears the front WITHOUT closing what is open.
+
+ This is the state the UI is in while the folder wizard is showing. If it
+ closed anything, pressing + and then changing your mind would cost you a
+ workspace.
+ """
+ opened = await _open(registry, tmp_path / "alpha")
+ pane = registry.session.terminals[0]
+ await registry.attach(pane.name, 80, 24, _noop, _noop_exit)
+
+ result = await routes.activate_workspace(routes.ActivateWorkspaceRequest(id=None))
+
+ assert result["active_id"] is None
+ assert result["state"]["session"] is None, "no workspace is on screen"
+ assert len(result["state"]["workspaces"]) == 1, "but it is still open"
+ assert pane.pty_id not in fake_pty.closed
+ assert opened["session"]["id"] == result["state"]["workspaces"][0]["id"]
+
+
+async def test_switching_to_a_workspace_that_is_gone_is_a_404(
+ registry: Registry, tmp_path: Path
+) -> None:
+ from fastapi import HTTPException
+
+ await _open(registry, tmp_path / "alpha")
+ with pytest.raises(HTTPException) as caught:
+ await routes.activate_workspace(
+ routes.ActivateWorkspaceRequest(id="ide_never_existed")
+ )
+ assert caught.value.status_code == 404
+
+
+# ------------------------------------------------------------------ closing
+async def test_closing_one_workspace_stops_only_its_agents(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ first = await _open(registry, tmp_path / "alpha")
+ first_id = first["session"]["id"]
+ first_pane = registry.get(first_id).terminals[0]
+ await registry.attach(first_pane.name, 80, 24, _noop, _noop_exit, first_id)
+
+ second = await _open(registry, tmp_path / "beta")
+ second_id = second["session"]["id"]
+ second_pane = registry.get(second_id).terminals[0]
+ await registry.attach(second_pane.name, 80, 24, _noop, _noop_exit, second_id)
+
+ result = await routes.close_workspace(second_id)
+
+ assert result["closed"] == second_id
+ assert second_pane.pty_id in fake_pty.closed
+ assert first_pane.pty_id not in fake_pty.closed
+ assert [w["id"] for w in result["state"]["workspaces"]] == [first_id]
+ assert result["state"]["active_id"] == first_id, "the survivor takes the front"
+
+
+async def test_closing_an_unknown_workspace_is_a_404(
+ registry: Registry, tmp_path: Path
+) -> None:
+ from fastapi import HTTPException
+
+ await _open(registry, tmp_path / "alpha")
+ with pytest.raises(HTTPException) as caught:
+ await routes.close_workspace("ide_never_existed")
+ assert caught.value.status_code == 404
+
+
+async def test_the_plain_close_still_closes_the_front_one(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """The toolbar button and every existing CLI caller keep working."""
+ await _open(registry, tmp_path / "alpha")
+ second = await _open(registry, tmp_path / "beta")
+
+ result = await routes.end_session()
+
+ assert result["closed"] is True
+ remaining = [w["name"] for w in result["state"]["workspaces"]]
+ assert remaining == ["alpha"]
+ assert second["session"]["id"] not in [
+ w["id"] for w in result["state"]["workspaces"]
+ ]
+
+
+# -------------------------------------------------------------------- state
+async def test_state_carries_the_bar_and_the_front_workspace_together(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """One fetch answers both questions, so the two can never disagree."""
+ await _open(registry, tmp_path / "alpha")
+ beta = await _open(registry, tmp_path / "beta")
+
+ state = await routes.get_state()
+
+ assert state["session"]["id"] == beta["session"]["id"]
+ assert state["active_id"] == beta["session"]["id"]
+ assert [w["name"] for w in state["workspaces"]] == ["alpha", "beta"]
+ assert state["max_workspaces"] == session_mod.MAX_WORKSPACES
+
+
+async def test_opening_a_folder_that_is_already_open_switches_to_it(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ first = await _open(registry, tmp_path / "alpha")
+ pane = registry.session.terminals[0]
+ await registry.attach(pane.name, 80, 24, _noop, _noop_exit)
+ await _open(registry, tmp_path / "beta")
+
+ again = await _open(registry, tmp_path / "alpha")
+
+ assert again["session"]["id"] == first["session"]["id"]
+ assert pane.pty_id not in fake_pty.closed, "the running agent must survive"
+ assert len(again["state"]["workspaces"]) == 2, "no duplicate tab"
+ assert again["state"]["active_id"] == first["session"]["id"]