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
feat(ide): organize projects and route workspace-aware coding tasks
rubenluetke10-beepd21c0980b10d
diff --git a/docs/igentic-workspaces.md b/docs/igentic-workspaces.mdnew file mode 100644index 0000000000..f6223b9f92--- /dev/null+++ b/docs/igentic-workspaces.md@@ -0,0 +1,87 @@+# iGentic projects and workspace orchestration++The IDE is organized as **Project > Workspace > Coding Agent session**. A+project is a connected folder in the existing project library. A workspace is+an independently named group of up to eight coding sessions in that project.+Multiple workspaces may use the same folder; independent sessions do not imply+isolated source checkouts. Users who need separate files connect a worktree as+another project.++## Interaction and identity++Connecting or creating a folder registers a project without starting a process.+The project's plus action opens a compact agent setup dialog. The project tree+shows open and saved workspaces, their session counts, and active selection.+Selecting an open workspace changes the visible group and active runtime ID;+it does not stop background agents. Restoring a closed workspace is explicit.++The grid uses at most four columns and two rows on a sufficiently wide display.+Narrow screens retain at most two rows and scroll horizontally when necessary,+rather than shrinking the user's terminal font. Dragging a card header or using+Alt+Arrow reorders stable session IDs. Reordering does not recreate the CLI+process. Each tile uses the existing+PTY adapter, output replay, reconnect budget, and terminal appearance tokens.++Project IDs come from the canonical folder identity. Workspace IDs survive+restore. A coding session is addressed as `pane:<history_id>`; its display name+and grid position are not execution identities. Additive snapshot migration+retains older project-less workspaces and keeps sibling workspaces in the same+folder distinct. Older snapshots above the eight-session limit are retained+but cannot be restored into the new grid unchanged.++## Live integration++The new `workspace-orchestrate` tool is available through the supervisor's voice+catalog to ChatGPT Live and the native Gemini/local Live path. It replaces the+legacy ambient IDE prompt tools on that surface. It is not installed in mission+worker tools and does not grant Society agents any new capability.++1. `inspect` reads the same project graph used by the sidebar, enriched with+ actual coding-session identities, status and observed activity.+2. `resolve` interprets model-extracted project/workspace/agent names or IDs.+ Explicit references take precedence. With no reference, the active workspace+ is the default. An unnamed agent is selected in stable order from idle or+ unstarted sessions. Duplicate names and multiple matching workspaces return+ structured clarification candidates rather than guessing.+3. `send` requires the resolved project, workspace and terminal IDs, a task, and+ the unique request ID issued by resolution. The application-owned ToolExecutor+ applies permission policy before the coding-session gateway delivers to that+ exact session.+4. `context` reads recorded results from the addressed session. A delivery+ receipt never asserts that the coding task has completed.++For example, a request to fix an installer in a named project can address a+background workspace while the user continues viewing another project. The+orchestrator never temporarily changes global selection to make a delivery.+Changing selection while an approval is pending cannot change its target.++Each send is durably claimed in SQLite before delivery. Retrying the same ID+returns its existing receipt. Reusing an ID with changed arguments fails.+Cancellation or interruption after a possible write leaves an uncertain claim;+neither voice reconnection nor a new tool-call ID replays that request. Receipts+include the immutable target and execution trace. Requests to a closed, moved,+archived or non-coding session fail without falling back to another terminal.++## Boundaries and verification++This is a T3 shared contract change. No new OS adapter, credential or model+default is introduced. PTY availability remains capability-probed; Windows uses+the existing ConPTY backend and Linux/macOS the existing POSIX backend.+Headless systems can inspect projects even without a usable terminal backend.++Contract coverage is in `tests/contract/test_workspace_orchestration.py`; the+workspace graph and migration tests are in+`tests/unit/agentic_ide/test_workspace_graph.py`. Frontend interaction tests+exercise project creation, switching, bounded grid layout and stable reordering.+Passing these tests is not evidence of native macOS execution, a microphone+test, or a completed real coding assignment. Live and desktop acceptance must+be reported separately from mocked transport checks.++A synthetic Gemini Realtime probe on Windows and a fresh headless Linux source+installation exercised model-selected resolution and one addressed delivery+through the real ToolExecutor, then received spoken delivery confirmation. The+Linux dependency image was preinstalled; the application was freshly installed+from source. The coding-session adapter in that probe was a fake; no repository+was changed. An OpenAI Live probe was attempted but session setup was rejected,+so live OpenAI acceptance remains open. Portable Linux contract tests pass;+native macOS execution and microphone/device acceptance remain unverified.diff --git a/docs/os-parity.md b/docs/os-parity.mdindex a8f2131757..4d69d80280 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -1,5 +1,22 @@# OS Feature Parity — macOS / Linux Gap Register+## iGentic project workspaces (T3)++Project ownership, workspace snapshots, eight-session ordering and addressed+task receipts use portable Python/SQLite and the same browser UI on all three+OSes. Terminal capability is checked through `workspace.agents.pty_available`:+Windows retains ConPTY, Linux and macOS retain the existing POSIX backend, and+an unavailable backend is reported without importing a new native dependency.+ChatGPT Live and native Gemini/local voice use the same supervisor tool and+permission boundary. There is no OS-specific routing or credential path.++`tests/contract/test_workspace_orchestration.py` covers explicit and ambient+resolution, ambiguous references, background dispatch, immutable targets and+durable retry behavior. Native macOS desktop/PTY acceptance and real-device+audio are not established by the portable tests. See+[workspace architecture](igentic-workspaces.md) for the product and execution+contract.+## Window caption (2026-09-21, T2)The desktop window is frameless on Windows, macOS and Linux. The page drawsdiff --git a/jarvis/agentic_ide/orchestration.py b/jarvis/agentic_ide/orchestration.pynew file mode 100644index 0000000000..a2c163762b--- /dev/null+++ b/jarvis/agentic_ide/orchestration.py@@ -0,0 +1,293 @@+"""Workspace-aware target resolution and durable, addressed task delivery.++Names are references, never execution identities. Resolution returns the three+stable IDs needed by send; moving focus, renaming or reordering cannot retarget+an approval. This layer never activates a workspace or composes a second prompt.+"""++from __future__ import annotations++import asyncio+import threading+from typing import Any+from uuid import UUID, uuid4++from jarvis.core.protocols import CodingSessionGateway+from jarvis.live.state import LiveLedger++from .session import Registry, SessionError, accepts_prompts+from .workspace_catalog import project_graph+++def _matches(reference: str, *values: str) -> bool:+ return reference.strip().casefold() in {v.strip().casefold() for v in values if v}+++class WorkspaceOrchestrator:+ """One graph for Live discovery, explicit resolution and scoped delivery."""++ def __init__(+ self,+ registry: Registry,+ sessions: CodingSessionGateway,+ ledger: LiveLedger,+ ) -> None:+ self.registry = registry+ self.sessions = sessions+ self.ledger = ledger++ def graph(self) -> dict[str, Any]:+ from jarvis.workspace.agents import pty_available++ graph = project_graph(self.registry)+ for project in graph["projects"]:+ for workspace in project["workspaces"]:+ owner = self.registry.get(workspace["id"])+ workspace["agents"] = (+ [+ {+ "id": "pane:" + term.history_id,+ "name": term.name,+ "agent": term.agent,+ "status": term.status,+ "activity": term.reading().activity,+ "accepts_tasks": accepts_prompts(term.agent) and not term.archived,+ }+ for term in owner.terminals+ ]+ if owner+ else []+ )+ return {+ **graph,+ "available": pty_available(),+ "note": (+ "Workspace selection is UI context, not permission. "+ "Closed workspaces must be restored before dispatch."+ ),+ }++ def resolve(self, args: dict[str, Any], graph: dict[str, Any]) -> dict[str, Any]:+ projects = graph["projects"]+ project_ref = str(args.get("project") or "")+ workspace_ref = str(args.get("workspace") or "")+ agent_ref = str(args.get("agent") or "")+ if project_ref:+ projects = [p for p in projects if _matches(project_ref, p["id"], p["name"], p["path"])]+ if len(projects) != 1:+ return self._choice("project", projects)+ candidates = [(p, w) for p in projects for w in p["workspaces"]]+ if workspace_ref:+ matched = [(p, w) for p, w in candidates if _matches(workspace_ref, w["id"], w["name"])]+ # People often call a project "the Personal Jarvis workspace".+ # Interpret that only when it identifies exactly one project.+ if not matched:+ owners = [p for p in projects if _matches(workspace_ref, p["id"], p["name"])]+ if len(owners) == 1:+ matched = [(p, w) for p, w in candidates if p["id"] == owners[0]["id"]]+ candidates = matched+ elif not project_ref:+ named_agents = [+ (p, w)+ for p, w in candidates+ if agent_ref and any(_matches(agent_ref, a["id"], a["name"]) for a in w["agents"])+ ]+ candidates = named_agents or [+ (p, w) for p, w in candidates if w["id"] == graph["active_workspace_id"]+ ]+ if len(candidates) != 1:+ return self._choice(+ "workspace",+ [{"project_id": p["id"], "project": p["name"], **w} for p, w in candidates],+ )+ project, workspace = candidates[0]+ if workspace["status"] != "open":+ return {+ "status": "unavailable",+ "reason": "Restore this closed workspace first.",+ "project_id": project["id"],+ "workspace_id": workspace["id"],+ }+ agents = [a for a in workspace["agents"] if a["accepts_tasks"]]+ if agent_ref:+ named = [a for a in agents if _matches(agent_ref, a["id"], a["name"])]+ agents = named or [a for a in agents if _matches(agent_ref, a["agent"])]+ if len(agents) != 1:+ return self._choice("agent", agents)+ else:+ # A task need not require manually selecting a tile. Stable grid+ # order is the tie-breaker among idle sessions; never interrupt one.+ agents = [+ a+ for a in agents+ if a["status"] == "pending"+ or (+ a["status"] == "live" and a["activity"] not in {"working", "asking", "starting"}+ )+ ]+ agents = agents[:1]+ if not agents:+ return {+ "status": "unavailable",+ "reason": "No idle coding agent is available in this workspace.",+ "project_id": project["id"],+ "workspace_id": workspace["id"],+ }+ agent = agents[0]+ return {+ "status": "resolved",+ "request_id": uuid4().hex,+ "target": {+ "project_id": project["id"],+ "workspace_id": workspace["id"],+ "terminal_id": agent["id"],+ "project": project["name"],+ "workspace": workspace["name"],+ "agent": agent["name"],+ },+ "selection": "explicit_agent" if agent_ref else "first_idle_agent",+ }++ @staticmethod+ def _choice(kind: str, choices: list[dict]) -> dict[str, Any]:+ return {+ "status": "needs_clarification",+ "kind": kind,+ "candidates": choices,+ "reason": "Reference is ambiguous."+ if choices+ else "No matching open target. Connect or restore the workspace first.",+ }++ async def run(self, args: dict[str, Any], *, trace_id: str = "") -> dict[str, Any]:+ action = args.get("action")+ if action in {"inspect", "resolve"}:+ graph = await asyncio.to_thread(self.graph)+ return graph if action == "inspect" else self.resolve(args, graph)+ if action not in {"send", "context"}:+ raise ValueError("Unknown workspace orchestration action.")+ project_id, workspace_id, terminal_id = (+ str(args.get(key) or "") for key in ("project_id", "workspace_id", "terminal_id")+ )+ if not project_id or not workspace_id or not terminal_id.startswith("pane:"):+ raise ValueError(+ "Resolve a target first; project_id, workspace_id and terminal_id are required."+ )+ target = {+ "project_id": project_id,+ "workspace_id": workspace_id,+ "terminal_id": terminal_id,+ }+ request_id = str(args.get("request_id") or "").strip()+ if action == "send":+ prompt = str(args.get("prompt") or "").strip()+ if not prompt or not request_id or len(request_id) > 160:+ raise ValueError(+ "Sending requires a prompt and a stable request_id (at most 160 characters)."+ )+ try:+ UUID(request_id)+ except ValueError as exc:+ raise ValueError("Use the unique request_id returned by resolve.") from exc+ previous = await asyncio.to_thread(+ self.ledger.claim,+ "workspace-orchestration",+ request_id,+ "send",+ {**target, "prompt": prompt},+ 0,+ )+ if previous is not None:+ return previous+ owner = self.registry.get(workspace_id)+ found = self.registry.find_terminal(terminal_id, workspace_id) if owner else None+ result: dict[str, Any]+ if owner is None or owner.project_id != project_id or found is None or found[1].archived:+ result = {+ "status": "stale_target",+ "target": target,+ "reason": "The resolved coding session is no longer in that project/workspace.",+ }+ elif not accepts_prompts(found[1].agent):+ result = {+ "status": "unavailable",+ "target": target,+ "reason": "This session does not accept coding tasks.",+ }+ else:+ # The low-level gateway enforces idle/asking state and refuses exited+ # agents. It never falls through to a shell or a different pane.+ try:+ delivery = await self.sessions.run(+ {+ "action": action,+ "workspace_id": workspace_id,+ "terminal_id": terminal_id,+ **(+ {"prompt": prompt}+ if action == "send"+ else {"limit": args.get("limit", 30)}+ ),+ }+ )+ result = {+ "status": delivery.get("delivery", "observed"),+ "target": target,+ "trace_id": trace_id,+ **delivery,+ }+ except SessionError as exc:+ # The coding-session adapter documents SessionError as a+ # pre-write refusal; post-write uncertainty is a receipt.+ result = {+ "status": "not_accepted",+ "target": target,+ "reason": str(exc),+ "completed": False,+ }+ except Exception as exc:+ # Preserve uncertainty: an adapter can fail after the write.+ # The durable claim remains, preventing an automatic replay.+ from loguru import logger++ logger.warning("Workspace action {} failed: {}", action, type(exc).__name__)+ if action == "send":+ return {+ "status": "uncertain",+ "target": target,+ "reason": (+ "Delivery could not be confirmed. Inspect the session; "+ "do not resend automatically."+ ),+ }+ raise+ if action == "send":+ await asyncio.to_thread(+ self.ledger.finish, "workspace-orchestration", request_id, result+ )+ return result+++_orchestrators: dict[int, WorkspaceOrchestrator] = {}+_creation_lock = threading.Lock()+++def get_orchestrator() -> WorkspaceOrchestrator:+ """Lazy composition: no filesystem, PTY or model initialization at boot."""+ from jarvis.core.paths import user_data_dir++ from .control import CodingSessionControl+ from .session import get_registry++ registry = get_registry()+ key = id(registry)+ with _creation_lock:+ if key not in _orchestrators:+ root = user_data_dir()+ root.mkdir(parents=True, exist_ok=True)+ _orchestrators[key] = WorkspaceOrchestrator(+ registry,+ CodingSessionControl(registry),+ LiveLedger(root / "workspace-orchestration.sqlite3"),+ )+ return _orchestrators[key]diff --git a/jarvis/agentic_ide/resume_store.py b/jarvis/agentic_ide/resume_store.pyindex d797f69969..5098987af0 100644--- a/jarvis/agentic_ide/resume_store.py+++ b/jarvis/agentic_ide/resume_store.py@@ -34,14 +34,15 @@ import jsonimport osimport threadingimport time-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom pathlib import Pathfrom typing import Any-from uuid import uuid4+from uuid import NAMESPACE_URL, uuid4, uuid5from loguru import loggerfrom .agent_sessions import ResumeHandle, has_conversation+from .library import project_id_for# Saves arrive from more than one thread (see `save`), and the last one has to# be the one that lands rather than the one that happened to finish its rename@@ -187,10 +188,12 @@ class SnapshotWorkspace:# file's, because the file holds workspaces that closed at different times# and the merge in `save` has to know which record is the newer one.saved_at: float = 0.0+ project_id: str = ""def to_dict(self) -> dict[str, Any]:return {"session_id": self.session_id,+ "project_id": self.project_id or project_id_for(self.folder),"folder": self.folder,"name": self.name,"saved_at": self.saved_at,@@ -222,7 +225,9 @@ class SnapshotWorkspace:saved_at = 0.0raw_layout = data.get("layout")return SnapshotWorkspace(- session_id=str(data.get("session_id") or ""),+ session_id=str(data.get("session_id") or "")+ or "ide_" + uuid5(NAMESPACE_URL, folder_key(folder)).hex[:12],+ project_id=str(data.get("project_id") or "") or project_id_for(folder),folder=folder,name=str(data.get("name") or "").strip(),terminals=terminals,@@ -267,6 +272,33 @@ class Snapshot:# necessarily the first one.active_session_id: str = ""+ def __post_init__(self) -> None:+ """Repair legacy ID collisions without reminting healthy workspace IDs.++ Old/imported files can give two different folders the same session ID.+ They must remain separate registry entries, and the repaired identity+ must be deterministic so repeated reads and sidebar clicks agree.+ Exact duplicate records for the same folder retain their ID and are+ deduplicated by the registry's existing restore-set handling.+ """+ seen: dict[str, str] = {}+ normalized: list[SnapshotWorkspace] = []+ for workspace in self.workspaces:+ folder = folder_key(workspace.folder)+ identity = workspace.session_id+ attempt = 0+ while not identity or (identity in seen and seen[identity] != folder):+ seed = f"{workspace.session_id}|{folder}|{attempt}"+ identity = "ide_" + uuid5(NAMESPACE_URL, seed).hex[:12]+ attempt += 1+ seen[identity] = folder+ normalized.append(+ workspace+ if identity == workspace.session_id+ else replace(workspace, session_id=identity)+ )+ self.workspaces = normalized+@propertydef terminal_count(self) -> int:return sum(len(w.terminals) for w in self.workspaces)@@ -401,9 +433,9 @@ def save(snapshot: Snapshot) -> None:clear()returntarget = _store_path()- snapshot = _merged_with_stored(snapshot)tmp = target.with_name(f"{target.name}.tmp-{os.getpid()}-{uuid4().hex[:8]}")with _WRITE_LOCK:+ snapshot = _merged_with_stored(snapshot)try:target.parent.mkdir(parents=True, exist_ok=True)tmp.write_text(json.dumps(snapshot.to_dict(), indent=2), encoding="utf-8")@@ -424,7 +456,7 @@ MAX_REMEMBERED_WORKSPACES = 20def _merged_with_stored(snapshot: Snapshot) -> Snapshot:- """Fold the live workspaces into what is already remembered, keyed by folder.+ """Merge by workspace identity so closed siblings in one project survive.**The failure this exists for.** A save used to replace the file outright, sothe restore point only ever held what happened to be open at that moment.@@ -433,22 +465,23 @@ def _merged_with_stored(snapshot: Snapshot) -> Snapshot:to notice until the offer came back holding one pane. Reported as "it onlyresumed one".- So a save UPDATES rather than replaces: a folder that is open now overwrites- its own record (the newest arrangement of that folder is the truth), and- every other remembered folder is left exactly as it was. Only the user+ So a save UPDATES rather than replaces: a workspace that is open overwrites+ its own record, and every other remembered workspace is left intact.+ Several independent workspaces may deliberately share one folder. Only the userasking to start fresh throws any of it away.Ordered newest-first and trimmed, so the file cannot grow without limit andthe offer leads with what was most recently worked in."""stamped = [w if w.saved_at else _restamp(w, snapshot.saved_at) for w in snapshot.workspaces]- live_folders = {folder_key(w.folder) for w in stamped}+ live_keys = {(w.session_id, folder_key(w.folder)) for w in stamped}try:stored = load()- except Exception: # noqa: BLE001 - a broken file must not block the write+ except Exception as exc: # noqa: BLE001 - a broken file must not block the write+ logger.warning("Agentic IDE: previous workspace snapshot could not be merged: {}", exc)stored = Nonekept = (- [w for w in stored.workspaces if folder_key(w.folder) not in live_folders]+ [w for w in stored.workspaces if (w.session_id, folder_key(w.folder)) not in live_keys]if stored is not Noneelse [])@@ -468,6 +501,7 @@ def _restamp(workspace: SnapshotWorkspace, when: float) -> SnapshotWorkspace:return SnapshotWorkspace(session_id=workspace.session_id,folder=workspace.folder,+ project_id=workspace.project_id or project_id_for(workspace.folder),name=workspace.name,terminals=workspace.terminals,layout=workspace.layout,@@ -589,6 +623,7 @@ def offer(snapshot: Snapshot | None, *, installed: set[str]) -> dict[str, Any]:workspaces.append({"session_id": space.session_id,+ "project_id": space.project_id or project_id_for(space.folder),"folder": space.folder,"folder_name": Path(space.folder).name or space.folder,# The label the user gave the tab, empty when never renamed. Keptdiff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex cc263f9437..f37d954a16 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -67,6 +67,7 @@ import osimport reimport shutilimport sys+import threadingimport timefrom collections.abc import AsyncIterator, Awaitable, Callable, Sequencefrom contextlib import asynccontextmanager@@ -80,7 +81,7 @@ from loguru import loggerfrom jarvis.workspace import agents as workspace_agentsfrom jarvis.workspace import launch_picks-from . import layout_tree, opening, prompt_history, recap_engine, resume_store+from . import layout_tree, library, opening, prompt_history, recap_engine, resume_storefrom .activity import NO_READING, Reading, has_work_behind_it, observedfrom .agent_sessions import (ResumeHandle,@@ -216,19 +217,8 @@ def _unavailable(agent: str) -> str:return f"{pretty} cannot open: this machine has no shell Jarvis can start."-# 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+# One workspace fits at most four columns and two rows of coding sessions.+MAX_TERMINALS = 8# How deep a wizard-opened column is filled before the next one is started.## The workspace is exactly one screenful, so its columns share the window's@@ -1421,6 +1411,8 @@ class Session:profile: ProjectProfileterminals: list[Terminal]created_at: float+ # Durable ownership in the project library, independent of the workspace ID.+ project_id: str = ""# WHERE every pane sits and how much room it has — the split tree, the one# authority on workspace geometry (see ``layout_tree``). Every structural# change (split, close, move, refold, restore) rewrites it and then lets@@ -1521,6 +1513,7 @@ class Session:def to_dict(self) -> dict[str, Any]:return {"id": self.id,+ "project_id": self.project_id or library.project_id_for(self.folder),"folder": self.folder,"name": self.name,"project": self.profile.to_dict(),@@ -1563,6 +1556,8 @@ class Session:)return {"folder": self.folder,+ "id": self.id,+ "project_id": self.project_id or library.project_id_for(self.folder),"name": self.name,"focus_mode": self.focus_mode,"terminals": terminals,@@ -1578,6 +1573,7 @@ class Session:live = sum(1 for t in self.terminals if t.status == "live")return {"id": self.id,+ "project_id": self.project_id or library.project_id_for(self.folder),"folder": self.folder,"name": self.name,"branch": self.profile.branch,@@ -1974,7 +1970,14 @@ 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]],+ *,+ project_id: str | None = None,+ name: str | None = None,+ ) -> Session:"""Open ``folder`` as a NEW workspace with one terminal per request entry.``requested`` entries look like ``{"agent": "claude", "name": "Mika"}``;@@ -2007,6 +2010,13 @@ class Registry:except OSError as exc:raise SessionError(f"Cannot open {root}: {exc}") from exc+ if project_id:+ project = await asyncio.to_thread(library.get_project, project_id)+ if project is None and project_id != library.project_id_for(root):+ raise SessionError("That project does not exist.")+ if project and library.project_id_for(root) != library.project_id_for(project.path):+ raise SessionError("The workspace folder must belong to its project.")+unknown = {str(r.get("agent")) for r in requested if not is_runnable(str(r.get("agent")))}@@ -2033,21 +2043,19 @@ class Registry:for index, entry in enumerate(requested):agent = str(entry.get("agent"))wanted = str(entry.get("name") or "").strip() or pool[index]- name = _unique_name(wanted, used)- used.add(normalize(name))+ terminal_name = _unique_name(wanted, used)+ used.add(normalize(terminal_name))requested_account = _requested_account(entry)resolved_account = resolve_account(agent, requested_account)terminals.append(Terminal(- key=normalize(name) or f"t{index}",- name=name,+ key=normalize(terminal_name) or f"t{index}",+ name=terminal_name,agent=agent,display_name=agent_display(agent),index=index,- # Columns of WIZARD_COLUMN_HEIGHT, filled top to bottom- # before the next one opens — the same arithmetic the- # preview draws with (frontend `layout.ts`), so the- # workspace that appears is the one that was shown.+ # Legacy hints are normalized into row-major order+ # when the workspace is opened below.column=index // WIZARD_COLUMN_HEIGHT,slot=index % WIZARD_COLUMN_HEIGHT,account=resolved_account,@@ -2067,7 +2075,13 @@ class Registry:))- session = await self._open_locked(root, terminals)+ session = await self._open_locked(+ root,+ terminals,+ name=name,+ project_id=project_id,+ grid=True,+ )logger.info("Agentic IDE session started: {} terminals in {}",len(terminals),@@ -2123,6 +2137,8 @@ class Registry:*,name: str | None = None,workspace_id: str | None = None,+ project_id: str | None = None,+ grid: bool = False,) -> Session:"""Turn a prepared list of panes into a NEW open workspace, at the front.@@ -2150,6 +2166,7 @@ class Registry:profile=profile,terminals=terminals,created_at=time.time(),+ project_id=project_id or library.project_id_for(root),# Both callers prepare panes with legacy (column, slot) positions# — the wizard's opening arithmetic, a snapshot's remembered grid# — and the columns-of-stacks shape those describe is exactly@@ -2157,6 +2174,8 @@ class Registry:# replaces this afterwards (`_restore_one_locked`).layout=layout_tree.from_grid((t.key, t.column, t.slot) for t in terminals),)+ if grid:+ self._row_major_grid(session)self._sessions[session.id] = sessionself._focus_locked(session)# Start indexing the codebase NOW, in a background thread, so the@@ -2312,8 +2331,89 @@ class Registry:)return wanted+ async def restore_workspace(self, workspace_id: str) -> Session:+ """Explicitly reopen one saved workspace, preserving every session ID."""+ async with self._lock:+ existing = self.get(workspace_id)+ if existing is not None:+ self._focus_locked(existing)+ return existing+ snapshot = await asyncio.to_thread(resume_store.load)+ saved = (+ next(+ (space for space in snapshot.workspaces if space.session_id == workspace_id),+ None,+ )+ if snapshot+ else None+ )+ if saved is None:+ raise SessionError("That saved workspace does not exist.")+ session = await self._restore_one_locked(saved)+ if session is None:+ raise SessionError("That saved workspace could not be reopened.")+ await self._persist()+ return session++ async def reorder_terminals(self, workspace_id: str, terminal_ids: list[str]) -> Session:+ """Persist row-major order without restarting or renaming an agent."""+ async with self._lock:+ session = self.get(workspace_id)+ if session is None:+ raise SessionError("That workspace is not open.")+ by_id = {term.history_id: term for term in session.terminals}+ if len(terminal_ids) != len(by_id) or set(terminal_ids) != set(by_id):+ raise SessionError(+ "Terminal order must contain every workspace terminal exactly once."+ )+ session.terminals = [by_id[identity] for identity in terminal_ids]+ self._row_major_grid(session)+ await self._persist()+ return session++ @staticmethod+ def _row_major_grid(session: Session) -> None:+ """Keep legacy geometry consistent with the persistent terminal order."""+ # Rebuild the legacy split tree from the new order. Old geometry+ # must never sort the terminals back into their previous positions.+ columns = (+ len(session.terminals)+ if len(session.terminals) <= 4+ else (len(session.terminals) + 1) // 2+ )+ rows = [+ layout_tree.normalize(+ layout_tree.Split(+ direction="row",+ children=[+ layout_tree.Leaf(term.key)+ for term in session.terminals[start : start + columns]+ ],+ weights=[1.0] * len(session.terminals[start : start + columns]),+ )+ )+ for start in range(0, len(session.terminals), columns or 1)+ ]+ session.layout = (+ layout_tree.normalize(+ layout_tree.Split(+ direction="column",+ children=rows,+ weights=[1.0] * len(rows),+ )+ )+ if rows+ else None+ )+ Registry._renumber(session)+async def _restore_one_locked(self, space: resume_store.SnapshotWorkspace) -> Session | None:"""Reopen one remembered workspace. Caller holds the lock."""+ if len(space.terminals) > MAX_TERMINALS:+ raise SessionError(+ f"This saved workspace has {len(space.terminals)} terminals; "+ f"the workspace limit is {MAX_TERMINALS}. Its saved sessions were preserved."+ )root = Path(space.folder).expanduser() # noqa: ASYNC240try:if not await asyncio.to_thread(root.is_dir):@@ -2386,6 +2486,7 @@ class Registry:terminals,name=space.name or None,workspace_id=space.session_id or None,+ project_id=space.project_id or library.project_id_for(space.folder),)# Which record this came back from, so a second restore of the same file# recognises it rather than opening a duplicate.@@ -2542,6 +2643,7 @@ class Registry:resume_store.SnapshotWorkspace(session_id=session.id,folder=session.folder,+ project_id=session.project_id or library.project_id_for(session.folder),name=session.name,terminals=[t.to_snapshot() for t in session.terminals],layout=layout_tree.to_dict(session.layout) if session.layout else None,@@ -4084,6 +4186,7 @@ class Registry:async def add_terminal(self,*,+ workspace_id: str | None = None,agent: str | None = None,name: str | None = None,anchor: str | None = None,@@ -4127,8 +4230,9 @@ class Registry:pane somebody opened to try something else is the confusing kind ofhelpful."""+ selected_id = workspace_id or self.active_idasync with self._lock:- session = self.session+ session = self.get(selected_id) if selected_id else Noneif session is None:raise SessionError("No Agentic-IDE session is running.")if len(session.terminals) >= MAX_TERMINALS:@@ -4258,14 +4362,19 @@ class Registry:return termasync def add_terminals(- self, count: int, *, agent: str | None = None, account: str | None = None+ self,+ count: int,+ *,+ agent: str | None = None,+ account: str | None = None,+ workspace_id: str | None = None,) -> tuple[list[Terminal], bool]:- """Open up to ``count`` more panes — the batch behind "open five more".+ """Open a batch in one pinned workspace, rejecting oversized requests.- Returns the panes that were created and whether the pane cap- truncated the request, because those are two different answers the caller- has to speak out loud: five requested with three opened is a success the- user must hear ("room for three"), not a silent partial.+ Returns the created panes and a flag for partial operational failure.+ Capacity is checked before any pane is created. A concurrent addition+ or a disappearing agent binary can still stop a batch partway through,+ which the flag reports honestly.Deliberately a loop over ``add_terminal`` rather than a second placementimplementation: the anchor, the call-sign pool, and the grid position are@@ -4273,17 +4382,24 @@ class Registry:drift from what the split buttons do. No anchor is named, so without anexplicit ``account`` every pane opens on the workspace's active one.- The cap is the expected stopping point, so hitting it is not an error.- A failure with NOTHING opened is — an unknown agent or a vanished binary- must not be reported as "nothing to do".+ A failure before creating any pane is raised to the caller."""- if self.session is None:+ selected = self.get(workspace_id)+ if selected is None:raise SessionError("No Agentic-IDE session is running.")wanted = max(1, int(count))+ if len(selected.terminals) + wanted > MAX_TERMINALS:+ raise SessionError(f"A workspace can contain at most {MAX_TERMINALS} terminals.")created: list[Terminal] = []for _ in range(wanted):try:- created.append(await self.add_terminal(agent=agent, account=account))+ created.append(+ await self.add_terminal(+ agent=agent,+ account=account,+ workspace_id=selected.id,+ )+ )except SessionError as exc:if not created:raise@@ -4339,6 +4455,14 @@ class Registry:if anchor.key == moved.key:return moved+ if session.layout is None:+ # Legacy/injected workspaces can still carry only grid hints.+ # Build their tree before moving; moving None followed by+ # renumbering would silently leave every pane in its old order.+ session.layout = layout_tree.from_grid(+ (term.key, term.column, term.slot) for term in session.terminals+ )+# "swap" exchanges the two panes and keeps the tree's exact shape;# the four sides carve the TARGET's own rectangle — the same local# meaning the split buttons have, at any depth. The moved pane's@@ -5426,20 +5550,23 @@ def coding_mode_event(session: Session | None, *, source_layer: str) -> Any:_REGISTRY: Registry | None = None+_REGISTRY_LOCK = threading.Lock()def get_registry() -> Registry:"""The process-wide Agentic-IDE registry (created on first use)."""global _REGISTRY- if _REGISTRY is None:- _REGISTRY = Registry()- return _REGISTRY+ with _REGISTRY_LOCK:+ if _REGISTRY is None:+ _REGISTRY = Registry()+ return _REGISTRYdef reset_registry() -> None:"""Drop the registry — tests only."""global _REGISTRY- _REGISTRY = None+ with _REGISTRY_LOCK:+ _REGISTRY = None__all__ = [diff --git a/jarvis/agentic_ide/workspace_catalog.py b/jarvis/agentic_ide/workspace_catalog.pynew file mode 100644index 0000000000..a4b2fc631a--- /dev/null+++ b/jarvis/agentic_ide/workspace_catalog.py@@ -0,0 +1,90 @@+"""Project ownership and open/saved workspace navigation, without launching agents."""++from __future__ import annotations++from pathlib import Path+from typing import TYPE_CHECKING, Any++from . import library, resume_store++if TYPE_CHECKING:+ from .session import Registry+++def project_graph(registry: Registry) -> dict[str, Any]:+ """Combine the project library and workspace registry by durable IDs.++ Older installations have folder-based snapshots but no project library.+ Their project rows are derived without writing during a read. Selecting a+ saved workspace remains an explicit action; this function never starts it.+ """+ from .session import MAX_TERMINALS++ projects = {+ project.id: {**project.to_dict(), "workspaces": []}+ for project in library.list_projects()+ if not project.scratch+ }++ def owner(project_id: str, folder: str) -> dict[str, Any]:+ if project_id not in projects:+ projects[project_id] = {+ **library.Project(+ id=project_id,+ path=folder,+ name=Path(folder).name or folder,+ ).to_dict(),+ "workspaces": [],+ }+ return projects[project_id]++ open_ids: set[str] = set()+ for session in registry.sessions:+ project_id = session.project_id or library.project_id_for(session.folder)+ owner(project_id, session.folder)["workspaces"].append(+ {+ **session.to_card(active=session.id == registry.active_id),+ "status": "open",+ "restorable": False,+ }+ )+ open_ids.add(session.id)++ saved = resume_store.load()+ for space in saved.workspaces if saved else []:+ if space.session_id in open_ids:+ continue+ project_id = space.project_id or library.project_id_for(space.folder)+ try:+ folder_exists = Path(space.folder).is_dir()+ except OSError:+ # A disconnected volume is unavailable, not a reason to lose history.+ folder_exists = False+ owner(project_id, space.folder)["workspaces"].append(+ {+ "id": space.session_id,+ "project_id": project_id,+ "folder": space.folder,+ "name": space.name or Path(space.folder).name or "Workspace",+ "branch": None,+ "terminals": len(space.terminals),+ "live_terminals": 0,+ "focus_mode": False,+ "created_at": space.saved_at,+ "last_active_at": space.saved_at,+ "active": False,+ "status": "closed",+ "restorable": folder_exists and len(space.terminals) <= MAX_TERMINALS,+ }+ )+ open_ids.add(space.session_id)++ active = registry.session+ return {+ "projects": list(projects.values()),+ "active_project_id": (+ active.project_id or library.project_id_for(active.folder) if active else None+ ),+ "active_workspace_id": registry.active_id,+ "max_terminals": MAX_TERMINALS,+ }diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex 8f66f7db54..5463d7c188 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -848,8 +848,20 @@ def _register_runtime_manager(manager: Any) -> None:"""Publish one Brain Manager and its public tool gateway for all surfaces."""try:from jarvis.brain.tool_gateway import BrainSupervisorToolGateway+ from jarvis.brain.workspace_tool import WorkspaceOrchestrationToolfrom jarvis.core import runtime_refs+ class WorkspaceGateway:+ async def run(self, args: dict[str, Any], *, trace_id: str = "") -> dict[str, Any]:+ # Resolve lazily, off the boot path and event loop. The runtime+ # keeps the durable receipt store; providers receive a protocol.+ import asyncio++ from jarvis.agentic_ide.orchestration import get_orchestrator++ orchestrator = await asyncio.to_thread(get_orchestrator)+ return await orchestrator.run(args, trace_id=trace_id)+async def session_tool(session_id: str) -> Any:# Compose the optional society hand lazily; no society import at boot.from jarvis.society.surface import coding_tool_for_session@@ -873,6 +885,7 @@ def _register_runtime_manager(manager: Any) -> None:session_tool=session_tool,browser_tool=browser_tool,session_tools=session_tools,+ workspace_tool=WorkspaceOrchestrationTool(WorkspaceGateway()),))except Exception as exc: # noqa: BLE001 - registration never blocks bootdiff --git a/jarvis/brain/tool_gateway.py b/jarvis/brain/tool_gateway.pyindex d3c13f0c42..53417ad42e 100644--- a/jarvis/brain/tool_gateway.py+++ b/jarvis/brain/tool_gateway.py@@ -35,11 +35,13 @@ class BrainSupervisorToolGateway:browser_tool: Callable[[str], Awaitable[Tool | None]] | None = None,session_tools: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any] | None]]| None = None,+ workspace_tool: Tool | None = None,) -> None:self._manager = managerself._session_tool = session_toolself._browser_tool = browser_toolself._session_tools = session_tools+ self._workspace_tool = workspace_toolself._lock = threading.Lock()self._fingerprint: tuple[tuple[str, int], ...] = ()self._catalog_version = 0@@ -111,6 +113,13 @@ class BrainSupervisorToolGateway:if context is not None and getattr(computer_use, "enabled", True):tools.update(context.tools or {})tools["screen_snapshot"] = LiveScreenTool()+ if self._workspace_tool is not None:+ # Live delegates coding to one addressed service. The old prompt+ # tools silently choose an ambient pane and cannot safely coexist.+ tools = {+ name: tool for name, tool in tools.items() if not name.startswith("agentic-ide-")+ }+ tools[self._workspace_tool.name] = self._workspace_toolreturn toolsdef voice_catalog(self) -> tuple[SupervisorToolDescriptor, ...]:diff --git a/jarvis/brain/workspace_tool.py b/jarvis/brain/workspace_tool.pynew file mode 100644index 0000000000..8471895f1d--- /dev/null+++ b/jarvis/brain/workspace_tool.py@@ -0,0 +1,77 @@+"""Application-owned workspace tool, independent of any voice provider."""++from __future__ import annotations++from jarvis.core.protocols import ExecutionContext, ToolResult, WorkspaceOrchestrationGateway+++class WorkspaceOrchestrationTool:+ name = "workspace-orchestrate"+ risk_tier = "ask"+ is_action_tool = True+ description = (+ "Route coding tasks to Projects > Workspaces > coding agents. Inspect the current graph; "+ "resolve explicit project/workspace/agent references (names or IDs) before sending. "+ "With no named workspace resolve uses the visible workspace, and selects an idle agent "+ "without requiring a focused terminal. Ask on needs_clarification; never guess. "+ "Send with all three resolved IDs and request_id returned by resolve; reuse it for "+ "retries. Explicit background targets never switch the visible workspace. "+ "Accepted means delivered, not completed; uncertain delivery must not be retried. "+ "After a proven pre-write refusal, resolve again for a fresh request_id "+ "before a new attempt. "+ "Use context with the same IDs to inspect recorded results. No prompt rewriting is needed."+ )+ schema = {+ "type": "object",+ "additionalProperties": False,+ "properties": {+ "action": {"type": "string", "enum": ["inspect", "resolve", "send", "context"]},+ **{+ key: {"type": "string"}+ for key in (+ "project",+ "workspace",+ "agent",+ "project_id",+ "workspace_id",+ "terminal_id",+ "prompt",+ "request_id",+ )+ },+ "request_id": {+ "type": "string",+ "pattern": "^[a-fA-F0-9]{32}$",+ "description": "Copy request_id from resolve; keep it unchanged on retries.",+ },+ "limit": {"type": "integer", "minimum": 1, "maximum": 100},+ },+ "required": ["action"],+ }++ def __init__(self, gateway: WorkspaceOrchestrationGateway) -> None:+ self.gateway = gateway++ def risk_tier_for_args(self, args: dict) -> str:+ return "safe" if args.get("action") in {"inspect", "resolve", "context"} else "ask"++ def describe_args(self, args: dict) -> dict:+ return {+ "level": "read" if self.risk_tier_for_args(args) == "safe" else "modify",+ "project": str(args.get("project_id") or args.get("project") or ""),+ "workspace": str(args.get("workspace_id") or args.get("workspace") or ""),+ "agent": str(args.get("terminal_id") or args.get("agent") or ""),+ "task": str(args.get("prompt") or "")[:240],+ }++ async def execute(self, args: dict, ctx: ExecutionContext) -> ToolResult:+ try:+ result = await self.gateway.run(args, trace_id=str(ctx.trace_id))+ except ValueError as exc:+ return ToolResult(success=False, output=None, error=str(exc))+ status = result.get("status")+ return ToolResult(+ success=result.get("success") is not False+ and status not in {"uncertain", "unavailable", "stale_target", "not_accepted"},+ output=result,+ )diff --git a/jarvis/core/protocols.py b/jarvis/core/protocols.pyindex 1724a50951..cff49036ea 100644--- a/jarvis/core/protocols.py+++ b/jarvis/core/protocols.py@@ -459,6 +459,12 @@ class Tool(Protocol):...+class WorkspaceOrchestrationGateway(Protocol):+ """Resolve and address coding sessions without ambient terminal focus."""++ async def run(self, args: dict[str, Any], *, trace_id: str = "") -> dict[str, Any]: ...++@runtime_checkableclass SupervisorToolGateway(Protocol):"""Versioned catalog and sole safety-gated execution seam for owned tools."""diff --git a/jarvis/live/config.py b/jarvis/live/config.pyindex 37be55ecb6..a135806d11 100644--- a/jarvis/live/config.py+++ b/jarvis/live/config.py@@ -34,6 +34,11 @@ class LiveConfig(BaseModel):"Discover only the tools needed for the current task using a few English ""keywords; reuse their schemas and still-current results from this conversation. ""Read tool schemas before calling. Do not bypass denied actions. "+ "For coding work use workspace-orchestrate: inspect and resolve the current "+ "Project/Workspace/agent graph, then send to the returned stable IDs. Explicit "+ "project or workspace references override visible context. Do not switch the UI "+ "to dispatch elsewhere. Ask when resolution is ambiguous. Reuse the same "+ "request_id for a retry and never replay uncertain delivery. ""Computer-use tasks use the selected thinking model and the same credential. "+ self.backend_instructions),diff --git a/jarvis/live/native.py b/jarvis/live/native.pyindex 4374fa59ac..5a5cb1bc55 100644--- a/jarvis/live/native.py+++ b/jarvis/live/native.py@@ -60,7 +60,12 @@ class NativeLiveVoiceSession(LiveVoiceSession):"screen_snapshot, inspect the image, call the desktop primitives, and verify ""the result with a new snapshot. Do not call a separate computer-use harness. ""Request confirmation for pending approvals. Use confirm_action only after "- "explicit approval. A started job is not complete. Never invent tool results."+ "explicit approval. A started job is not complete. Never invent tool results. "+ "Use workspace-orchestrate for coding tasks: inspect and resolve project, "+ "workspace and agent references, then send to the returned stable IDs. "+ "Explicit references override the visible workspace; ask on ambiguity. "+ "Do not switch the UI to address another workspace. Reuse request_id on "+ "retries and never replay uncertain delivery."),history=tuple({"role": item["role"], "text": item["delta"]} for item in self._initial_seeddiff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 5c9ea1b9d3..9f056b44c6 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -90,6 +90,7 @@ from jarvis.agentic_ide import (recap_engine,recents,resume_store,+ workspace_catalog,)from jarvis.agentic_ide.activity import has_work_behind_itfrom jarvis.agentic_ide.agent_sessions import has_conversation@@ -255,6 +256,10 @@ class TerminalRequest(BaseModel):class StartSessionRequest(BaseModel):folder: str = Field(description="Absolute path of the folder to work in.")+ project_id: str | None = Field(+ default=None, description="Owning project from the project library."+ )+ name: str | None = Field(default=None, max_length=120, description="Optional workspace name.")terminals: list[TerminalRequest] = Field(default_factory=list,description="One entry per terminal, in grid order.",@@ -262,6 +267,7 @@ class StartSessionRequest(BaseModel):class AddTerminalRequest(BaseModel):+ workspace_id: str | None = Field(default=None, description="Workspace to add the session to.")agent: str | None = Field(default=None,description="Coding agent to run; defaults to the anchor terminal's.",@@ -326,6 +332,7 @@ class AddTerminalsRequest(BaseModel):description="Coding agent to run in all of them; defaults to the last pane's.",)account: str | None = Field(default=None, description=_ACCOUNT_FIELD_DESCRIPTION)+ workspace_id: str | None = Field(default=None, description="Workspace to add the sessions to.")class MoveTerminalRequest(BaseModel):@@ -505,6 +512,7 @@ class WorkspaceCard(BaseModel):"""One open workspace, as the workspace bar shows it."""id: str+ project_id: str = ""folder: strname: strbranch: str | None = None@@ -524,6 +532,12 @@ class WorkspacesResponse(BaseModel):max_workspaces: int | None+class TerminalOrderRequest(BaseModel):+ terminal_ids: list[str] = Field(+ description="Every terminal history_id exactly once, in row-major grid order.",+ )++class SpawnGroupRequest(BaseModel):"""One "N panes running agent X" part of a fleet request."""@@ -1377,7 +1391,7 @@ def get_state_brief() -> dict:@router.get("/agents", response_model=AgentsResponse, summary="Coding agents available")-async def get_agents() -> AgentsResponse:+async def get_agents(quick: bool = False) -> AgentsResponse:"""What this machine can open in a terminal, and how to install it.Every registered entry (``jarvis.workspace.agents``): the coding-agent CLIs@@ -1386,10 +1400,17 @@ async def get_agents() -> AgentsResponse:resolvable the way the PTY will resolve it — a GUI process starts with aminimal PATH, so "installed" and "launchable from here" are not the samequestion.++ ``quick`` is the workspace launch picker: check executable resolution and+ static capabilities without running CLI versions or live model catalogs.+ The full catalog remains available to settings and model-selection views."""from jarvis.workspace import launch_picksfrom jarvis.workspace.agents import detect_agents, pty_available+ if quick:+ return await asyncio.to_thread(_quick_agent_catalog)+infos = await detect_agents()# Asked once for the whole list rather than per entry: two of these lists# come from the CLI itself (a subprocess and a file read), and an entry@@ -1419,6 +1440,35 @@ async def get_agents() -> AgentsResponse:)+def _quick_agent_catalog() -> AgentsResponse:+ """Resolve launchable coding agents without executing any CLI probe."""+ from jarvis.workspace import agents as workspace_agents+ from jarvis.workspace import launch_picks++ agents = [+ AgentStatus(+ name=spec.name,+ display_name=spec.display_name,+ installed=agent_argv(spec.name) is not None,+ version=None,+ install_command=workspace_agents.install_command(spec.name),+ kind=spec.kind,+ description=spec.description,+ custom=spec.custom,+ logo_url=spec.logo_url,+ accepts_prompts=accepts_prompts(spec.name),+ **launch_picks.offered(spec.name),+ )+ for spec in workspace_agents.coding_agents()+ ]+ return AgentsResponse(+ terminal_available=workspace_agents.pty_available(),+ max_terminals=MAX_TERMINALS,+ suggested_names=default_names(MAX_TERMINALS),+ agents=agents,+ )++@router.get("/folders", response_model=FoldersResponse, summary="Browse folders")async def get_folders(path: str | None = None, include_hidden: bool = False) -> FoldersResponse:"""Sub-folders of ``path``; without ``path``, this machine's start points."""@@ -1873,6 +1923,39 @@ def _unwrap_file_uri(value: str) -> str:return path[email protected]("/projects", summary="Projects with open and saved coding workspaces")+def get_project_workspaces() -> dict:+ """Return the sidebar hierarchy without starting any coding session."""+ return workspace_catalog.project_graph(get_registry())++[email protected]("/workspaces/{workspace_id}/terminal-order", summary="Reorder workspace terminals")+async def reorder_workspace_terminals(+ request: Request,+ workspace_id: str,+ req: TerminalOrderRequest,+) -> dict:+ registry = get_registry()+ try:+ session = await registry.reorder_terminals(workspace_id, req.terminal_ids)+ except SessionError as exc:+ status = 404 if registry.get(workspace_id) is None else 422+ raise HTTPException(status_code=status, detail=str(exc)) from exc+ await _announce_workspace(request, session, "reordered")+ return {"ok": True, "workspace": session.to_dict(), "state": registry.state()}++[email protected]("/workspaces/{workspace_id}/restore", summary="Reopen one saved workspace")+async def restore_saved_workspace(request: Request, workspace_id: str) -> dict:+ registry = get_registry()+ try:+ session = await registry.restore_workspace(workspace_id)+ except SessionError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ await _announce_workspace(request, session, "restored")+ return {"ok": True, "session": session.to_dict(), "state": registry.state()}++@router.get("/workspaces",response_model=WorkspacesResponse,@@ -1957,7 +2040,12 @@ async def start_session(request: Request, req: StartSessionRequest) -> dict:history with folders the user never selected."""try:- session = await get_registry().start(req.folder, [t.model_dump() for t in req.terminals])+ session = await get_registry().start(+ req.folder,+ [t.model_dump() for t in req.terminals],+ project_id=req.project_id,+ name=req.name,+ )except SessionError as exc:raise HTTPException(status_code=422, detail=str(exc)) from exc@@ -2488,6 +2576,7 @@ async def add_terminal(req: AddTerminalRequest) -> dict:"""try:term = await get_registry().add_terminal(+ workspace_id=req.workspace_id,agent=req.agent,name=req.name,anchor=req.anchor,@@ -2507,17 +2596,21 @@ async def add_terminals(request: Request, req: AddTerminalsRequest) -> dict:"""Open ``count`` more terminals in the running workspace.The batch behind a spoken "open five more Claude Code terminals", and the- same call the CLI makes. Placement, call-signs and the agent default are the- single-terminal endpoint's — this only repeats it and reports honestly when- the pane cap within that workspace cut the request short.+ same call the CLI makes. Oversized requests are rejected before creating a+ pane. A concurrent addition or unavailable agent can still stop a batch,+ which the response reports as a partial result.``capped`` is true when fewer panes were opened than asked for. A client MUSTsurface that: five requested with three opened is not a plain success."""registry = get_registry()+ selected_id = req.workspace_id or registry.active_idtry:created, capped = await registry.add_terminals(- req.count, agent=req.agent, account=req.account+ req.count,+ agent=req.agent,+ account=req.account,+ workspace_id=selected_id,)except SessionError as exc:raise HTTPException(status_code=409, detail=str(exc)) from exc@@ -2525,7 +2618,7 @@ async def add_terminals(request: Request, req: AddTerminalsRequest) -> dict:# Tell every connected client, so a workspace view that is already open shows# the new panes instead of a stale grid. Best-effort: the panes exist whether# or not a bus is attached (it is not, in tests).- session = registry.session+ session = registry.get(selected_id) if selected_id else Nonebus = getattr(request.app.state, "bus", None)if session is not None and bus is not None and created:try:diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsxindex 54b09f4e12..b854242ed6 100644--- a/jarvis/ui/web/frontend/src/App.tsx+++ b/jarvis/ui/web/frontend/src/App.tsx@@ -424,7 +424,7 @@ export default function App() {open: settingsSidebarOpen,onToggle: () => setSettingsSidebarOpen((open) => !open),} : undefined} />- <VoiceWarmingBanner />+ {!(["agentic-ide", "chat-workspace", "agentic-ide-classic"].includes(activeSection)) && <VoiceWarmingBanner />}{/* The one-time "all lights green" note — the first time everysection of the active voice mode answers. Never again after. */}<ReadyCelebration />@@ -447,7 +447,7 @@ export default function App() {as long as a cliConnectCoach is set in the store. */}<CliConnectPoller />{/* Blocking onboarding gate — overlays everything until first-run setup is complete. */}- <OnboardingGate />+ <OnboardingGate activeSection={activeSection} />{/* `?` anywhere in the app opens this; the chunk loads on first use. */}{shortcutsOpen && (<Suspense fallback={null}>diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsxindex 520503fc1c..fb0ec37f0c 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx@@ -975,6 +975,16 @@ describe("pane header actions", () => {expect(onToggleMaximize).toHaveBeenCalledTimes(1);});+ it("starts a pane move from its explicit handle while leaving the recap clickable", () => {+ const onArrangeStart = vi.fn();+ render(<AgenticTerminal name="Dana" displayName="Claude Code" recap="Fix login"+ appearance="dark" fontSize={13} onArrangeStart={onArrangeStart} showArrangeHandle />);+ fireEvent.pointerDown(screen.getByRole("button", { name: "Move Dana" }), { button: 0, clientX: 20, clientY: 20 });+ expect(onArrangeStart).toHaveBeenCalledTimes(1);+ fireEvent.pointerDown(screen.getByTestId("pane-recap-Dana"), { button: 0, clientX: 30, clientY: 20 });+ expect(onArrangeStart).toHaveBeenCalledTimes(1);+ });+it("explains the bar's gestures in its own card after a settled hover", () => {vi.useFakeTimers();render(diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsxindex ec6107c005..6af14fbf40 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx@@ -59,6 +59,7 @@ import "@xterm/xterm/css/xterm.css";import {BookOpenText,Check,+ GripVertical,Loader2,Maximize2,MessageSquare,@@ -503,6 +504,8 @@ interface AgenticTerminalProps {* in selection mode, has nowhere to be dropped).*/onArrangeStart?: (event: React.PointerEvent) => void;+ /** Show a dedicated grip when the surrounding layout uses insertion reorder. */+ showArrangeHandle?: boolean;/** True while THIS pane is the one being carried — it is drawn as lifted. */arranging?: boolean;/**@@ -561,6 +564,7 @@ export function AgenticTerminal({onOpenChat,restartToken = 0,onArrangeStart,+ showArrangeHandle = false,arranging = false,layoutBusy = false,}: AgenticTerminalProps) {@@ -2289,6 +2293,7 @@ export function AgenticTerminal({status={visibleStatus}statusDetail={statusDetail}onArrangeStart={onArrangeStart}+ showArrangeHandle={showArrangeHandle}arranging={arranging}name={name}displayName={displayName}@@ -2464,6 +2469,7 @@ function PaneHeader({status,statusDetail,onArrangeStart,+ showArrangeHandle = false,arranging = false,onOpenConversation,onOpenChat,@@ -2493,6 +2499,7 @@ function PaneHeader({statusDetail?: string;/** Press on the header picks the pane up; absent leaves it undraggable. */onArrangeStart?: (event: React.PointerEvent) => void;+ showArrangeHandle?: boolean;arranging?: boolean;/** Opens the pane's recorded conversation — the mode-proof scroll history. */onOpenConversation?: () => void;@@ -2618,7 +2625,7 @@ function PaneHeader({// a maximized pane cannot be dragged, so its sentence never claims it can.const tipText = [onArrangeStart- ? `Drag ${name} by this bar to move it — drop it on another terminal to swap, or near an edge to place it there.`+ ? `Drag ${name} by this bar to move it.`: "",onToggleMaximize? onArrangeStart@@ -2748,6 +2755,21 @@ function PaneHeader({}}/><div className="flex min-w-0 flex-1 items-center gap-2">+ {showArrangeHandle && onArrangeStart && (+ <button type="button" aria-label={`Move ${name}`} title={`Move ${name}`}+ data-ide-drag-handle="true"+ data-testid={`pane-move-${name}`}+ onPointerDown={(event) => {+ hideTip();+ event.stopPropagation();+ onArrangeStart(event);+ }}+ onClick={(event) => event.stopPropagation()}+ className="flex h-5 w-5 shrink-0 cursor-grab items-center justify-center rounded text-[color:var(--pane-ink-muted)] hover:bg-[color:var(--pane-chip)] hover:text-[color:var(--pane-ink)] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[color:var(--pane-accent)] active:cursor-grabbing"+ style={{ touchAction: "none" }}>+ <GripVertical className="h-3.5 w-3.5" aria-hidden="true" />+ </button>+ )}{draft !== null ? (/** The call-sign, being typed.diff --git a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsxnew file mode 100644index 0000000000..017ab56f7d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx@@ -0,0 +1,22 @@+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, expect, it } from "vitest";+import { IdeProjectTree } from "./IdeProjectTree";+import { useIdeProjectsStore } from "@/store/ideProjects";+import type { IdeProject } from "@/lib/agenticIdeApi";++afterEach(cleanup);++it("preserves a manually collapsed active project across graph refreshes", () => {+ const project = { id: "p1", path: "/app", name: "App", archived: false, scratch: false,+ workspaces: [{ id: "w1", name: "Work", status: "open", live_terminals: 1, terminals: 1, restorable: true }] } as IdeProject;+ useIdeProjectsStore.setState({ projects: [project], activeWorkspaceId: "w1", action: null });+ render(<IdeProjectTree />);+ const selected = screen.getByTestId("ide-workspace-w1");+ expect(selected.className).toContain("bg-muted");+ expect(selected.className).not.toContain("bg-accent");+ const toggle = screen.getByRole("button", { name: "Collapse App" });+ fireEvent.click(toggle);+ expect(screen.queryByTestId("ide-workspace-w1")).toBeNull();+ act(() => useIdeProjectsStore.getState().publish([{ ...project, workspaces: [...project.workspaces] }], "w1"));+ expect(screen.queryByTestId("ide-workspace-w1")).toBeNull();+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsxnew file mode 100644index 0000000000..6694c097fd--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx@@ -0,0 +1,66 @@+import { useEffect, useRef, useState } from "react";+import { ChevronDown, ChevronRight, Folder, Plus } from "lucide-react";+import { useIdeProjectsStore } from "@/store/ideProjects";++/** The IDE's compact project navigation. Workspace IDs, never paths, select runtime context. */+export function IdeProjectTree() {+ const projects = useIdeProjectsStore((state) => state.projects);+ const activeWorkspaceId = useIdeProjectsStore((state) => state.activeWorkspaceId);+ const connectProject = useIdeProjectsStore((state) => state.connectProject);+ const newWorkspace = useIdeProjectsStore((state) => state.newWorkspace);+ const activateWorkspace = useIdeProjectsStore((state) => state.activateWorkspace);+ const [expanded, setExpanded] = useState<string[]>([]);+ const lastAutoExpandedWorkspace = useRef<string | null>(null);++ useEffect(() => {+ const current = projects.find((project) => project.workspaces.some((workspace) => workspace.id === activeWorkspaceId));+ if (current && activeWorkspaceId !== lastAutoExpandedWorkspace.current) {+ lastAutoExpandedWorkspace.current = activeWorkspaceId;+ setExpanded((old) => old.includes(current.id) ? old : [...old, current.id]);+ }+ }, [activeWorkspaceId, projects]);++ return <div data-testid="ide-project-tree" className="mt-1 px-2 pb-2">+ <div className="group flex items-center justify-between px-2 pb-1 text-xs font-medium text-muted-foreground">+ <span>Projects</span>+ <button type="button" aria-label="Connect project" title="Connect project folder" onClick={connectProject}+ className="rounded p-1 hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <Plus className="h-3.5 w-3.5" />+ </button>+ </div>+ {projects.filter((project) => !project.archived && !project.scratch).map((project) => {+ const open = expanded.includes(project.id);+ const active = project.workspaces.some((workspace) => workspace.id === activeWorkspaceId);+ return <div key={project.id} className="mb-0.5">+ <div className={`group flex min-h-9 items-center rounded-lg transition-colors hover:bg-muted/70 ${active ? "bg-muted" : ""}`}>+ <button type="button" aria-label={`${open ? "Collapse" : "Expand"} ${project.name}`} aria-expanded={open}+ onClick={() => setExpanded((old) => open ? old.filter((id) => id !== project.id) : [...old, project.id])}+ className="flex min-w-0 flex-1 items-center gap-2 px-2 py-2 text-left text-sm text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {open ? <ChevronDown className="h-3.5 w-3.5 shrink-0 text-muted-foreground" /> : <ChevronRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}+ <Folder className="h-4 w-4 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate">{project.name}</span>+ </button>+ <button type="button" aria-label={`New workspace in ${project.name}`} title="New workspace" onClick={() => newWorkspace(project.id)}+ className="mr-1 rounded p-1.5 text-muted-foreground opacity-70 hover:bg-background hover:text-foreground group-hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <Plus className="h-3.5 w-3.5" />+ </button>+ </div>+ {open && <div className="ml-5 border-l border-border/70 pl-2">+ {project.workspaces.map((workspace) => <button key={workspace.id} type="button"+ data-testid={`ide-workspace-${workspace.id}`}+ aria-current={workspace.id === activeWorkspaceId ? "page" : undefined}+ title={workspace.status === "closed" && !workspace.restorable ? "This workspace cannot be restored on this machine" : undefined}+ disabled={workspace.status === "closed" && !workspace.restorable}+ onClick={() => activateWorkspace(workspace.id)}+ className={`flex min-h-8 w-full items-center gap-2 rounded-md px-2 text-left text-xs transition-colors hover:bg-muted/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-45 ${workspace.id === activeWorkspaceId ? "bg-muted text-foreground" : "text-muted-foreground"}`}>+ <span className={`h-1.5 w-1.5 shrink-0 rounded-full ${workspace.status === "open" && workspace.live_terminals > 0 ? "bg-emerald-500" : "bg-muted-foreground/40"}`} />+ <span className="min-w-0 flex-1 truncate">{workspace.name}</span>+ <span className="tabular-nums opacity-70">{workspace.terminals}</span>+ </button>)}+ {project.workspaces.length === 0 && <button type="button" onClick={() => newWorkspace(project.id)} className="px-2 py-2 text-left text-xs text-muted-foreground hover:text-foreground">Create workspace</button>}+ </div>}+ </div>;+ })}+ {projects.every((project) => project.archived || project.scratch) && <p className="px-2 py-2 text-xs text-muted-foreground">Connect a folder to start a project.</p>}+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsxnew file mode 100644index 0000000000..15a6e4f497--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsx@@ -0,0 +1,63 @@+import { describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import type { SessionState } from "@/lib/agenticIdeApi";+const reorder = vi.hoisted(() => vi.fn());+vi.mock("@/lib/agenticIdeApi", () => ({ reorderIdeTerminals: reorder }));+vi.mock("./AgenticTerminal", () => ({ AgenticTerminal: ({ name, onToggleMaximize, onArrangeStart, showArrangeHandle }: { name: string; onToggleMaximize: () => void; onArrangeStart?: (event: React.PointerEvent) => void; showArrangeHandle?: boolean }) => <>+ <button onClick={onToggleMaximize}>{name}</button>+ {showArrangeHandle && <button type="button" data-ide-drag-handle="true" onPointerDown={onArrangeStart}>Move {name}</button>}+</> }));+vi.mock("@/hooks/useTheme", () => ({ useThemeValue: () => "dark" }));+import { columnsForSessions } from "./WorkspaceTerminalGrid";+import { WorkspaceTerminalGrid } from "./WorkspaceTerminalGrid";++class ResizeObserverStub { observe() {} disconnect() {} }+vi.stubGlobal("ResizeObserver", ResizeObserverStub);+vi.stubGlobal("PointerEvent", MouseEvent);++describe("workspace session columns", () => {+ it("uses the compact reference layout on a wide desktop", () => {+ expect([1, 2, 3, 4, 5, 6, 7, 8].map((count) => columnsForSessions(count, 1800)))+ .toEqual([1, 2, 3, 2, 3, 3, 4, 4]);+ });++ it("limits columns as available width shrinks", () => {+ expect(columnsForSessions(8, 680)).toBe(4);+ expect(columnsForSessions(3, 310)).toBe(2);+ expect(columnsForSessions(2, 310)).toBe(1);+ });+});++it("shows the remaining pane when a maximized session closes", async () => {+ const terminal = (name: string) => ({ name, key: name, history_id: name, display_name: name });+ const session = (names: string[]) => ({ id: "w1", terminals: names.map(terminal) }) as SessionState;+ const props = { onChanged: vi.fn(), onAdd: vi.fn(), onClose: vi.fn(), onSelect: vi.fn(), selected: "", fontSize: 13, appearance: null };+ const { rerender } = render(<WorkspaceTerminalGrid session={session(["T1", "T2"])} {...props} />);+ fireEvent.click(screen.getByRole("button", { name: "T1" }));+ rerender(<WorkspaceTerminalGrid session={session(["T2"])} {...props} />);+ await waitFor(() => expect(screen.getByRole("button", { name: "T2" }).closest("[data-session-id]")?.className).not.toContain("hidden"));+});++it("reorders through the visible handle and leaves terminal keys alone", async () => {+ reorder.mockReset();+ const session = { id: "w1", terminals: ["T1", "T2"].map((name) => ({ name, key: name, history_id: name, display_name: name })) } as SessionState;+ reorder.mockResolvedValue({ session });+ const props = { onChanged: vi.fn(), onAdd: vi.fn(), onClose: vi.fn(), onSelect: vi.fn(), selected: "", fontSize: 13, appearance: null };+ render(<WorkspaceTerminalGrid session={session} {...props} />);+ const source = screen.getByRole("button", { name: "Move T1" });+ const target = document.querySelector<HTMLElement>('[data-session-id="T2"]');+ Object.defineProperty(document, "elementFromPoint", { configurable: true, value: vi.fn(() => target) });+ fireEvent.pointerDown(source, { button: 0, clientX: 10, clientY: 10 });+ fireEvent.pointerMove(window, { clientX: 35, clientY: 10 });+ fireEvent.pointerUp(window, { clientX: 35, clientY: 10 });+ await waitFor(() => expect(reorder).toHaveBeenCalledWith("w1", ["T2", "T1"]));++ reorder.mockClear();+ const tile = document.querySelector<HTMLElement>('[data-session-id="T1"]')!;+ const terminalInput = document.createElement("textarea");+ tile.appendChild(terminalInput);+ fireEvent.keyDown(terminalInput, { altKey: true, key: "ArrowRight" });+ expect(reorder).not.toHaveBeenCalled();+ fireEvent.keyDown(tile, { altKey: true, key: "ArrowRight" });+ await waitFor(() => expect(reorder).toHaveBeenCalledWith("w1", ["T2", "T1"]));+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsxnew file mode 100644index 0000000000..190098d13e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx@@ -0,0 +1,122 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { AgenticTerminal } from "./AgenticTerminal";+import type { SessionState, TerminalState } from "@/lib/agenticIdeApi";+import { reorderIdeTerminals } from "@/lib/agenticIdeApi";+import { useThemeValue } from "@/hooks/useTheme";+import { useEventStore } from "@/store/events";++export function columnsForSessions(count: number, width: number): number {+ if (count < 1) return 1;+ const readable = Math.max(1, Math.min(4, Math.floor(width / 320) || 1));+ const desired = count <= 3 ? count : count <= 4 ? 2 : count <= 6 ? 3 : 4;+ return Math.max(Math.ceil(count / 2), Math.min(readable, desired));+}++interface Props {+ session: SessionState;+ onChanged: (session: SessionState) => void;+ onAdd: () => void;+ onClose: (terminal: TerminalState) => void;+ onSelect: (name: string) => void;+ selected: string;+ fontSize: number;+ appearance: "light" | "dark" | null;+}++export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSelect, selected, fontSize, appearance }: Props) {+ const theme = useThemeValue();+ const pushToast = useEventStore((state) => state.pushToast);+ const frame = useRef<HTMLDivElement>(null);+ const [width, setWidth] = useState(1280);+ const [dragging, setDragging] = useState<string | null>(null);+ const [hover, setHover] = useState<string | null>(null);+ const [maximized, setMaximized] = useState<string | null>(null);+ const dragCleanup = useRef<(() => void) | null>(null);+ const ordered = session.terminals;+ const columns = columnsForSessions(ordered.length, width);++ useEffect(() => {+ if (maximized && !ordered.some((terminal) => (terminal.history_id ?? terminal.key) === maximized)) setMaximized(null);+ }, [maximized, ordered]);++ useEffect(() => {+ const node = frame.current;+ if (!node) return;+ const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));+ observer.observe(node);+ return () => observer.disconnect();+ }, []);+ useEffect(() => () => dragCleanup.current?.(), []);++ const move = useCallback(async (sourceId: string, targetId: string) => {+ if (sourceId === targetId) return;+ const ids = ordered.map((terminal) => terminal.history_id ?? terminal.key);+ const from = ids.indexOf(sourceId);+ const to = ids.indexOf(targetId);+ if (from < 0 || to < 0) return;+ ids.splice(to, 0, ids.splice(from, 1)[0]);+ try {+ const state = await reorderIdeTerminals(session.id, ids);+ if (state.session) onChanged(state.session);+ } catch (error) {+ pushToast("error", (error as Error).message);+ }+ }, [onChanged, ordered, pushToast, session.id]);++ const startDrag = useCallback((id: string, event: React.PointerEvent) => {+ if (event.button !== 0 || dragCleanup.current) return;+ const initialX = event.clientX;+ const initialY = event.clientY;+ let armed = false;+ const onMove = (motion: PointerEvent) => {+ if (!armed && Math.hypot(motion.clientX - initialX, motion.clientY - initialY) > 5) { armed = true; setDragging(id); }+ if (!armed) return;+ const tile = document.elementFromPoint(motion.clientX, motion.clientY)?.closest<HTMLElement>("[data-session-id]");+ setHover(tile?.dataset.sessionId ?? null);+ };+ const cleanup = () => {+ window.removeEventListener("pointermove", onMove);+ window.removeEventListener("pointerup", onUp);+ window.removeEventListener("pointercancel", onCancel);+ dragCleanup.current = null;+ setDragging(null);+ setHover(null);+ };+ const onCancel = () => cleanup();+ const onUp = (release: PointerEvent) => {+ cleanup();+ const tile = document.elementFromPoint(release.clientX, release.clientY)?.closest<HTMLElement>("[data-session-id]");+ if (armed && tile?.dataset.sessionId) void move(id, tile.dataset.sessionId);+ };+ dragCleanup.current = cleanup;+ window.addEventListener("pointermove", onMove);+ window.addEventListener("pointerup", onUp);+ window.addEventListener("pointercancel", onCancel);+ }, [move]);++ const tiles = useMemo(() => ordered.map((terminal) => ({ ...terminal, stableId: terminal.history_id ?? terminal.key })), [ordered]);+ return <div ref={frame} data-testid="workspace-terminal-grid" className="h-full min-h-0 overflow-auto p-2.5">+ <div className="grid h-full gap-2.5" style={{ gridTemplateColumns: `repeat(${maximized ? 1 : columns}, minmax(0, 1fr))`, gridTemplateRows: `repeat(${maximized ? 1 : Math.ceil(tiles.length / columns)}, minmax(0, 1fr))`, minWidth: maximized ? undefined : `${columns * 320}px`, minHeight: "280px" }}>+ {tiles.map((terminal, index) => <div key={terminal.stableId} data-session-id={terminal.stableId}+ tabIndex={0} aria-label={`${terminal.name}, position ${index + 1} of ${tiles.length}. Press Alt+Arrow keys to reorder.`}+ onKeyDown={(event) => {+ if (event.target !== event.currentTarget && !(event.target instanceof HTMLElement && event.target.closest("[data-ide-drag-handle]"))) return;+ if (!event.altKey || !["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) return;+ event.preventDefault();+ const delta = event.key === "ArrowLeft" ? -1 : event.key === "ArrowRight" ? 1 : event.key === "ArrowUp" ? -columns : columns;+ const target = tiles[index + delta];+ if (target) void move(terminal.stableId, target.stableId);+ }}+ className={`relative min-h-0 min-w-0 rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${dragging === terminal.stableId ? "opacity-60" : ""} ${hover === terminal.stableId && dragging !== terminal.stableId ? "ring-2 ring-primary" : ""} ${maximized && maximized !== terminal.stableId ? "hidden" : ""}`}>+ <AgenticTerminal name={terminal.name} workspaceId={session.id} displayName={terminal.display_name}+ recap={terminal.recap} promptCount={terminal.prompts_sent} appearance={appearance ?? theme} fontSize={fontSize}+ focused={selected === terminal.name} onFocus={() => onSelect(terminal.name)}+ maximized={maximized === terminal.stableId} onToggleMaximize={() => setMaximized((current) => current === terminal.stableId ? null : terminal.stableId)}+ onArrangeStart={maximized ? undefined : (event) => startDrag(terminal.stableId, event)}+ showArrangeHandle={!maximized}+ onClose={() => onClose(terminal)} onAttachError={(message) => pushToast("error", message)}+ splitDisabled={tiles.length >= 8} onSplit={() => onAdd()} />+ </div>)}+ </div>+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsxindex 05800ec41e..f1ed955b8f 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx@@ -13,6 +13,18 @@ import { isSectionId, useEventStore } from "@/store/events";import { useHomeStore } from "@/store/home";import { useIdeChatStore } from "@/store/ideChat";+test("IDE sidebar puts Projects first and returns to the normal chat navigation", () => {+ act(() => useEventStore.setState({ activeSection: "agentic-ide" }));+ renderSidebar();+ expect(screen.getByTestId("ide-project-tree")).toBeDefined();+ expect(screen.queryByTestId("sidebar-new-chat")).toBeNull();+ expect(screen.queryByTestId("nav-row-agentic-ide")).toBeNull();+ fireEvent.click(screen.getByTestId("ide-back-to-jarvis"));+ expect(useEventStore.getState().activeSection).toBe("chats");+ expect(screen.getByTestId("sidebar-new-chat")).toBeDefined();+ cleanup();+});+// The sidebar header avatar must mirror the chosen on-screen display style:// the ghost mascot ONLY when the user explicitly picked "mascot"; the slim bar// for "jarvis_bar"/"none" and while the style is still loading (config null).diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsxindex 5df6fec658..2e6ada94e9 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx@@ -3,6 +3,7 @@ import {MessageSquare,Mic,ChevronDown,+ ChevronLeft,MoreHorizontal,Store,UserCircle2,@@ -28,8 +29,7 @@ import { RecentChats } from "@/components/home/RecentChats";import { useConversations } from "@/hooks/useConversations";import { useHomeStore } from "@/store/home";import { useAgentChatStore } from "@/store/agentChat";-import { useIdeChatStore } from "@/store/ideChat";-import { WorkspaceChats } from "@/components/agentic/WorkspaceChats";+import { IdeProjectTree } from "@/components/agentic/IdeProjectTree";import { useAppInstance } from "@/hooks/useAppInstance";import { usePublishIdentity } from "@/components/marketplace/PublishIdentity";import { GigiMark } from "@/components/GigiMark";@@ -199,7 +199,6 @@ export function Sidebar({* Only while the IDE is the section on screen: every other section gets the* plain navigation, with no workspace list bolted on top of it.*/- const ideView = useIdeChatStore((s) => s.view);/** Is there anything for this column to list?*@@ -216,9 +215,7 @@ export function Sidebar({* workspace as its own band now, so it has something true to say for as* long as any of them is running.*/- const ideWorkspaceOpen = useIdeChatStore((s) => s.workspaces.length > 0);const onIdeSection = IDE_SECTIONS.includes(active);- const chatFace = onIdeSection && ideWorkspaceOpen && ideView === "chat";const [moreOpen, setMoreOpen] = useState(false);const [newChatOpen, setNewChatOpen] = useState(false);const [startingVoice, setStartingVoice] = useState(false);@@ -465,7 +462,13 @@ export function Sidebar({</div><div className="flex min-h-0 flex-1 flex-col overflow-y-auto scrollbar-jarvis">- <nav aria-label={t("sidebar.sections")} className="space-y-1 px-2 py-2">+ {onIdeSection ? <nav aria-label="IDE navigation" className="px-2 pt-2">+ <button type="button" data-testid="ide-back-to-jarvis" onClick={() => setActive("chats")}+ className="flex min-h-8 w-full items-center gap-2 rounded-md px-2 text-left text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <ChevronLeft aria-hidden className="h-3.5 w-3.5 shrink-0" />+ {!railed && <span>Back to Jarvis</span>}+ </button>+ </nav> : <nav aria-label={t("sidebar.sections")} className="space-y-1 px-2 py-2"><ul className="space-y-1"><li><Dialog.Root open={newChatOpen} onOpenChange={(open) => { if (!startingVoiceRef.current) setNewChatOpen(open); }}><Dialog.Trigger asChild><button type="button" data-testid="sidebar-new-chat"@@ -503,10 +506,10 @@ export function Sidebar({{!railed && <span>{t(moreOpen ? "sidebar.show_less" : "sidebar.more")}</span>}</button>{moreOpen && <ul id="sidebar-more" className="space-y-1">{moreItems.map((item) => renderRow(item))}</ul>}- </nav>- {!railed && <section className="mt-4 px-2 pb-3" aria-label={t("sidebar.recent_chats")}>- {chatFace ? <WorkspaceChats /> : <RecentChats />}- </section>}+ </nav>}+ {!railed && (onIdeSection+ ? <IdeProjectTree />+ : <section className="mt-4 px-2 pb-3" aria-label={t("sidebar.recent_chats")}><RecentChats /></section>)}</div>{/* The footer is one button now, not a popup: it opens the Settings hubdiff --git a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.test.tsxindex 990d3a537c..df7075481b 100644--- a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.test.tsx+++ b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.test.tsx@@ -1,4 +1,4 @@-import { cleanup, render, screen, waitFor } from "@testing-library/react";+import { act, cleanup, render, screen, waitFor } from "@testing-library/react";import { afterEach, expect, it, vi } from "vitest";vi.mock("./OnboardingFlow", () => ({ OnboardingFlow: () => <div data-testid="flow" /> }));@@ -33,6 +33,14 @@ it("shows the overlay when not completed", async () => {await waitFor(() => expect(screen.getByRole("dialog")).toBeDefined());});+it("keeps a fresh install's IDE accessible without app-wide onboarding", async () => {+ stub({ ...base, completed: false });+ const { rerender } = render(<OnboardingGate activeSection="agentic-ide" />);+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ rerender(<OnboardingGate activeSection="chats" />);+ await waitFor(() => expect(screen.getByRole("dialog")).toBeDefined());+});+it("renders nothing when completed", async () => {stub({ ...base, completed: true });render(<OnboardingGate />);@@ -70,6 +78,6 @@ it("closes when the flow reports completion", async () => {stub({ ...base, completed: false });render(<OnboardingGate />);await screen.findByTestId("flow");- window.dispatchEvent(new CustomEvent("jarvis:onboarding-changed"));+ act(() => window.dispatchEvent(new CustomEvent("jarvis:onboarding-changed")));await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());});diff --git a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsxindex 14c79b139f..ba2b1d5352 100644--- a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx+++ b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx@@ -27,7 +27,7 @@ const OnboardingFlow = lazy(() =>* onboarding/completed state changes until the final step, so the* restart-loop bug cannot come back through this path.*/-export function OnboardingGate() {+export function OnboardingGate({ activeSection }: { activeSection?: string } = {}) {const onb = useOnboarding();// Set once the user completes the guide (the "Start" / complete() path// dispatches jarvis:onboarding-changed). It dismisses the stage even under@@ -49,6 +49,10 @@ export function OnboardingGate() {[],);+ // The IDE can connect a folder and launch agents without completing app-wide+ // voice setup. An explicit onboarding preview still opens when requested.+ if (!forced && ["agentic-ide", "chat-workspace", "agentic-ide-classic"].includes(activeSection ?? "")) return null;+if (onb.loading) return null;if (onb.error) return null; // fail open — never trap the userif (!onb.state) return null;diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.tsindex 94b35d739c..0d97c80ec9 100644--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts@@ -12,6 +12,7 @@ import type {CuratedModel,PermissionModeOption,} from "./agentChatApi";+import type { ChatProject } from "./chatLibraryApi";export interface AgentStatus {name: string;@@ -354,6 +355,8 @@ export interface ActivityResponse {export interface SessionState {id: string;+ project_id?: string | null;+ name?: string;folder: string;project: ProjectProfile;created_at: number;@@ -376,6 +379,7 @@ export interface SessionState {*/export interface WorkspaceCard {id: string;+ project_id?: string | null;folder: string;/** Project name — what the tab is labelled with. */name: string;@@ -389,6 +393,42 @@ export interface WorkspaceCard {active: boolean;}+export interface ProjectWorkspace extends WorkspaceCard {+ status: "open" | "closed";+ restorable: boolean;+}++export interface IdeProject extends ChatProject {+ workspaces: ProjectWorkspace[];+}++export interface IdeProjectsResponse {+ projects: IdeProject[];+ active_project_id: string | null;+ active_workspace_id: string | null;+ max_terminals: number;+}++export function fetchIdeProjects(): Promise<IdeProjectsResponse> {+ return getJson<IdeProjectsResponse>("/api/agentic-ide/projects");+}++export async function restoreIdeWorkspace(id: string): Promise<IdeState> {+ const res = await fetch(`/api/agentic-ide/workspaces/${encodeURIComponent(id)}/restore`, { method: "POST" });+ if (!res.ok) throw new Error(await detail(res));+ return ((await res.json()) as { state: IdeState }).state;+}++export async function reorderIdeTerminals(id: string, terminalIds: string[]): Promise<IdeState> {+ const res = await fetch(`/api/agentic-ide/workspaces/${encodeURIComponent(id)}/terminal-order`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ terminal_ids: terminalIds }),+ });+ if (!res.ok) throw new Error(await detail(res));+ return ((await res.json()) as { state: IdeState }).state;+}+/*** Which subscription new terminals of one coding CLI open on.*@@ -586,8 +626,8 @@ export function fetchIdeState(): Promise<IdeState> {return getJson<IdeState>("/api/agentic-ide/state");}-export function fetchIdeAgents(): Promise<AgentsResponse> {- return getJson<AgentsResponse>("/api/agentic-ide/agents");+export function fetchIdeAgents(quick = false): Promise<AgentsResponse> {+ return getJson<AgentsResponse>(`/api/agentic-ide/agents${quick ? "?quick=true" : ""}`);}/** One entry, probed just now — what an install dialog watches for. */@@ -1164,11 +1204,12 @@ export async function resolveDroppedFolder(payload: {export async function startIdeSession(folder: string,terminals: TerminalPlan[],+ options: { projectId?: string; name?: string } = {},): Promise<IdeState> {const res = await fetch("/api/agentic-ide/session", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ folder, terminals }),+ body: JSON.stringify({ folder, terminals, project_id: options.projectId, name: options.name }),});if (!res.ok) throw new Error(await detail(res));const body = (await res.json()) as { session: SessionState; state: IdeState };@@ -1288,6 +1329,7 @@ export async function forgetResumeOffer(): Promise<void> {* inherits the anchor's. Returns the updated workspace.*/export async function addTerminal(payload: {+ workspace_id?: string;anchor?: string;direction?: "right" | "down";agent?: string;diff --git a/jarvis/ui/web/frontend/src/store/ideProjects.ts b/jarvis/ui/web/frontend/src/store/ideProjects.tsnew file mode 100644index 0000000000..466f7a0867--- /dev/null+++ b/jarvis/ui/web/frontend/src/store/ideProjects.ts@@ -0,0 +1,27 @@+import { create } from "zustand";+import type { IdeProject } from "@/lib/agenticIdeApi";++type IdeAction =+ | { kind: "connect-project"; nonce: number }+ | { kind: "new-workspace"; projectId: string; nonce: number }+ | { kind: "activate-workspace"; workspaceId: string; nonce: number };++interface IdeProjectsStore {+ projects: IdeProject[];+ activeWorkspaceId: string | null;+ action: IdeAction | null;+ publish: (projects: IdeProject[], activeWorkspaceId: string | null) => void;+ connectProject: () => void;+ newWorkspace: (projectId: string) => void;+ activateWorkspace: (workspaceId: string) => void;+}++export const useIdeProjectsStore = create<IdeProjectsStore>((set) => ({+ projects: [],+ activeWorkspaceId: null,+ action: null,+ publish: (projects, activeWorkspaceId) => set({ projects, activeWorkspaceId }),+ connectProject: () => set((state) => ({ action: { kind: "connect-project", nonce: (state.action?.nonce ?? 0) + 1 } })),+ newWorkspace: (projectId) => set((state) => ({ action: { kind: "new-workspace", projectId, nonce: (state.action?.nonce ?? 0) + 1 } })),+ activateWorkspace: (workspaceId) => set((state) => ({ action: { kind: "activate-workspace", workspaceId, nonce: (state.action?.nonce ?? 0) + 1 } })),+}));diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeActivation.test.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeActivation.test.tsxnew file mode 100644index 0000000000..7b7c1703d7--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeActivation.test.tsx@@ -0,0 +1,52 @@+import { act, cleanup, render, screen, waitFor } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";+import { useIdeProjectsStore } from "@/store/ideProjects";+import { AgenticIdeView } from "./AgenticIdeView";++const api = vi.hoisted(() => ({+ fetchIdeState: vi.fn(), fetchIdeProjects: vi.fn(), fetchIdeAgents: vi.fn(),+ activateWorkspace: vi.fn(), restoreIdeWorkspace: vi.fn(),+}));+vi.mock("@/lib/agenticIdeApi", () => api);+vi.mock("@/lib/chatLibraryApi", () => ({ openProject: vi.fn() }));+vi.mock("@/store/events", () => ({ useEventStore: (select: (value: unknown) => unknown) => select({ pushToast: vi.fn() }) }));+vi.mock("@/components/agentic/FolderPicker", () => ({ FolderPicker: () => null }));+vi.mock("@/components/agentic/VoiceBubble", () => ({ VoiceBubble: () => null, storedVoiceBubbleOpen: () => false, storeVoiceBubbleOpen: vi.fn() }));+vi.mock("@/components/agentic/WorkspaceTerminalGrid", () => ({ WorkspaceTerminalGrid: ({ session }: { session: { id: string } }) => <div data-testid="live-grid">{session.id}</div> }));++afterEach(cleanup);++it("serializes rapid workspace switches and displays only the latest result", async () => {+ const card = (id: string) => ({ id, project_id: "p1", folder: "/code/app", name: id, branch: null,+ terminals: 1, live_terminals: 1, focus_mode: false, created_at: 0, last_active_at: 0, active: false,+ status: "open", restorable: true });+ const stateFor = (id: string) => ({ active: true, active_id: id, max_terminals: 8, workspaces: [], session: {+ id, project_id: "p1", folder: "/code/app", name: id, created_at: 0, focus_mode: false,+ project: { name: "App" }, terminals: [],+ } });+ let current: Record<string, unknown> = { active: false, active_id: null, session: null, workspaces: [], max_terminals: 8 };+ const project = { id: "p1", path: "/code/app", name: "App", archived: false, scratch: false, workspaces: [card("A"), card("B")] };+ api.fetchIdeState.mockImplementation(() => Promise.resolve(current));+ api.fetchIdeProjects.mockImplementation(() => Promise.resolve({ projects: [project],+ active_project_id: "p1", active_workspace_id: current.active_id, max_terminals: 8 }));+ api.fetchIdeAgents.mockResolvedValue({ terminal_available: true, max_terminals: 8, agents: [] });+ useIdeProjectsStore.setState({ projects: [], activeWorkspaceId: null, action: null });+ let resolveA!: (value: unknown) => void;+ let resolveB!: (value: unknown) => void;+ api.activateWorkspace.mockImplementation((id: string) => id === "A"+ ? new Promise((resolve) => { resolveA = resolve; })+ : new Promise((resolve) => { resolveB = resolve; }));++ render(<AgenticIdeView />);+ await screen.findByText("Choose a workspace");+ act(() => useIdeProjectsStore.getState().activateWorkspace("A"));+ await waitFor(() => expect(api.activateWorkspace).toHaveBeenCalledWith("A"));+ act(() => useIdeProjectsStore.getState().activateWorkspace("B"));+ expect(api.activateWorkspace).toHaveBeenCalledTimes(1);+ act(() => resolveA(stateFor("A")));+ await waitFor(() => expect(api.activateWorkspace).toHaveBeenCalledWith("B"));+ expect(screen.queryByTestId("live-grid")).toBeNull();+ current = stateFor("B");+ act(() => resolveB(current));+ expect((await screen.findByTestId("live-grid")).textContent).toBe("B");+});diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsxindex f6ddee5167..1f87abb347 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx@@ -1,1201 +1,104 @@-import {- cleanup,- fireEvent,- render,- screen,- waitFor,-} from "@testing-library/react";+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--// jsdom ships no ResizeObserver, and the workspace grid measures itself with-// one to decide how many panes fit side by side.-class ResizeObserverPolyfill {- observe(): void {}- unobserve(): void {}- disconnect(): void {}-}-if (typeof globalThis.ResizeObserver === "undefined") {- globalThis.ResizeObserver =- ResizeObserverPolyfill as unknown as typeof ResizeObserver;-}--// Most component-specific copy remains an identity translation in this suite.-// The launcher navigation uses real English labels so its accessible workflow-// stays readable while the locale dictionaries are tested separately.-const launcherEnglish = vi.hoisted<Record<string, string>>(() => ({- "workspace_launcher.wizard.steps.folder.title": "Choose the project folder",- "workspace_launcher.wizard.steps.layout.title": "Shape the workspace",- "workspace_launcher.wizard.steps.view.title": "Choose how to read the workspace",- "workspace_launcher.wizard.steps.review.title": "Review before opening",- "workspace_launcher.wizard.continue_layout": "Continue to layout",- "workspace_launcher.wizard.continue_agents": "Continue to agents",- "workspace_launcher.wizard.choose_view": "Choose the view",- "workspace_launcher.wizard.review_workspace": "Review workspace",- "workspace_launcher.wizard.open_workspace": "Open workspace",- "workspace_launcher.wizard.terminal_unavailable_before":- "This machine has no usable terminal backend. Required:",- "workspace_launcher.wizard.no_cli":- "No coding-agent CLI was found on this machine's PATH.",- "workspace_launcher.wizard.open_clis": "Open CLIs",- "workspace_launcher.wizard.views.grid.title": "Terminal grid",- "workspace_launcher.wizard.views.chat.title": "Chat",-}));-vi.mock("@/i18n", () => ({- useT: () => (key: string) => launcherEnglish[key] ?? key,- // The chat stage inside the grid reads these two as well.- translate: (key: string) => launcherEnglish[key] ?? key,- fill: (template: string, vars: Record<string, string | number>) =>- template.replace(/\{(\w+)\}/g, (_m, name: string) => String(vars[name] ?? `{${name}}`)),-}));--// The workspace grid follows the app theme for its terminal colours; this test-// renders the view outside the provider, so the hook is stubbed.-vi.mock("@/hooks/useTheme", () => ({- useTheme: () => ({ theme: "dark", setTheme: vi.fn(), toggle: vi.fn() }),- useThemeValue: () => "dark",- // The top bar's light/dark flip reads the provider through this one, and it- // renders inside the bar this view carries.- useOptionalTheme: () => ({ theme: "dark", setTheme: vi.fn(), toggle: vi.fn() }),-}));--const pushToast = vi.fn();-const setActiveSection = vi.fn();-vi.mock("@/store/events", () => ({- useEventStore: (selector: (s: Record<string, unknown>) => unknown) =>- selector({ pushToast, setActiveSection }),-}));--// Stub the heavy ChatsView import (only ViewHeader is needed).-vi.mock("@/views/ChatsView", () => ({- ViewHeader: ({ title }: { title: string }) => <header>{title}</header>,-}));--/*- * The IDE carries the app's own Restart/Update actions in its header row, so- * this view now mounts the updater hook — which fetches `/api/update/status`- * the moment it appears. jsdom has no server behind that, so left real it is an- * unhandled request on every render in this file, and the button's visibility- * would depend on how that failure happened to land. "No update offered" is- * both the deterministic answer and the state of every dev tree.- */-vi.mock("@/hooks/useUpdate", () => ({- useUpdate: () => ({- status: { managed: false, update_available: false },- refresh: vi.fn(),- }),-}));--// xterm.js needs a real canvas, which jsdom has not got — stub the panes.-vi.mock("@/components/agentic/AgenticTerminal", () => ({- AgenticTerminal: ({ name }: { name: string }) => (- <div data-testid={`pane-${name}`}>{name}</div>- ),-}));--vi.mock("@/lib/agenticIdeApi", () => ({- fetchIdeState: vi.fn(),- fetchIdeAgents: vi.fn(),- fetchFolders: vi.fn(),- searchFolders: vi.fn(),- fetchRecents: vi.fn(),- forgetRecent: vi.fn(),- resolveDroppedFolder: vi.fn(),- startIdeSession: vi.fn(),- endIdeSession: vi.fn(),- setFocusMode: vi.fn(),- promptTerminal: vi.fn(),- fetchResumeOffer: vi.fn(),- resumeWorkspace: vi.fn(),- forgetResumeOffer: vi.fn(),- fetchWorkspaces: vi.fn(),- activateWorkspace: vi.fn(),- renameWorkspace: vi.fn(),- closeWorkspace: vi.fn(),- fetchNativePickerSupport: vi.fn(),- openNativePicker: vi.fn(),- syncAgenticIdeSurface: vi.fn(async () => undefined),- fetchAllVoiceAttachments: vi.fn(async () => ({ batches: [] })),- attachToTerminal: vi.fn(),- removeVoiceAttachment: vi.fn(async () => undefined),- // The grid polls this to keep the pane headers current.- fetchTerminalRecaps: vi.fn(async () => ({- workspace_id: null,- terminals: [],- })),- // The remembered terminal text size, read once when the grid mounts.- fetchTerminalUiPreferences: vi.fn(async () => ({- terminal_font_size: 13,- stored: false,- min: 10,- max: 20,- default: 13,- })),- saveTerminalFontSize: vi.fn(async (size: number) => ({- terminal_font_size: size,- stored: true,- min: 10,- max: 20,- default: 13,- })),-}));-import { AgenticIdeView } from "./AgenticIdeView";-import { workspaceLaunchShortcut } from "@/components/agentic/WorkspaceLauncher";-import * as api from "@/lib/agenticIdeApi";-import { GRID_HORIZONTAL_PADDING_PX } from "@/components/agentic/layout";--const AGENTS: api.AgentsResponse = {- terminal_available: true,- max_terminals: 12,- suggested_names: ["Mika", "Nova", "Aria", "Kai"],- agents: [- {- name: "claude",- display_name: "Claude Code",- installed: true,- version: "2.1.195",- install_command: "npm install -g @anthropic-ai/claude-code",- },- {- name: "codex",- display_name: "Codex",- installed: true,- version: "0.142.3",- install_command: "npm install -g @openai/codex",- },- ],-};--const EMPTY_STATE: api.IdeState = {- active: false,- session: null,- max_terminals: 12,- workspaces: [],- active_id: null,- max_workspaces: 6,-};--/**- * The state the backend returns with one workspace open.- *- * Derives the workspace bar from the session rather than letting a test spell- * both out, so a fixture can never describe a front workspace that is not in- * the bar — a shape the backend cannot produce and a test should not either.- */-function stateWith(session: api.SessionState): api.IdeState {- return {- active: true,- session,- max_terminals: 12,- workspaces: [- {- id: session.id,- folder: session.folder,- name: session.project.name,- branch: session.project.branch,- terminals: session.terminals.length,- live_terminals: session.terminals.filter((t) => t.status === "live")- .length,- focus_mode: session.focus_mode,- created_at: session.created_at,- last_active_at: session.created_at,- active: true,- },- ],- active_id: session.id,- max_workspaces: 6,- };-}--const NO_OFFER: api.ResumeOffer = {- available: false,- saved_at: 0,- workspace_count: 0,- terminal_count: 0,- resumable_count: 0,- workspaces: [],-};+import { useIdeProjectsStore } from "@/store/ideProjects";-const PREVIOUS_WORKSPACE: api.ResumeOffer = {- available: true,- saved_at: 1_753_473_600,- workspace_count: 1,- terminal_count: 2,- resumable_count: 1,- workspaces: [- {- session_id: "ide_old",- folder: "/work/project",- folder_name: "project",- name: "",- folder_exists: true,- available: true,- resumable_count: 1,- terminals: [- {- key: "alex",- name: "Alex",- agent: "claude",- display_name: "Claude Code",- column: 0,- slot: 0,- available: true,- resumable: true,- prompts_sent: 2,- },- {- key: "blake",- name: "Blake",- agent: "claude",- display_name: "Claude Code",- column: 1,- slot: 0,- available: true,- resumable: false,- prompts_sent: 0,- },- ],- },- ],-};--function sessionWith(names: string[], focus = false): api.SessionState {- return {- id: "ide_test",- folder: "/work/project",- project: {- path: "/work/project",- name: "project",- exists: true,- is_repo: true,- branch: "main",- stacks: ["Python"],- instruction_files: ["CLAUDE.md"],- top_level_dirs: ["src"],- skills: [],- subagents: [],- commands: [],- note: "",- },- created_at: 0,- focus_mode: focus,- terminals: names.map((name, index) => ({- key: name.toLowerCase(),- name,- agent: "claude",- display_name: "Claude Code",- index,- column: index,- slot: 0,- status: "live" as const,- exit_code: null,- error: "",- started_at: 0,- last_output_at: 0,- idle_seconds: 0,- prompts_sent: 0,- last_prompt: "",- lines_captured: 0,- })),- };-}+const api = vi.hoisted(() => ({+ fetchIdeState: vi.fn(), fetchIdeProjects: vi.fn(), fetchIdeAgents: vi.fn(),+ startIdeSession: vi.fn(), activateWorkspace: vi.fn(), restoreIdeWorkspace: vi.fn(),+ addTerminal: vi.fn(), closeTerminal: vi.fn(), closeWorkspace: vi.fn(), renameWorkspace: vi.fn(),+}));+const openProject = vi.hoisted(() => vi.fn());+vi.mock("@/lib/agenticIdeApi", () => api);+vi.mock("@/lib/chatLibraryApi", () => ({ openProject }));+vi.mock("@/store/events", () => ({ useEventStore: (select: (value: unknown) => unknown) => select({ pushToast: vi.fn() }) }));+vi.mock("@/components/agentic/FolderPicker", () => ({ FolderPicker: ({ onSelect }: { onSelect: (path: string) => void }) => <button onClick={() => onSelect("/code/app")}>Pick folder</button> }));+vi.mock("@/components/agentic/VoiceBubble", () => ({ VoiceBubble: () => null, storedVoiceBubbleOpen: () => false, storeVoiceBubbleOpen: vi.fn() }));+vi.mock("@/components/agentic/WorkspaceTerminalGrid", () => ({ WorkspaceTerminalGrid: ({ session }: { session: { id: string } }) => <div data-testid="live-grid">{session.id}</div> }));++const emptyState = { active: false, session: null, max_terminals: 8, workspaces: [], active_id: null };+const project = { id: "p1", path: "/code/app", name: "App", color: null, pinned: false, archived: false,+ created_at: 0, last_opened_at: 0, exists: true, chats: 0, scratch: false, workspaces: [] };+const agent = { name: "codex", display_name: "Codex", installed: true, version: "1", install_command: null };beforeEach(() => {- // The wizard's view step preselects the remembered reading mode, and the- // grid reads the same key on mount — a value left behind by one test must- // not decide how the next one's workspace opens.- window.localStorage.removeItem("jarvis.agenticIde.workspaceView");- vi.mocked(api.fetchIdeAgents).mockResolvedValue(AGENTS);- vi.mocked(api.fetchIdeState).mockResolvedValue(EMPTY_STATE);- vi.mocked(api.fetchFolders).mockResolvedValue({- path: null,- parent: null,- entries: [- {- name: "project",- path: "/work/project",- is_project: true,- is_repo: true,- },- ],- device_name: "Rubens MacBook",- });- vi.mocked(api.fetchRecents).mockResolvedValue({- device_name: "Rubens MacBook",- recents: [],- });- vi.mocked(api.searchFolders).mockResolvedValue({- query: "",- entries: [],- truncated: false,- });- // Nothing to resume by default; the resume tests override this.- vi.mocked(api.fetchResumeOffer).mockResolvedValue(NO_OFFER);- // No system folder window in jsdom — the picker falls back to browsing.- vi.mocked(api.fetchNativePickerSupport).mockResolvedValue({- available: false,- reason: "not available under test",- });-});--afterEach(() => {- cleanup();vi.clearAllMocks();+ api.fetchIdeState.mockResolvedValue(emptyState);+ api.fetchIdeProjects.mockResolvedValue({ projects: [], active_project_id: null, active_workspace_id: null, max_terminals: 8 });+ api.fetchIdeAgents.mockResolvedValue({ terminal_available: true, max_terminals: 8, suggested_names: [], agents: [agent] });+ useIdeProjectsStore.setState({ projects: [], activeWorkspaceId: null, action: null });});--describe("Agentic IDE — before the first read lands", () => {- /**- * A workspace the view has not heard about yet is NOT "no workspace".- *- * This view used to fall straight through to the launcher while it waited, so- * a user returning to a running workspace was met by step 1 of the onboarding- * flow asking which folder the agents should work in — in front of eleven- * agents that had never stopped (maintainer report 2026-07-29). Being told to- * wait a moment is a far better answer than being told to start over.- */- it("shows a neutral placeholder rather than the onboarding screen", async () => {- // Both reads hang: this is the state the view is in on every cold start,- // held open so it can be asserted on.- vi.mocked(api.fetchIdeState).mockReturnValue(new Promise(() => {}));- vi.mocked(api.fetchIdeAgents).mockReturnValue(new Promise(() => {}));-- render(<AgenticIdeView />);-- expect(await screen.findByTestId("agentic-ide-loading")).toBeTruthy();- // The thing that would read as "there is nothing open here".- expect(screen.queryByTestId("workspace-launcher")).toBeNull();- });-- it("draws a running workspace without waiting for the CLI sweep", async () => {- // `/agents` starts one subprocess per registered CLI and takes over a- // second on a cold cache. The grid never asks what is installed, so it must- // not wait for the answer — this is the other half of the 3 s on the way- // back into the section.- vi.mocked(api.fetchIdeAgents).mockReturnValue(new Promise(() => {}));- vi.mocked(api.fetchIdeState).mockResolvedValue(- stateWith(sessionWith(["Mika", "Nova"])),- );-- render(<AgenticIdeView />);-- expect(await screen.findByTestId("pane-Mika")).toBeTruthy();- });-- it("holds the placeholder until the launcher has agents to offer", async () => {- // The reverse: with no workspace open, the wizard's agent step is the whole- // point of the sweep, so showing the wizard before it lands would offer an- // empty list.- vi.mocked(api.fetchIdeAgents).mockReturnValue(new Promise(() => {}));-- render(<AgenticIdeView />);-- expect(await screen.findByTestId("agentic-ide-loading")).toBeTruthy();- expect(screen.queryByTestId("workspace-launcher")).toBeNull();- });-});--describe("Agentic IDE launcher", () => {- it("shows the launch chord for the current operating system", () => {- expect(workspaceLaunchShortcut("Win32")).toBe("Ctrl+↵");- expect(workspaceLaunchShortcut("MacIntel")).toBe("⌘↵");- expect(workspaceLaunchShortcut("Linux x86_64")).toBe("Ctrl+↵");- });-- async function chooseFolder(): Promise<void> {- fireEvent.click(await screen.findByRole("button", { name: /project/i }));- }-- async function openLayout(): Promise<void> {- await chooseFolder();- fireEvent.click(- screen.getByRole("button", { name: /continue to layout/i }),- );- }-- async function openAgents(): Promise<void> {- await openLayout();- fireEvent.click(- screen.getByRole("button", { name: /continue to agents/i }),- );- }-- it("keeps later decisions locked until a folder is picked", async () => {- render(<AgenticIdeView />);- await waitFor(() => expect(api.fetchIdeAgents).toHaveBeenCalled());-- const next = screen.getByRole("button", {- name: /continue to layout/i,- }) as HTMLButtonElement;- expect(next.disabled).toBe(true);- expect(- (screen.getByTestId("launcher-step-layout") as HTMLButtonElement)- .disabled,- ).toBe(true);-- await chooseFolder();- await waitFor(() => expect(next.disabled).toBe(false));- });-- it("walks through folder, layout, agents, view and review before opening", async () => {- vi.mocked(api.startIdeSession).mockResolvedValue(- stateWith(sessionWith(["Mika", "Nova"])),- );- render(<AgenticIdeView />);- await waitFor(() => expect(api.fetchIdeAgents).toHaveBeenCalled());-- expect(- screen.getByRole("heading", { name: /choose the project folder/i }),- ).toBeTruthy();- expect(screen.queryByDisplayValue("Mika")).toBeNull();-- await openLayout();- expect(- screen.getByRole("heading", { name: /shape the workspace/i }),- ).toBeTruthy();- expect(- screen.getByRole("textbox", { name: /number of terminals/i }),- ).toBeTruthy();-- fireEvent.click(- screen.getByRole("button", { name: /continue to agents/i }),- );- expect(await screen.findByText("0 / 2")).toBeTruthy();- fireEvent.click(screen.getAllByText("workspace_launcher.agents.all")[0]);- expect(screen.getByText("2 / 2")).toBeTruthy();-- fireEvent.click(screen.getByRole("button", { name: /choose the view/i }));- expect(- screen.getByRole("heading", { name: /choose how to read the workspace/i }),- ).toBeTruthy();- // The full terminal grid is the preselected answer, not an open question.- expect(- screen.getByTestId("view-choice-grid").getAttribute("aria-checked"),- ).toBe("true");-- fireEvent.click(screen.getByRole("button", { name: /review workspace/i }));- expect(- screen.getByRole("heading", { name: /review before opening/i }),- ).toBeTruthy();- expect(screen.getByTestId("review-view-mode").textContent).toBe(- "Terminal grid",- );- fireEvent.click(screen.getByRole("button", { name: /open workspace/i }));-- await waitFor(() =>- expect(api.startIdeSession).toHaveBeenCalledWith("/work/project", [- { agent: "claude", name: "Mika" },- { agent: "claude", name: "Nova" },- ]),- );- // Panes are rendered once the session exists.- expect(await screen.findByTestId("pane-Mika")).toBeTruthy();- });-- it("opens the workspace in chat view when the view step says so", async () => {- vi.mocked(api.startIdeSession).mockResolvedValue(- stateWith(sessionWith(["Mika", "Nova"])),- );- render(<AgenticIdeView />);- await waitFor(() => expect(api.fetchIdeAgents).toHaveBeenCalled());- await openAgents();- fireEvent.click(screen.getAllByText("workspace_launcher.agents.all")[0]);-- fireEvent.click(screen.getByRole("button", { name: /choose the view/i }));- fireEvent.click(screen.getByTestId("view-choice-chat"));- expect(- screen.getByTestId("view-choice-chat").getAttribute("aria-checked"),- ).toBe("true");-- fireEvent.click(screen.getByRole("button", { name: /review workspace/i }));- expect(screen.getByTestId("review-view-mode").textContent).toBe("Chat");- fireEvent.click(screen.getByRole("button", { name: /open workspace/i }));-- // The grid reads the stored preference on mount, so the workspace comes up- // with the chat rail showing instead of the wall of terminals.- expect(await screen.findByTestId("pane-Mika")).toBeTruthy();- expect(- window.localStorage.getItem("jarvis.agenticIde.workspaceView"),- ).toBe("chat");- // Chat is the reading mode the workspace comes up in. The list of- // sessions that used to sit in a rail beside the panes is the app- // sidebar's now, which this view does not draw — so the claim is carried- // by the switch itself.- expect(- screen.getByTestId("agentic-view-mode-toggle").getAttribute("aria-pressed"),- ).toBe("true");- });-- it("keeps every reading-mode miniature visible on the dark workspace", async () => {- render(<AgenticIdeView />);- await waitFor(() => expect(api.fetchIdeAgents).toHaveBeenCalled());- await openAgents();- fireEvent.click(screen.getAllByText("workspace_launcher.agents.all")[0]);- fireEvent.click(screen.getByRole("button", { name: /choose the view/i }));-- for (const view of ["grid", "chat"] as const) {- const panes = screen- .getByTestId(`view-choice-${view}`)- .querySelectorAll("[data-view-preview-pane]");- expect(panes).toHaveLength(4);- for (const pane of panes) {- expect(pane.className).toContain("border-foreground/20");- expect(pane.className).toContain("bg-foreground/");- }- }- });-- it("keeps an aggregate agent split across backward navigation", async () => {- render(<AgenticIdeView />);- await waitFor(() => expect(api.fetchIdeAgents).toHaveBeenCalled());- await openAgents();-- fireEvent.click(screen.getByText("workspace_launcher.agents.split_evenly"));- fireEvent.click(screen.getByTestId("launcher-step-folder"));-- const path = screen.getByTestId("folder-path-input");- fireEvent.change(path, { target: { value: "/work/another" } });- fireEvent.keyDown(path, { key: "Enter" });-- fireEvent.click(screen.getByTestId("launcher-step-agents"));-- expect(- screen- .getAllByRole("spinbutton")- .map((input) => (input as HTMLInputElement).value),- ).toEqual(["1", "1"]);- });-- /**- * Set the count to ``n`` in a workspace of ``width`` × ``height`` pixels and- * return the stage — the miniature of the workspace that is about to open.- */- async function stageAt(- width: number,- n: string,- height: number = 0,- ): Promise<HTMLElement> {- const previous = globalThis.ResizeObserver;- class WidthObserver {- constructor(private readonly callback: ResizeObserverCallback) {}- observe(): void {- this.callback(- [{ contentRect: { width, height } } as ResizeObserverEntry],- this as unknown as ResizeObserver,- );- }- unobserve(): void {}- disconnect(): void {}- }- globalThis.ResizeObserver =- WidthObserver as unknown as typeof ResizeObserver;- try {- render(<AgenticIdeView />);- await waitFor(() => expect(api.fetchIdeAgents).toHaveBeenCalled());- await openLayout();- fireEvent.change(- await screen.findByRole("textbox", {- name: /number of terminals/i,- }),- { target: { value: n } },- );- return screen.getByTestId("workspace-stage-grid");- } finally {- globalThis.ResizeObserver = previous;- }- }-- /** Columns and rows the stage lays its panes out in. */- const columnsOf = (stage: HTMLElement) => stage.style.gridTemplateColumns;- const rowsOf = (stage: HTMLElement) => stage.style.gridTemplateRows;- /**- * The width the stage draws the workspace at — always its own frame.- *- * It used to be set inline to more than 100 % when the workspace was wider- * than the window, which was the honest preview of a grid you scrolled- * sideways. Nothing scrolls now (maintainer, 2026-08-04), so an inline width- * appearing here at all would mean the preview is promising a workspace the- * running grid will not build.- */- const widthOf = (stage: HTMLElement) => stage.style.width;-- it("sets any count from one control instead of cards plus a custom row", async () => {- // Two ways to set one number meant two competing "selected" states. One- // control now covers every value, and its two grips must never disagree.- await stageAt(2328, "10");-- expect(- (- screen.getByRole("slider", {- name: /number of terminals/i,- }) as HTMLInputElement- ).value,- ).toBe("10");- expect(- (- screen.getByRole("textbox", {- name: /number of terminals/i,- }) as HTMLInputElement- ).value,- ).toBe("10");- expect(- screen.queryByRole("button", { name: /custom terminals/i }),- ).toBeNull();- });-- it("lets the exact terminal count be cleared and typed directly", async () => {- render(<AgenticIdeView />);- await waitFor(() => expect(api.fetchIdeAgents).toHaveBeenCalled());- await openLayout();-- const input = await screen.findByRole("textbox", {- name: /number of terminals/i,- });- fireEvent.change(input, { target: { value: "" } });- expect((input as HTMLInputElement).value).toBe("");-- fireEvent.change(input, { target: { value: "11" } });- fireEvent.keyDown(input, { key: "Enter" });-- expect((input as HTMLInputElement).value).toBe("11");- expect(- (- screen.getByRole("slider", {- name: /number of terminals/i,- }) as HTMLInputElement- ).value,- ).toBe("11");- });-- it("builds the requested number of terminal plans", async () => {- render(<AgenticIdeView />);- await waitFor(() => expect(api.fetchIdeAgents).toHaveBeenCalled());- await openLayout();- fireEvent.change(- await screen.findByRole("textbox", { name: /number of terminals/i }),- { target: { value: "10" } },- );- fireEvent.click(- screen.getByRole("button", { name: /continue to agents/i }),- );-- expect(screen.getByText("0 / 10")).toBeTruthy();- expect(- screen- .getByRole("progressbar", {- name: "workspace_launcher.agents.assigned",- })- .getAttribute("aria-valuemax"),- ).toBe("10");- });-- it("caps the count at the backend limit", async () => {- await stageAt(2328, "99");-- expect(- (- screen.getByRole("textbox", {- name: /number of terminals/i,- }) as HTMLInputElement- ).value,- ).toBe("12");- expect(- (- screen.getByRole("button", {- name: /use one more terminal/i,- }) as HTMLButtonElement- ).disabled,- ).toBe(true);- });-- it("previews 12 terminals as six columns of two, all of them on one screen", async () => {- // One screenful, opened two deep: a single line spent the whole window on- // one row, and past five panes each one fell under the width a 60-column- // agent grid needs, clipping at the tile edge (reported 2026-08-11 —- // WIZARD_COLUMN_HEIGHT in layout.ts holds the full rationale). The preview- // mirrors the exact panes the backend opens: columns of two.- const stage = await stageAt(2328, "12");- expect(columnsOf(stage)).toBe("repeat(6, minmax(0, 1fr))");- expect(rowsOf(stage)).toBe("repeat(2, minmax(0, 1fr))");- expect(widthOf(stage)).toBe("");- });-- it("previews the same twelve in a narrow window, still all on one screen", async () => {- // Neither the arrangement nor how much of it you see depends on the window- // any more — only how wide each pane ends up, which the readout says.- const stage = await stageAt(1314, "12");- expect(columnsOf(stage)).toBe("repeat(6, minmax(0, 1fr))");- expect(rowsOf(stage)).toBe("repeat(2, minmax(0, 1fr))");- expect(widthOf(stage)).toBe("");- });-- it("keeps a small workspace in wizard columns at any usable width", async () => {- // Three panes are a full column of two plus one beside it — the second- // column's single pane spans the height, so the grid stays two rows.- const stage = await stageAt(1314, "3");- expect(columnsOf(stage)).toBe("repeat(2, minmax(0, 1fr))");- expect(rowsOf(stage)).toBe("repeat(2, minmax(0, 1fr))");- // Nothing to scroll past, so the stage is an ordinary full-width grid.- expect(widthOf(stage)).toBe("");- });-- it("previews four terminals as two columns of two in a 2K workspace", async () => {- // The wizard's opening shape is columns of two (layout.ts,- // WIZARD_COLUMN_HEIGHT): four terminals start as a 2 x 2. Only the OPENING- // shape — the user's own splits and drags rearrange it freely afterwards.- const stage = await stageAt(2048, "4", 1164);- expect(columnsOf(stage)).toBe("repeat(2, minmax(0, 1fr))");- expect(rowsOf(stage)).toBe("repeat(2, minmax(0, 1fr))");- expect(widthOf(stage)).toBe("");- });-- it("draws one pane per terminal and never grows the box to fit them", async () => {- // The old dot preview sat in a fixed 40×40 px box with nothing bounding it,- // so a high count in a narrow window grew a tall column of dots straight out- // through the card, over the buttons above and below. The stage is a FIXED- // frame, and every pane is drawn inside it however many there are.- const stage = await stageAt(800, "12");- expect(stage.children.length).toBe(12);- expect(columnsOf(stage)).toBe("repeat(6, minmax(0, 1fr))");- expect(rowsOf(stage)).toBe("repeat(2, minmax(0, 1fr))");- expect(widthOf(stage)).toBe("");- });-- it("names the width each pane ends up with, and warns when that is tight", async () => {- // The reported bug behind this readout: an arrangement stated without its- // consequence. The consequence changed on 2026-08-04 — nothing scrolls, so- // a high count is paid for in pane WIDTH — and the sentence says that.- await stageAt(1050, "8");-- const readout = screen.getByTestId("workspace-stage-readout");- // Eight terminals open as four columns of two (layout.ts,- // WIZARD_COLUMN_HEIGHT), so the width is shared four ways, not eight.- expect(readout.textContent).toContain("4 across");- expect(readout.textContent).toContain("All on one screen");- // Never a promise of somewhere else to look: every pane is on this screen.- expect(readout.textContent).not.toMatch(/scroll/i);- // 1 056, not 1 050: the view rounds the measured width to 16 px steps, and- // 8 panes share it minus the grid's own padding. Computed rather than- // written out, because tightening that padding moves the number without- // changing anything the test is about.- const each = Math.round((1056 - GRID_HORIZONTAL_PADDING_PX) / 4);- expect(readout.textContent).toContain(`${each} px each`);- expect(readout.textContent).toMatch(/narrow for an agent/i);- });-- it("drops the warning once the panes really are roomy", async () => {- await stageAt(3200, "8");-- const readout = screen.getByTestId("workspace-stage-readout");- expect(readout.textContent).toContain("4 across");- expect(readout.textContent).toContain("All on one screen");- expect(readout.textContent).not.toMatch(/narrow for an agent/i);- expect(readout.textContent).not.toMatch(/scroll/i);- });-- it("says so plainly when the machine has no terminal backend", async () => {- vi.mocked(api.fetchIdeAgents).mockResolvedValue({- ...AGENTS,- terminal_available: false,- });- render(<AgenticIdeView />);- expect(await screen.findByText(/no usable terminal backend/i)).toBeTruthy();- });-- it("points at the CLIs page when no coding agent is installed", async () => {- vi.mocked(api.fetchIdeAgents).mockResolvedValue({- ...AGENTS,- agents: AGENTS.agents.map((a) => ({ ...a, installed: false })),- });- render(<AgenticIdeView />);- fireEvent.click(await screen.findByRole("button", { name: /open clis/i }));- expect(setActiveSection).toHaveBeenCalledWith("clis");- });-});--describe("Agentic IDE running workspace", () => {- it("renders the open session instead of the wizard", async () => {- vi.mocked(api.fetchIdeState).mockResolvedValue(- stateWith(sessionWith(["Mika"])),- );- render(<AgenticIdeView />);- expect(await screen.findByTestId("pane-Mika")).toBeTruthy();- expect(screen.queryByTestId("workspace-launcher")).toBeNull();- });-- it("toggles focus mode through the API, not just locally", async () => {- vi.mocked(api.fetchIdeState).mockResolvedValue(- stateWith(sessionWith(["Mika"])),- );- vi.mocked(api.setFocusMode).mockResolvedValue(true);- render(<AgenticIdeView />);-- const toggle = await screen.findByTestId("agentic-focus-toggle");- // The view turns coding mode on by itself when a workspace opens, so the- // starting state is not asserted here — what matters is that the switch goes- // through the API rather than only flipping local state.- await waitFor(() => expect(api.setFocusMode).toHaveBeenCalled());- const before = toggle.getAttribute("aria-pressed") === "true";- vi.mocked(api.setFocusMode).mockResolvedValue(!before);-- fireEvent.click(toggle);- await waitFor(() =>- expect(api.setFocusMode).toHaveBeenLastCalledWith(!before),- );- await waitFor(() =>- expect(toggle.getAttribute("aria-pressed")).toBe(String(!before)),- );- });-- /*- * The mode is scoped to this section, and the signal is `onScreen`.- *- * This view is sticky — MainView keeps it mounted so a workspace survives a- * trip to Settings — so there is no unmount to clean up on. That is exactly- * how the mode came to be permanently on: this view switched it on and- * nothing ever switched it off, leaving the assistant in coding mode on every- * screen for the rest of the session.- */- it("hands an auto-enabled coding mode back when the section is left", async () => {- vi.mocked(api.fetchIdeState).mockResolvedValue(- stateWith(sessionWith(["Mika"])),- );- vi.mocked(api.setFocusMode).mockResolvedValue(true);- const { rerender } = render(<AgenticIdeView onScreen />);-- await waitFor(() => expect(api.setFocusMode).toHaveBeenCalledWith(true));-- vi.mocked(api.setFocusMode).mockResolvedValue(false);- rerender(<AgenticIdeView onScreen={false} />);- await waitFor(() => expect(api.setFocusMode).toHaveBeenLastCalledWith(false));- });-- it("switches the mode back on when the section is returned to", async () => {- vi.mocked(api.fetchIdeState).mockResolvedValue(- stateWith(sessionWith(["Mika"])),- );- vi.mocked(api.setFocusMode).mockResolvedValue(true);- const { rerender } = render(<AgenticIdeView onScreen />);- await waitFor(() => expect(api.setFocusMode).toHaveBeenCalledWith(true));-- vi.mocked(api.setFocusMode).mockResolvedValue(false);- rerender(<AgenticIdeView onScreen={false} />);- await waitFor(() => expect(api.setFocusMode).toHaveBeenLastCalledWith(false));-- // The cached session still claims focus_mode is on, which is precisely why- // the auto-enable gate reads the local flag instead of the session.- vi.mocked(api.setFocusMode).mockResolvedValue(true);- rerender(<AgenticIdeView onScreen />);- await waitFor(() => expect(api.setFocusMode).toHaveBeenLastCalledWith(true));- });-- it("leaves a hand-toggled coding mode alone when the section is left", async () => {- vi.mocked(api.fetchIdeState).mockResolvedValue(- stateWith(sessionWith(["Mika"], true)),- );- vi.mocked(api.setFocusMode).mockResolvedValue(true);- const { rerender } = render(<AgenticIdeView onScreen />);-- const toggle = await screen.findByTestId("agentic-focus-toggle");- // Off by hand, then on by hand: now the mode is the user's, not the screen's,- // so walking away must not take it back. This is what keeps "ask Jarvis- // about my terminals from another room" working.- vi.mocked(api.setFocusMode).mockResolvedValue(false);- fireEvent.click(toggle);- await waitFor(() => expect(api.setFocusMode).toHaveBeenLastCalledWith(false));- vi.mocked(api.setFocusMode).mockResolvedValue(true);- fireEvent.click(toggle);- await waitFor(() => expect(api.setFocusMode).toHaveBeenLastCalledWith(true));-- const callsBeforeLeaving = vi.mocked(api.setFocusMode).mock.calls.length;- rerender(<AgenticIdeView onScreen={false} />);- await Promise.resolve();- expect(vi.mocked(api.setFocusMode).mock.calls.length).toBe(- callsBeforeLeaving,- );- });-- it("shows panes that voice opened, without a reload", async () => {- /*- * The regression this guards: a spoken "spawn three more terminals" adds the- * panes in the backend, but this view fetches its state once on mount. Before- * the listener existed, the agents were running and the user saw the old grid- * — the feature looked broken while working perfectly.- */- vi.mocked(api.fetchIdeState).mockResolvedValue(- stateWith(sessionWith(["Mika", "Nova"])),- );- render(<AgenticIdeView />);- await screen.findByTestId("pane-Mika");- expect(screen.queryByTestId("pane-Aria")).toBeNull();-- // Voice opened a third pane; the WebSocket layer turns the bus event into- // this window event.- vi.mocked(api.fetchIdeState).mockResolvedValue(- stateWith(sessionWith(["Mika", "Nova", "Aria"])),- );- window.dispatchEvent(- new CustomEvent("jarvis:agentic-ide-changed", {- detail: { names: ["Aria"], agent: "claude" },- }),- );-- await screen.findByTestId("pane-Aria");- // The panes that were already mounted stay mounted: re-parenting one would- // tear down its WebSocket and kill the agent behind it.- expect(screen.getByTestId("pane-Mika")).toBeTruthy();- });-});--describe("AgenticIdeView — resuming the last workspace", () => {- it("offers the previous workspace above the wizard", async () => {- vi.mocked(api.fetchResumeOffer).mockResolvedValue(PREVIOUS_WORKSPACE);- render(<AgenticIdeView />);-- await screen.findByTestId("resume-card");- expect(screen.getByTestId("resume-pane-alex")).toBeTruthy();- // The launcher is still right there — the offer never blocks it.- expect(screen.getByTestId("workspace-launcher")).toBeTruthy();- });-- it("says nothing when there is nothing to resume", async () => {- render(<AgenticIdeView />);- await screen.findByTestId("workspace-launcher");- expect(screen.queryByTestId("resume-card")).toBeNull();- });-- it("does not offer a resume while a workspace is open", async () => {- vi.mocked(api.fetchIdeState).mockResolvedValue(- stateWith(sessionWith(["Mika"])),- );- vi.mocked(api.fetchResumeOffer).mockResolvedValue(PREVIOUS_WORKSPACE);- render(<AgenticIdeView />);-- await screen.findByTestId("pane-Mika");- expect(screen.queryByTestId("resume-card")).toBeNull();- });-- it("reopens the workspace and reports what really came back", async () => {- vi.mocked(api.fetchResumeOffer).mockResolvedValue(PREVIOUS_WORKSPACE);- vi.mocked(api.resumeWorkspace).mockResolvedValue({- state: stateWith(sessionWith(["Mika", "Nova"])),- workspace_count: 1,- terminal_count: 2,- resumable_count: 1,- started_fresh: 1,- skipped: [],- });- render(<AgenticIdeView />);-- fireEvent.click(await screen.findByTestId("resume-all"));-- await screen.findByTestId("pane-Mika");- expect(screen.queryByTestId("resume-card")).toBeNull();- // The honest report: one pane came back empty and the user is told so.- await waitFor(() =>- expect(pushToast).toHaveBeenCalledWith(- "success",- expect.stringMatching(/1 continued, 1 started fresh/),- ),- );- });-- it("forgets the workspace when the user starts fresh", async () => {- vi.mocked(api.fetchResumeOffer).mockResolvedValue(PREVIOUS_WORKSPACE);- vi.mocked(api.forgetResumeOffer).mockResolvedValue(undefined);- render(<AgenticIdeView />);-- fireEvent.click(await screen.findByTestId("resume-dismiss"));-- await waitFor(() => expect(api.forgetResumeOffer).toHaveBeenCalledTimes(1));- expect(screen.queryByTestId("resume-card")).toBeNull();- });-});--/*- * The workspace bar.- *- * What these defend is the promise the bar makes by existing: several- * workspaces are open at once, and moving between them costs nothing. The- * ordering assertions are the important ones — the backend has to be told the- * front workspace changed BEFORE the outgoing panes unmount, because a pane- * that disappears while its workspace is still the front one is indistinguishable- * from a close.- */-function twoWorkspaces(): api.IdeState {- const front = sessionWith(["Mika"]);- const base = stateWith(front);- return {- ...base,- workspaces: [- {- id: "ide_other",- folder: "/work/api",- name: "api",- branch: "main",- terminals: 3,- live_terminals: 2,- focus_mode: false,- created_at: 0,- last_active_at: 0,- active: false,- },- ...base.workspaces,- ],- };-}--describe("AgenticIdeView — the workspace bar", () => {- it("lists every open workspace and marks the one on screen", async () => {- vi.mocked(api.fetchIdeState).mockResolvedValue(twoWorkspaces());- render(<AgenticIdeView />);-- await screen.findByTestId("workspace-bar");- const other = screen.getByTestId("workspace-tab-ide_other");- const front = screen.getByTestId("workspace-tab-ide_test");- expect(other.getAttribute("aria-selected")).toBe("false");- expect(front.getAttribute("aria-selected")).toBe("true");- // The badge is one number: open terminal panes, not running agents versus- // every pane ever placed in the workspace.- expect(screen.getByTestId("workspace-panes-ide_other").textContent).toBe(- "3",- );- });-- it("uses the active session count instead of a stale spawn total", async () => {- const active = sessionWith(["Mika", "Nova"]);- const state = stateWith(active);- state.workspaces[0] = {- ...state.workspaces[0],- terminals: 60,- live_terminals: 60,- };- vi.mocked(api.fetchIdeState).mockResolvedValue(state);- render(<AgenticIdeView />);-- expect(- (await screen.findByTestId("workspace-panes-ide_test")).textContent,- ).toBe("2");- });-- it("stays hidden while nothing is open", async () => {- render(<AgenticIdeView />);- await screen.findByTestId("workspace-launcher");- expect(screen.queryByTestId("workspace-bar")).toBeNull();- });-- it("switches to another workspace through the API", async () => {- vi.mocked(api.fetchIdeState).mockResolvedValue(twoWorkspaces());- const other = sessionWith(["Kai"]);- other.id = "ide_other";- vi.mocked(api.activateWorkspace).mockResolvedValue(stateWith(other));- render(<AgenticIdeView />);-- fireEvent.click(await screen.findByTestId("workspace-tab-ide_other"));-- await waitFor(() =>- expect(api.activateWorkspace).toHaveBeenCalledWith("ide_other"),- );- await screen.findByTestId("pane-Kai");- // Switching is not closing: nothing was ended.- expect(api.endIdeSession).not.toHaveBeenCalled();- expect(api.closeWorkspace).not.toHaveBeenCalled();- });-- it("clears the front workspace before showing the wizard for a new one", async () => {- vi.mocked(api.fetchIdeState).mockResolvedValue(twoWorkspaces());- vi.mocked(api.activateWorkspace).mockResolvedValue({- ...twoWorkspaces(),- session: null,- active_id: null,- active: false,+afterEach(cleanup);++describe("Agentic IDE project flow", () => {+ it("connects a folder as a project without opening a coding session", async () => {+ openProject.mockResolvedValue(project);+ api.fetchIdeProjects.mockResolvedValueOnce({ projects: [], active_project_id: null, active_workspace_id: null, max_terminals: 8 })+ .mockResolvedValue({ projects: [project], active_project_id: null, active_workspace_id: null, max_terminals: 8 });+ render(<AgenticIdeView />);+ fireEvent.click(await screen.findByRole("button", { name: "Connect folder" }));+ expect(api.fetchIdeAgents).toHaveBeenCalledWith(true);+ fireEvent.click(screen.getByRole("button", { name: "Pick folder" }));+ fireEvent.click(screen.getByRole("button", { name: "Connect project" }));+ await waitFor(() => expect(openProject).toHaveBeenCalledWith("/code/app", undefined));+ await waitFor(() => expect(screen.queryByRole("dialog", { name: "Connect project" })).toBeNull());+ expect(api.startIdeSession).not.toHaveBeenCalled();+ });++ it("creates a workspace with an explicit project and per-session agents", async () => {+ api.fetchIdeProjects.mockResolvedValue({ projects: [project], active_project_id: null, active_workspace_id: null, max_terminals: 8 });+ api.fetchIdeAgents.mockResolvedValue({ terminal_available: true, max_terminals: 8, suggested_names: [], agents: [agent,+ { ...agent, name: "harness", display_name: "Browser Harness", accepts_prompts: false }] });+ api.startIdeSession.mockResolvedValue(emptyState);+ render(<AgenticIdeView />);+ await screen.findByText("Choose a workspace");+ act(() => useIdeProjectsStore.getState().newWorkspace("p1"));+ await screen.findByRole("dialog", { name: "New workspace" });+ expect(screen.queryByRole("option", { name: "Browser Harness" })).toBeNull();+ fireEvent.change(screen.getByLabelText("Sessions"), { target: { value: "2" } });+ fireEvent.change(screen.getByLabelText("Name (optional)"), { target: { value: "Installer" } });+ fireEvent.click(screen.getByRole("button", { name: "Create workspace" }));+ await waitFor(() => expect(api.startIdeSession).toHaveBeenCalledWith("/code/app", [{ agent: "codex" }, { agent: "codex" }], { projectId: "p1", name: "Installer" }));+ await waitFor(() => expect(screen.queryByRole("dialog", { name: "New workspace" })).toBeNull());+ });++ it("restores a closed workspace by ID before showing its sessions", async () => {+ const workspace = { id: "w1", project_id: "p1", folder: "/code/app", name: "Installer", branch: null, terminals: 1,+ live_terminals: 0, focus_mode: false, created_at: 0, last_active_at: 0, active: false, status: "closed", restorable: true };+ api.fetchIdeProjects.mockResolvedValue({ projects: [{ ...project, workspaces: [workspace] }], active_project_id: null, active_workspace_id: null, max_terminals: 8 });+ const restored = { ...emptyState, active: true, active_id: "w1", session: {+ id: "w1", project_id: "p1", folder: "/code/app", name: "Installer", created_at: 0, focus_mode: false, project: { name: "App" }, terminals: [],+ } };+ api.restoreIdeWorkspace.mockImplementation(async () => {+ api.fetchIdeState.mockResolvedValue(restored);+ api.fetchIdeProjects.mockResolvedValue({ projects: [{ ...project, workspaces: [{ ...workspace, status: "open", active: true }] }], active_project_id: "p1", active_workspace_id: "w1", max_terminals: 8 });+ return restored;});render(<AgenticIdeView />);-- fireEvent.click(await screen.findByTestId("workspace-add"));-- // null, not a close: the workspaces stay open with their agents running.- await waitFor(() =>- expect(api.activateWorkspace).toHaveBeenCalledWith(null),- );- expect(api.closeWorkspace).not.toHaveBeenCalled();- expect(api.endIdeSession).not.toHaveBeenCalled();- // The launcher is showing, and the bar still lists both workspaces.- await screen.findByTestId("workspace-launcher");- expect(screen.getByTestId("workspace-tab-ide_other")).toBeTruthy();- expect(screen.getByTestId("workspace-tab-ide_test")).toBeTruthy();- });-- it("asks before closing a workspace, then closes only that one", async () => {- vi.mocked(api.fetchIdeState).mockResolvedValue(twoWorkspaces());- const left = stateWith(sessionWith(["Mika"]));- vi.mocked(api.closeWorkspace).mockResolvedValue(left);- render(<AgenticIdeView />);-- fireEvent.click(await screen.findByTestId("workspace-close-ide_other"));- // One click arms it; the workspace is still open at this point.- expect(api.closeWorkspace).not.toHaveBeenCalled();-- fireEvent.click(screen.getByTestId("workspace-close-confirm-ide_other"));- await waitFor(() =>- expect(api.closeWorkspace).toHaveBeenCalledWith("ide_other"),- );- await waitFor(() =>- expect(screen.queryByTestId("workspace-tab-ide_other")).toBeNull(),- );+ await screen.findByText("Choose a workspace");+ act(() => useIdeProjectsStore.getState().activateWorkspace("w1"));+ await waitFor(() => expect(api.restoreIdeWorkspace).toHaveBeenCalledWith("w1"));+ expect((await screen.findByTestId("live-grid")).textContent).toBe("w1");+ expect(api.activateWorkspace).not.toHaveBeenCalled();});- it("renames a workspace from the pencil action", async () => {- vi.mocked(api.fetchIdeState).mockResolvedValue(twoWorkspaces());- const renamed = twoWorkspaces();- renamed.workspaces = renamed.workspaces.map((workspace) =>- workspace.id === "ide_other"- ? { ...workspace, name: "Backend review" }- : workspace,- );- vi.mocked(api.renameWorkspace).mockResolvedValue(renamed);+ it("exposes compact workspace rename and close actions", async () => {+ const session = { id: "w1", project_id: "p1", folder: "/code/app", name: "App work", created_at: 0,+ focus_mode: false, project: { name: "App" }, terminals: [] };+ const current = { ...emptyState, active: true, active_id: "w1", session };+ api.fetchIdeState.mockResolvedValue(current);+ api.fetchIdeProjects.mockResolvedValue({ projects: [{ ...project, workspaces: [{+ id: "w1", project_id: "p1", folder: "/code/app", name: "App work", branch: null, terminals: 0,+ live_terminals: 0, focus_mode: false, created_at: 0, last_active_at: 0, active: true, status: "open", restorable: true,+ }] }], active_project_id: "p1", active_workspace_id: "w1", max_terminals: 8 });+ api.renameWorkspace.mockResolvedValue(current);render(<AgenticIdeView />);-- fireEvent.click(await screen.findByTestId("workspace-rename-ide_other"));- const input = screen.getByTestId(- "workspace-rename-input-ide_other",- ) as HTMLInputElement;- fireEvent.change(input, { target: { value: "Backend review" } });- fireEvent.click(screen.getByTestId("workspace-rename-save-ide_other"));-- await waitFor(() =>- expect(api.renameWorkspace).toHaveBeenCalledWith(- "ide_other",- "Backend review",- ),- );- expect(await screen.findByText("Backend review")).toBeTruthy();- expect(api.closeWorkspace).not.toHaveBeenCalled();+ fireEvent.click(await screen.findByRole("button", { name: "Workspace actions" }));+ fireEvent.click(screen.getByRole("button", { name: "Rename workspace" }));+ fireEvent.change(screen.getByLabelText("Workspace name"), { target: { value: "Installer" } });+ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ await waitFor(() => expect(api.renameWorkspace).toHaveBeenCalledWith("w1", "Installer"));+ await waitFor(() => expect(screen.queryByRole("dialog", { name: "Rename workspace" })).toBeNull());});- it("refuses to add one past the cap", async () => {- const full = twoWorkspaces();- vi.mocked(api.fetchIdeState).mockResolvedValue({- ...full,- max_workspaces: 2,- });- render(<AgenticIdeView />);-- const add = (await screen.findByTestId(- "workspace-add",- )) as HTMLButtonElement;- expect(add.disabled).toBe(true);- });-- it("keeps adding available when the backend has no workspace cap", async () => {- vi.mocked(api.fetchIdeState).mockResolvedValue({- ...twoWorkspaces(),- max_workspaces: null,- });- render(<AgenticIdeView />);-- const add = (await screen.findByTestId(- "workspace-add",- )) as HTMLButtonElement;- expect(add.disabled).toBe(false);- });});diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsxindex 7f57d173b3..0c80a6a609 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx@@ -1,1264 +1,288 @@-/**- * Agentic IDE — the "code with Jarvis" section.- *- * Two states in one view:- *- * * no workspace open → a five-step wizard: folder, how many terminals, an- * aggregate agent allocation, grid or chat view, then start,- * * workspace open → the terminal grid (see AgenticGrid).- *- * The wizard order is deliberate and matches how the decision actually gets- * made: you know the folder first, the number of panes second, then which agent- * sits in which pane, and last how you want to read them. Every step is- * reversible and nothing is started until the last one.- *- * i18n note: the section label and view header go through the locale files; the- * panel copy inside is still English-only source awaiting its i18n keys.- */-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { Loader2 } from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";+import { FolderPlus, Loader2, Mic, Moon, MoreHorizontal, Plus, Sun, X, ZoomIn, ZoomOut } from "lucide-react";+import { FolderPicker } from "@/components/agentic/FolderPicker";+import { VoiceBubble, storedVoiceBubbleOpen, storeVoiceBubbleOpen } from "@/components/agentic/VoiceBubble";+import { WorkspaceTerminalGrid } from "@/components/agentic/WorkspaceTerminalGrid";import { useEventStore } from "@/store/events";import { useIdeChatStore } from "@/store/ideChat";-import { AgenticGrid, rememberViewMode } from "@/components/agentic/AgenticGrid";+import { useIdeProjectsStore } from "@/store/ideProjects";+import { openProject } from "@/lib/chatLibraryApi";import {- VoiceBubble,- storedVoiceBubbleOpen,- storeVoiceBubbleOpen,-} from "@/components/agentic/VoiceBubble";-import {- WorkspaceLauncher,- type PlannedTerminal,-} from "@/components/agentic/WorkspaceLauncher";-import { Button } from "@/components/agentic/controls";-import {- type AgentAccount,- type AgentAccountsResponse,- fetchAgentAccounts,- groupFor,-} from "@/lib/agentAccountsApi";-import { openScratchProject } from "@/lib/chatLibraryApi";--import { WorkspaceBar } from "@/components/agentic/WorkspaceBar";-import {- isEmptyPayload,- type PaneDropPayload,-} from "@/components/agentic/paneDrop";-import {- activateWorkspace,- addTerminal,- attachToTerminal,- closeWorkspace,- endIdeSession,- fetchIdeAgents,- fetchIdeState,- fetchResumeOffer,- forgetResumeOffer,- renameWorkspace,- resumeWorkspace,- setFocusMode,- startIdeSession,- type AgentsResponse,- type IdeAccountState,- type IdeState,- type ResumeOffer,- type SessionState,- type WorkspaceCard,+ activateWorkspace, addTerminal, closeTerminal, closeWorkspace, fetchIdeAgents, fetchIdeProjects, fetchIdeState, renameWorkspace,+ restoreIdeWorkspace, startIdeSession,+ type AgentStatus, type IdeProject, type IdeState, type TerminalState,} from "@/lib/agenticIdeApi";-/**- * Terminal plan for ``count`` panes, preserving whatever the user already chose- * for the panes that still exist.- *- * A pure function called from the click handlers on purpose. The first version- * of this was a `useEffect` that synchronised `planned` against `count` — and- * one of its dependencies was `meta?.suggested_names ?? []`, a fresh array on- * every render. Setting state from an effect whose dependency is recreated each- * render is an infinite loop; it froze the tab and only showed up because a test- * ran out of heap. Deriving on the event that actually changes the plan has no- * such failure mode.- */-function buildPlan(- count: number,- previous: PlannedTerminal[],- agent: string,- names: string[],-): PlannedTerminal[] {- return Array.from({ length: count }, (_, i) => {- const kept = previous[i];- if (kept) return kept;- return { agent, name: names[i] ?? `T${i + 1}` };- });-}+const FONT_KEY = "jarvis.agenticIde.terminalFontSize";+const APPEARANCE_KEY = "jarvis.agenticIde.terminalAppearance";-export interface AgenticIdeViewProps {- /**- * Is this view the section currently on screen?- *- * Unlike every other section, this one is HIDDEN rather than unmounted when- * the user goes elsewhere (see MainView) — its panes are live terminals, and- * tearing them down to rebuild them seconds later is what put an onboarding- * wizard in front of a running workspace. Being hidden with CSS means the- * view cannot measure whether anyone can see it, so the shell says so.- *- * Defaults to true: rendered on its own (tests, any future embedding), a view- * that is there IS on screen, which is how this behaved before it could hide.- */- onScreen?: boolean;-}+export interface AgenticIdeViewProps { onScreen?: boolean }+/** Project and workspace navigation is shared with Sidebar; PTY tiles stay mounted by stable session ID. */export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {- const pushToast = useEventStore((s) => s.pushToast);- const setActiveSection = useEventStore((s) => s.setActiveSection);-- const [loading, setLoading] = useState(true);- const [meta, setMeta] = useState<AgentsResponse | null>(null);- const [session, setSession] = useState<SessionState | null>(null);- const [promptTarget, setPromptTarget] = useState("");- const [focusMode, setFocus] = useState(false);+ const pushToast = useEventStore((state) => state.pushToast);+ const action = useIdeProjectsStore((state) => state.action);+ const publishProjects = useIdeProjectsStore((state) => state.publish);+ const setWorkspace = useIdeChatStore((state) => state.setWorkspace);+ const setWorkspaces = useIdeChatStore((state) => state.setWorkspaces);+ const [state, setState] = useState<IdeState | null>(null);+ const [projects, setProjects] = useState<IdeProject[]>([]);+ const [agents, setAgents] = useState<AgentStatus[]>([]);+ const [projectDialog, setProjectDialog] = useState(false);+ const [projectPath, setProjectPath] = useState<string | null>(null);+ const [projectName, setProjectName] = useState("");+ const [workspaceProject, setWorkspaceProject] = useState<IdeProject | null>(null);+ const [workspaceName, setWorkspaceName] = useState("");+ const [workspaceAgents, setWorkspaceAgents] = useState<string[]>([]);+ const [selected, setSelected] = useState("");+ const [agentMenu, setAgentMenu] = useState(false);+ const [workspaceMenu, setWorkspaceMenu] = useState(false);+ const [renameOpen, setRenameOpen] = useState(false);+ const [renameValue, setRenameValue] = useState("");const [busy, setBusy] = useState(false);- /*- * The floating voice bubble — held HERE, not in the grid, because the- * conversation belongs to the app: the grid is keyed by workspace, and a- * bubble mounted inside it would reset the orb mid-sentence on every tab- * switch (the same reason the old voice column lived outside the grid).- * The choice survives restarts so the bubble greets its user where they- * left it.- */const [voiceOpen, setVoiceOpen] = useState(storedVoiceBubbleOpen);- const toggleVoiceBubble = useCallback(() => {- setVoiceOpen((current) => {- storeVoiceBubbleOpen(!current);- return !current;- });- }, []);- const closeVoiceBubble = useCallback(() => {- storeVoiceBubbleOpen(false);- setVoiceOpen(false);- }, []);-- // Every open workspace, for the bar above. The one on screen is `session`;- // these are the others, still running, one click away.- const [workspaces, setWorkspaces] = useState<WorkspaceCard[]>([]);- const [maxWorkspaces, setMaxWorkspaces] = useState<number | null>(6);- // Which subscription new terminals open on, per coding CLI. Carried on the- // workspace state rather than fetched separately, so the toolbar and the- // panes can never disagree about which plan the next one will spend.- const [ideAccounts, setIdeAccounts] = useState<IdeAccountState[]>([]);- /*- * The wizard is showing for an ADDITIONAL workspace.- *- * Kept as its own flag rather than inferred from `session === null`, because- * the two mean different things once several workspaces exist: no session can- * also be "everything was closed", and the bar has to know whether the +- * button is the selected tab. Pressing + clears the front on the BACKEND too- * (see `startAdding`), which is what stops the outgoing panes from being read- * as a close.- */- const [addingNew, setAddingNew] = useState(false);-- const [folder, setFolder] = useState<string | null>(null);- const [count, setCount] = useState(2);- const [planned, setPlanned] = useState<PlannedTerminal[]>([]);- /*- * Grid or chat — held in the store, not here.- *- * Three copies of this answer used to exist (this view, the grid, the- * store), coupled only by a localStorage key each of them read once on- * mount. Flipping the switch in the workspace bar therefore moved the grid- * and nothing else: the sidebar went on showing the app's sections, because- * its copy of "which view" had been read minutes earlier and never heard- * about the change (maintainer, 2026-08-25 — the sessions did not come- * along when the view changed). One store, one answer, every reader on it.- */- const view = useIdeChatStore((s) => s.view);- const setView = useIdeChatStore((s) => s.setView);- const publishWorkspace = useIdeChatStore((s) => s.setWorkspace);- const paneRequest = useIdeChatStore((s) => s.paneRequest);- const terminalRequest = useIdeChatStore((s) => s.terminalRequest);- const workspaceRequest = useIdeChatStore((s) => s.workspaceRequest);- const sessionRequest = useIdeChatStore((s) => s.sessionRequest);- const newChatRequest = useIdeChatStore((s) => s.newChatRequest);- const addWorkspaceRequest = useIdeChatStore((s) => s.addWorkspaceRequest);- const publishWorkspaces = useIdeChatStore((s) => s.setWorkspaces);- const publishAgents = useIdeChatStore((s) => s.setAgents);- // The registered subscriptions per CLI. Only ever used to OFFER a choice, so- // a failed load costs the picker, never the wizard: with none loaded every- // pane simply opens on the active account, exactly as before.- const [accounts, setAccounts] = useState<AgentAccountsResponse | null>(null);- // The workspace that was open when the window last closed, if it can come- // back. Null both when there is nothing to offer and after the user has- // answered the offer either way.- const [offer, setOffer] = useState<ResumeOffer | null>(null);-- /**- * Re-read the agent sweep alone, without disturbing the workspace state.- *- * The user just added, edited or removed a CLI of their own, and that is the- * ONE thing this read answers differently than a second ago. Going through- * `refresh()` would also re-read the session and the workspace list — several- * hundred milliseconds of work whose answer has not changed, and one of them- * closes the wizard when it finds a workspace open.- */- const reloadAgents = useCallback(- () =>- fetchIdeAgents().then(setMeta, () => {- /* Same bargain as the sweep in `refresh`: the entry is already stored- and registered, so a failed re-read costs an out-of-date list, not- the change itself. */- }),- [],- );-- const refresh = useCallback(async () => {- /*- * Both reads start together, but the workspace is applied WITHOUT waiting- * for the agent sweep.- *- * `/agents` starts one subprocess per registered CLI — 1.1-1.4 s on a cold- * cache, and on Windows every one of those is an npm shim (see- * `_DETECTION_TTL_S` in jarvis/workspace/agents.py). Awaiting the two- * together meant a running workspace could not be drawn until a question- * about which CLIs are installed had been answered, which is a question the- * grid never asks. The wizard needs the answer; the grid does not, and the- * grid is what the user is coming back to.- */- const sweep = fetchIdeAgents().then(setMeta, () => {- // Swallowed on purpose, and it costs exactly what it did when this was- // one `Promise.all`: `meta` stays as it was, so the wizard opens without- // its install callouts and the agent step offers whatever it had before.- // A failed sweep must not take the workspace state down with it — that- // state is the half of this read that the user is here for.- });- try {- const state = await fetchIdeState();- setSession(state.session);- setWorkspaces(state.workspaces ?? []);- setMaxWorkspaces(- state.max_workspaces === undefined ? 6 : state.max_workspaces,- );- setIdeAccounts(state.accounts ?? []);- setFocus(Boolean(state.session?.focus_mode));- // The backend is the authority on whether a workspace is on screen. It- // says so by carrying one in `session`, so a fetch that finds one ends- // the "adding" state — otherwise a workspace opened in another tab (or- // by voice) would come up behind a wizard nobody asked for.- if (state.session !== null) setAddingNew(false);- // Only worth asking about when NOTHING is open. With a workspace around,- // its panes reconnect and continue by themselves — the offer is for the- // case where the workspaces themselves did not survive.- if ((state.workspaces ?? []).length === 0) {- try {- const previous = await fetchResumeOffer();- setOffer(previous.workspaces.length > 0 ? previous : null);- } catch {- /* no offer is a perfectly good answer — the wizard still works */- }- } else {- setOffer(null);- }- } catch {- /* backend still warming or headless — keep whatever we had */- } finally {- // What `loading` gates is the WIZARD (see the render below), and a wizard- // shown before the sweep lands is one whose agent step has nothing to- // offer — so the placeholder holds until it is in. A workspace that is- // already open never waits for this: the running branch is chosen before- // `loading` is read at all.- await sweep;- setLoading(false);- }- }, []);-- /** Apply a state the backend just handed back, without a second round-trip. */- const applyState = useCallback((state: IdeState) => {- setSession(state.session);- setWorkspaces(state.workspaces ?? []);- setMaxWorkspaces(- state.max_workspaces === undefined ? 6 : state.max_workspaces,- );- setFocus(Boolean(state.session?.focus_mode));- // Absent on a backend that predates the switcher — keeping what we had- // beats blanking the toolbar over a field that simply was not sent.- if (state.accounts) setIdeAccounts(state.accounts);- }, []);-- useEffect(() => {- void refresh();- }, [refresh]);-- // Loaded once, and deliberately NOT part of `refresh`: the wizard must open- // even when this fails. Without it every pane opens on the active account,- // which is exactly what happened before the switcher existed.- useEffect(() => {- fetchAgentAccounts()- .then(setAccounts)- .catch(() => setAccounts(null));- }, []);-- /*- * A state the workspace's settings panel handed back.- *- * Same as `applyState`, plus a re-read of the subscription list: that panel- * can ADD an account, and the wizard's per-pane picker was loaded once on- * mount — without this the next workspace would be offered a list one account- * short until the app is reloaded.- */- const applyStateFromSettings = useCallback(- (state: IdeState) => {- applyState(state);- fetchAgentAccounts()- .then(setAccounts)- .catch(() => undefined);- },- [applyState],- );-- /** The registered subscriptions of one CLI, for the wizard's per-pane picker. */- const accountsFor = useCallback(- // No id guard: the backend already answers only for the CLIs that HAVE- // switchable subscriptions, so a list here could only ever disagree with- // it — and it would disagree silently, by hiding a picker for a CLI whose- // seats the API just returned.- (platform: string): AgentAccount[] =>- groupFor(accounts, platform)?.accounts ?? [],- [accounts],- );-- /*- * Panes can appear without this view asking for them.- *- * Saying "spawn five more Claude Code terminals" adds them in the backend; the- * grid below renders whatever the last fetch returned, so without this listener- * the panes exist, their agents are told to start — and the user sees nothing.- * The event carries the new call-signs, but they are deliberately ignored here:- * re-fetching keeps ONE source of truth for the layout instead of patching the- * session object from a payload that could be a step behind.- */- useEffect(() => {- const onChanged = () => void refresh();- window.addEventListener("jarvis:agentic-ide-changed", onChanged);- return () =>- window.removeEventListener("jarvis:agentic-ide-changed", onChanged);- }, [refresh]);-- /*- * Being in this section IS the coding mode.- *- * Focus mode started as a switch you had to remember to flip, and the result- * was predictable: the workspace was open, agents were running, and Jarvis- * still answered as the general-purpose assistant because nobody had pressed- * the button. Standing in a room full of running coding agents and having to- * announce that you are now coding is not a mode, it is paperwork. So opening- * a workspace turns it on.- *- * The switch stays, and it stays honest: turning it OFF here is respected for- * as long as this workspace is open (`optedOutRef`), so "I want the normal- * assistant for a minute" works and does not get overridden a second later.- */- const optedOutRef = useRef(false);- /*- * Was the mode switched on BY this screen, or by the user?- *- * It decides what happens when the section is left. An auto-enabled mode is- * on loan — it belongs to this screen and goes back when you walk away. A- * mode the user switched on by hand is theirs, and stays on everywhere, which- * is how "ask Jarvis about my terminals from the kitchen" keeps working.- *- * Without this distinction the mode simply never turned off: this view- * switched it on, nothing switched it off, and because the view is sticky- * (see MainView) there was not even an unmount to hang the cleanup on. The- * result was an assistant permanently in coding mode on every screen, with- * only a small badge admitting it.- */- const autoEnabledRef = useRef(false);- const [modeIntroFor, setModeIntroFor] = useState<string | null>(null);-- /*- * How wide the workspace will be — measured here, in the wizard, because- * the preview must promise the arrangement the grid will actually produce.- *- * Width is what stops panes becoming unreadably narrow, and it is the ONLY- * thing that wraps a workspace: which panes share a row is otherwise the- * user's own choice, made through the split buttons. A preview computing- * columns from the count alone drifts apart from the running grid. The- * wizard shell sits in the same slot the grid will occupy, so measuring it- * here answers the same question.- *- * The readout names the width condition rather than silently assuming it —- * see WorkspaceShape. Measuring makes the picture correct for the window it- * was shown in; saying so is what keeps it honest after a resize.- */- const shellRef = useRef<HTMLDivElement | null>(null);- const [shellWidth, setShellWidth] = useState(0);- useEffect(() => {- const node = shellRef.current;- if (!node || typeof ResizeObserver === "undefined") return;- setShellWidth(node.clientWidth);- const observer = new ResizeObserver((entries) => {- const width = entries[0]?.contentRect.width ?? node.clientWidth;- // Same 16 px step the grid rounds to, so both sides flip at one width.- setShellWidth(Math.round(width / 16) * 16);- });- observer.observe(node);- return () => observer.disconnect();- // Both states decide WHICH element (if any) carries `shellRef`, so both have- // to re-run the measurement. `loading` is easy to forget and silent when it- // is: the first read finds no node, gives up, and the preview then promises- // an arrangement computed from a width of zero for the rest of the session.- }, [session, loading]);+ const [fontSize, setFontSize] = useState(() => Number(localStorage.getItem(FONT_KEY)) || 13);+ const [appearance, setAppearance] = useState<"light" | "dark" | null>(() => {+ const stored = localStorage.getItem(APPEARANCE_KEY);+ return stored === "light" || stored === "dark" ? stored : null;+ });+ const handledAction = useRef(0);+ const refreshEpoch = useRef(0);+ const activationRunning = useRef(false);+ const pendingActivation = useRef<string | null>(null);+ const session = state?.session ?? null;+ const activeProject = projects.find((project) => project.id === session?.project_id || project.workspaces.some((workspace) => workspace.id === session?.id));+ const installed = agents.filter((agent) => agent.installed && agent.kind !== "shell" && agent.accepts_prompts !== false);+ const dialogOpen = projectDialog || workspaceProject !== null || renameOpen;useEffect(() => {- // Gated on the LOCAL flag, not `session.focus_mode`: `session` is only- // refetched by `refresh`, so after this effect's counterpart hands the mode- // back on leaving, the cached session still claims the mode is on and- // returning to the section would never switch it on again. The local flag- // is the one that tracks what actually happened — and it is trustworthy- // here because `session` is non-null only once a refresh has landed, and- // that same refresh sets the flag from the backend.- if (!onScreen || !session || focusMode || optedOutRef.current) return;- let cancelled = false;- void (async () => {- try {- const on = await setFocusMode(true);- if (cancelled) return;- setFocus(on);- autoEnabledRef.current = on;- // First workspace on this machine: say once what just changed. A mode- // that switches silently is indistinguishable from a bug.- if (on && !hasSeenModeIntro()) setModeIntroFor(session.id);- } catch {- /* the workspace still works; the mode toggle stays available */+ if (!dialogOpen) return;+ const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;+ const dialog = document.querySelector<HTMLElement>("[data-ide-dialog]");+ if (!dialog) return;+ const focusable = () => [...dialog.querySelectorAll<HTMLElement>('button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')];+ (focusable()[0] ?? dialog).focus();+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.preventDefault();+ setProjectDialog(false); setWorkspaceProject(null); setRenameOpen(false);+ return;}- })();- return () => {- cancelled = true;+ if (event.key !== "Tab") return;+ const items = focusable();+ if (items.length === 0) { event.preventDefault(); dialog.focus(); return; }+ const first = items[0], last = items[items.length - 1];+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }};- // `onScreen` belongs here: this view is sticky and stays mounted, so coming- // back to the section is a prop change, not a remount. Without it the mode- // would be given back on leaving and never picked up again on return.- }, [session, onScreen, focusMode]);-- /*- * Leaving the section gives the mode back.- *- * The signal is `onScreen`, not an unmount — MainView keeps this view mounted- * on purpose so a dozen terminals survive a trip to Settings, which means- * there is no unmount to clean up on. Only an auto-enabled mode is returned;- * one the user switched on by hand is left alone.- *- * Failure is deliberately silent. This runs while the user is already looking- * at another section, and a toast about a mode belonging to the screen they- * just left would be noise pointing at nothing. The app-wide badge keeps- * telling the truth either way, because it re-reads the backend on every- * section change (useCodingMode, path 4).- */- useEffect(() => {- if (onScreen) return;- if (!autoEnabledRef.current) return;- autoEnabledRef.current = false;- void setFocusMode(false)- .then(() => setFocus(false))- .catch(() => {});- }, [onScreen]);-- // Memoised so these arrays keep a stable identity across renders — see the- // note on buildPlan for what an unstable one costs.- const agents = useMemo(() => meta?.agents ?? [], [meta]);- const suggested = useMemo(() => meta?.suggested_names ?? [], [meta]);- const installed = useMemo(() => agents.filter((a) => a.installed), [agents]);- const defaultAgent = installed[0]?.name ?? "claude";- const maxTerminals = meta?.max_terminals ?? 12;-- // What the grid's split menus offer — every entry the backend registered, so- // the coding CLIs and the plain terminal, and anything registered later- // without a change here. Uninstalled entries stay in the list but disabled,- // so their absence is visible rather than silently missing — and carry their- // install command, which is what lets the menu offer to fix it on the spot.- const splitChoices = useMemo(- () =>- agents.map((a) => ({- name: a.name,- displayName: a.display_name,- installed: a.installed,- kind: a.kind ?? "cli",- logoUrl: a.logo_url || undefined,- installCommand: a.install_command || undefined,- // Whether a chat can be STARTED here at all, and what it could run on.- // Both are the backend's answer (`jarvis/workspace/launch_picks.py`),- // carried through unchanged: the split menus ignore them, and the chat- // surface — which opens a conversation rather than just a pane — reads- // them to decide what to offer and what to pass back at spawn.- acceptsPrompts: a.accepts_prompts ?? true,- picks: {- models: a.models ?? [],- defaultModel: a.default_model ?? "",- effortLevels: a.effort_levels ?? [],- defaultEffort: a.default_effort ?? "",- permissionModes: a.permission_modes ?? [],- defaultPermissionMode: a.default_permission_mode ?? "",- },- // For a plain terminal the useful second line is WHICH shell opens; a- // CLI's name already says what it is, so it gets no line of its own.- description:- a.kind === "shell" && a.version- ? `${a.version} — no agent, just a prompt`- : (a.description ?? ""),- })),- [agents],- );-- const chooseCount = (n: number) => {- const next = Math.max(1, Math.min(maxTerminals, Math.trunc(n)));- setCount(next);- setPlanned((prev) => buildPlan(next, prev, "", suggested));- };-- const replayRecent = (recent: {- path: string;- terminals: number;- agents: Record<string, number>;- }) => {- const total = Math.max(1, Math.min(recent.terminals, maxTerminals));- setCount(total);- // Only agents this machine can actually open.- //- // A remembered folder outlives the entry it was worked in: a CLI the user- // added themselves and later deleted, one renamed between releases, one- // uninstalled since. The backend refuses the WHOLE open when any requested- // agent is unknown or missing ("Unknown agent(s): …"), so a single dead id- // in this list made the folder unopenable from here — with an error naming- // an agent the user no longer has and no way to get past it. Dropping the- // dead ids and topping the plan back up keeps the folder openable; the- // panes are staged, so what came back is visible before anything runs.- const usable = new Set(- agents.filter((a) => a.installed).map((a) => a.name),- );- const entries = Object.entries(recent.agents ?? {}).filter(- ([agent, n]) => n > 0 && usable.has(agent),- );- if (entries.length === 0) {- setPlanned(buildPlan(total, [], defaultAgent, suggested));- return;+ document.addEventListener("keydown", onKeyDown, true);+ return () => { document.removeEventListener("keydown", onKeyDown, true); previous?.focus(); };+ }, [dialogOpen, projectDialog, workspaceProject, renameOpen]);++ const refresh = useCallback(async (allowDuringActivation = false) => {+ if (activationRunning.current && !allowDuringActivation) return;+ const epoch = ++refreshEpoch.current;+ let [nextState, listing] = await Promise.all([fetchIdeState(), fetchIdeProjects()]);+ // A workspace switch can fall between the two reads. Never publish a tree+ // whose active row disagrees with the grid it is paired with.+ if (nextState.active_id !== listing.active_workspace_id) {+ [nextState, listing] = await Promise.all([fetchIdeState(), fetchIdeProjects()]);}- // Expand the remembered split back into one pane per terminal, grouped the- // way it was, then re-apply the call-sign pool in grid order.- const expanded: string[] = [];- for (const [agent, n] of entries) {- for (let i = 0; i < n && expanded.length < total; i += 1)- expanded.push(agent);- }- while (expanded.length < total) expanded.push(defaultAgent);- setPlanned(- expanded.map((agent, index) => ({- agent,- name: suggested[index] ?? `T${index + 1}`,- })),- );- };+ if (epoch !== refreshEpoch.current || pendingActivation.current || (activationRunning.current && !allowDuringActivation) || nextState.active_id !== listing.active_workspace_id) return;+ setState(nextState);+ setProjects(listing.projects);+ publishProjects(listing.projects, listing.active_workspace_id);+ }, [publishProjects]);- /*- * The plan is built when the count changes rather than held in sync with it.- *- * It is also built once the agent sweep lands so the staged launcher already- * has useful defaults when the user reaches Agents. Guarding on length keeps- * backward navigation from overwriting choices already made.- */useEffect(() => {- // Not before the sweep lands. `suggested` is empty until it does, so an- // earlier run would fill the plan with T1/T2 placeholders — and the guard- // below, which exists to protect choices the user has made, would then- // faithfully protect those placeholders from the real call-signs.- if (!meta) return;- setPlanned((previous) =>- previous.length === count- ? previous- : buildPlan(count, previous, "", suggested),- );- }, [meta, count, suggested]);-- const start = async () => {- if (!folder) return;- setBusy(true);- // Recorded BEFORE the grid can mount: a grid coming up in a fresh window- // reads the stored preference, so the wizard's answer has to be on disk by- // then. `setView` writes it too; this is the belt for the braces.- rememberViewMode(view);- try {- // The open answers with the whole state — the new workspace AND the bar.- // Re-fetching instead would be a race that can blank what was just opened.- const next = await startIdeSession(folder, planned);- applyState(next);- setAddingNew(false);- // The launcher is reusable — someone who opens a third workspace should- // not land on the leftovers of the second one's plan.- setFolder(null);- const names = next.session?.terminals.map((x) => x.name).join(", ") ?? "";- pushToast("success", `Workspace open — ${names}`);- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setBusy(false);- }- };-- const close = async () => {- setBusy(true);- try {- await endIdeSession();- setFocus(false);- // Closing on purpose withdraws the offer, so the wizard comes back clean- // rather than immediately proposing the workspace just shut down.- setOffer(null);- // Whatever is still open takes the front; only a full refresh knows what- // that is, so the view asks rather than guessing it is now empty.- await refresh();- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setBusy(false);- }- };+ void refresh().catch((error) => pushToast("error", (error as Error).message));+ void fetchIdeAgents(true).then((response) => setAgents(response.agents)).catch((error) => pushToast("error", (error as Error).message));+ }, [refresh, pushToast]);- /*- * ------------------------------------------------------------ workspace bar- *- * All three actions share one rule, and it is the whole reason they are- * awaited rather than fired off: **the backend has to know the front workspace- * changed BEFORE the outgoing panes come down.**- *- * A pane that disappears releases its viewer, and the backend decides what- * that means from which workspace the pane belongs to. Ordering the state- * change after the round-trip keeps that decision correct; doing it the other- * way round would tear down panes while their workspace was still the front- * one, which is the difference between "switched tab" and "closed".- */- const switchTo = async (id: string) => {- if (busy || (id === session?.id && !addingNew)) return;- setBusy(true);- try {- applyState(await activateWorkspace(id));- setAddingNew(false);- setOffer(null);- } catch (e) {- pushToast("error", (e as Error).message);- // The tab may have been closed elsewhere — re-read rather than leave a- // bar showing a workspace that is not there.- void refresh();- } finally {- setBusy(false);- }- };-- /*- * "Jump to a pane in another workspace", from the header bell.- *- * The grid cannot do this half itself: it is keyed by workspace, so switching- * tab REPLACES it — a maximize applied before the switch would land on the- * grid that is about to be thrown away, and one applied after it has no- * component left to call. So the wish is parked here, survives the swap, and- * is handed to the grid that comes up as `jumpTo`.- *- * The nonce is what lets the same pane be jumped to twice in a row: an effect- * cannot re-fire on a value that has not changed.- */- const [jumpTo, setJumpTo] = useState<{ pane: string; nonce: number } | null>(null);- const jumpToPane = useCallback(- async (workspaceId: string, pane: string) => {- if (workspaceId !== session?.id) await switchTo(workspaceId);- setJumpTo({ pane, nonce: Date.now() });- },- [session?.id, switchTo],- );-- /*- * Tell the rest of the app WHICH workspace is open.- *- * Nothing published this, so the store's `workspace` stayed null forever and- * every reader that gates on it — the sidebar's chat face above all — was- * unreachable code. The folder travels with it because that is the one thing- * the IDE knows and a chat list does not: which project a session is- * touching.- */useEffect(() => {if (!onScreen) return;- publishWorkspace(- session- ? { id: session.id, name: session.project.name, path: session.folder }- : null,- );- }, [onScreen, publishWorkspace, session]);-- /*- * Leaving the section hands the navigation back.- *- * Without this the sidebar keeps the workspace's chats while the user is- * reading Costs, because "is a workspace open" stayed true after this view- * went off screen.- */- useEffect(() => {- if (onScreen) return;- publishWorkspace(null);- }, [onScreen, publishWorkspace]);-- /*- * A session list asked for one pane.- *- * The list is in the app sidebar, outside this view and outside the grid, so- * the ask arrives through the store and is performed here — by the same jump- * the notification bell and the voice bubble use, which already knows how to- * switch workspace first.- */- const lastPaneRequest = useRef(0);- useEffect(() => {- if (!paneRequest || paneRequest.nonce === lastPaneRequest.current) return;- lastPaneRequest.current = paneRequest.nonce;- void jumpToPane(paneRequest.workspaceId, paneRequest.pane);- }, [jumpToPane, paneRequest]);+ void refresh().catch((error) => console.warn("Agentic IDE state refresh failed:", error));+ const timer = window.setInterval(() => {+ void refresh().catch((error) => console.warn("Agentic IDE state refresh failed:", error));+ }, 4000);+ return () => window.clearInterval(timer);+ }, [onScreen, refresh]);- /*- * The sidebar's session list draws every open workspace as a band — the- * same list the workspace bar draws, with the folder and which tab is at- * the front — and offers a new terminal under each, from the CLIs the- * grid's own split menus offer. Both are published from here because this- * view is the one place that holds them.- */- useEffect(() => {- publishWorkspaces(- onScreen- ? workspaces.map((w) => ({- id: w.id,- name: w.name,- folder: w.folder,- active: session ? w.id === session.id : w.active,- }))- : [],- );- }, [onScreen, publishWorkspaces, workspaces, session]);useEffect(() => {- publishAgents(splitChoices);- }, [publishAgents, splitChoices]);+ setWorkspace(session ? { id: session.id, name: session.name ?? session.project.name, path: session.folder } : null);+ setWorkspaces((state?.workspaces ?? []).map((workspace) => ({ id: workspace.id, name: workspace.name, folder: workspace.folder, active: workspace.active })));+ if (session && !session.terminals.some((terminal) => terminal.name === selected)) setSelected(session.terminals[0]?.name ?? "");+ }, [session, state?.workspaces, selected, setWorkspace, setWorkspaces]);- /*- * The sidebar asked for a new terminal in one workspace, or for one- * workspace's tab. Switching first when the ask names another tab, the- * way a pane request does; the grid then sees the new pane arrive and, in- * chat view, puts it on the stage.- */- const lastTerminalRequest = useRef(0);- useEffect(() => {- if (!terminalRequest || terminalRequest.nonce === lastTerminalRequest.current) return;- lastTerminalRequest.current = terminalRequest.nonce;- const { workspaceId, agent } = terminalRequest;- void (async () => {- try {- if (workspaceId !== session?.id) await switchTo(workspaceId);- setSession(await addTerminal({ agent }));- } catch (error) {- pushToast("error", error instanceof Error ? error.message : String(error));- }- })();- // `session` and `switchTo` are read at the moment of the ask, on purpose.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [terminalRequest]);- /*- * A new chat asked for in another workspace: bring that tab to the front and- * let its own grid open the draft. The grid is where the stage lives, so the- * request is answered there — this only makes sure the right one sees it.- */- const lastNewChatSwitch = useRef(0);- useEffect(() => {- if (!newChatRequest || newChatRequest.nonce === lastNewChatSwitch.current) return;- lastNewChatSwitch.current = newChatRequest.nonce;- if (newChatRequest.workspaceId !== session?.id) void switchTo(newChatRequest.workspaceId);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [newChatRequest]);- const lastWorkspaceRequest = useRef(0);- useEffect(() => {- if (!workspaceRequest || workspaceRequest.nonce === lastWorkspaceRequest.current) return;- lastWorkspaceRequest.current = workspaceRequest.nonce;- if (workspaceRequest.workspaceId !== session?.id) void switchTo(workspaceRequest.workspaceId);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [workspaceRequest]);- // A workspace with no project folder, asked for from the sidebar's last row.- const lastSessionRequest = useRef(0);- useEffect(() => {- if (!sessionRequest || sessionRequest.nonce === lastSessionRequest.current) return;- lastSessionRequest.current = sessionRequest.nonce;- void startSession();- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [sessionRequest]);- /*- * "Open one more workspace", asked for from the sidebar.- *- * The same act as the workspace bar's "+", performed by the same function,- * because it must be the same thing: chat mode hides the bar behind its own- * navigation, and a second, thinner "new workspace" reachable only from the- * sidebar would be one more flow to keep in step with this one. The launcher- * that comes up carries the folder picker, the pane count and the agents.- */- const lastAddWorkspaceRequest = useRef(0);- useEffect(() => {- if (!addWorkspaceRequest || addWorkspaceRequest.nonce === lastAddWorkspaceRequest.current)- return;- lastAddWorkspaceRequest.current = addWorkspaceRequest.nonce;- void startAdding();- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [addWorkspaceRequest]);-- /*- * A file dropped on a workspace TAB.- *- * It goes to that workspace's first pane, and the pane types the reference- * rather than swallowing it: a tab is a coarse target — it names a project,- * not an agent — so the honest reading is "put this in front of the agents- * over there", and the user finishes the thought when they switch to it.- * That is why this does not analyse or compose: the prompt bar is where a- * dropped file becomes part of an instruction, and this is not that.- *- * Dropping on the tab you are already on is the same gesture, so it is not- * special-cased away; switching to the target afterwards is what makes the- * result visible rather than something the user has to go looking for.- */- const dropOnWorkspace = async (id: string, payload: PaneDropPayload) => {- if (isEmptyPayload(payload)) return;- const label = workspaces.find((w) => w.id === id)?.name ?? "that workspace";- try {- // Switch FIRST, and not as a courtesy: a workspace card carries no pane- // names, so activating it is how the target pane becomes knowable at all.- // It also puts the user in front of the result instead of leaving the- // file somewhere they would have to go and find.- let active = session;- if (id !== session?.id || addingNew) {- const state = await activateWorkspace(id);- applyState(state);- setAddingNew(false);- setOffer(null);- active = state.session;- }- const pane = active?.terminals[0]?.name;- if (!pane) {- pushToast("warning", `${label} has no agent running to give the file to.`);- return;- }- const result = await attachToTerminal(pane, payload);- pushToast("success", `${result.files.join(", ")} → ${pane} in ${label}.`);- } catch (e) {- pushToast("error", (e as Error).message);- }- };-- /**- * Open a workspace without asking which folder.- *- * A question, a quick script, "what is in this file" are all worth asking- * without first naming a repository to ask them in. The agent still runs- * somewhere — a coding CLI is a process with a working directory and there is- * no such thing as nowhere — so it runs in the home folder, which exists on- * every account on every OS. The backend owns that choice (it is the same- * folder the chat library calls a session), so nothing here has to guess a- * path or spell one out per platform.- */- const startSession = async () => {- if (busy) return;- setBusy(true);- try {- const home = await openScratchProject();- const next = await startIdeSession(home.path, [{ agent: defaultAgent }]);- applyState(next);- setAddingNew(false);- setFolder(null);- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setBusy(false);- }- };-- const startAdding = async () => {- if (busy) return;+ const run = useCallback(async (work: () => Promise<void>) => {+ ++refreshEpoch.current; // invalidate reads started before this mutationsetBusy(true);- try {- applyState(await activateWorkspace(null));- setAddingNew(true);- // A fresh plan, not the previous workspace's.- setFolder(null);- setOffer(null);- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setBusy(false);- }- };-- const closeOne = async (id: string) => {- if (busy) return;+ try { await work(); await refresh(); }+ catch (error) { pushToast("error", (error as Error).message); }+ finally { setBusy(false); }+ }, [pushToast, refresh]);++ const activateFromTree = useCallback(async (workspaceId: string) => {+ pendingActivation.current = workspaceId;+ if (activationRunning.current) return;+ activationRunning.current = true;+ ++refreshEpoch.current;setBusy(true);try {- const next = await closeWorkspace(id);- applyState(next);- if (next.session === null && (next.workspaces ?? []).length === 0) {- // Nothing left — the wizard is the screen again, and the offer for the- // workspace just shut down has been withdrawn with it.- setAddingNew(false);- setOffer(null);+ while (pendingActivation.current) {+ const targetId = pendingActivation.current;+ pendingActivation.current = null;+ const target = useIdeProjectsStore.getState().projects.flatMap((project) => project.workspaces).find((workspace) => workspace.id === targetId);+ try {+ const next = target?.status === "closed" ? await restoreIdeWorkspace(targetId) : await activateWorkspace(targetId);+ // A newer click is waiting: finish the switch in order, but never+ // paint the superseded workspace or publish it as current context.+ if (pendingActivation.current) continue;+ setState(next);+ await refresh(true);+ } catch (error) {+ pushToast("error", (error as Error).message);+ }}- } catch (e) {- pushToast("error", (e as Error).message);- void refresh();} finally {+ activationRunning.current = false;setBusy(false);}- };+ }, [pushToast, refresh]);- const renameOne = async (id: string, name: string) => {- if (busy) return false;- setBusy(true);- try {- applyState(await renameWorkspace(id, name));- return true;- } catch (e) {- pushToast("error", (e as Error).message);- return false;- } finally {- setBusy(false);+ useEffect(() => {+ if (!action || handledAction.current === action.nonce) return;+ handledAction.current = action.nonce;+ if (action.kind === "connect-project") { setProjectDialog(true); return; }+ if (action.kind === "new-workspace") {+ const project = projects.find((entry) => entry.id === action.projectId);+ if (project) { setWorkspaceProject(project); setWorkspaceName(""); setWorkspaceAgents([installed[0]?.name ?? ""]); }+ return;}- };+ void activateFromTree(action.workspaceId);+ }, [action, activateFromTree, installed, projects]);++ const connect = () => void run(async () => {+ if (!projectPath) throw new Error("Choose a folder for this project.");+ const project = await openProject(projectPath, projectName.trim() || undefined);+ setProjectDialog(false); setProjectPath(null); setProjectName("");+ const listing = await fetchIdeProjects();+ setProjects(listing.projects);+ publishProjects(listing.projects, listing.active_workspace_id);+ const found = listing.projects.find((entry) => entry.id === project.id);+ if (found) { setWorkspaceProject(found); setWorkspaceAgents([installed[0]?.name ?? ""]); }+ });- const resumeAll = async () => {- setBusy(true);- try {- const result = await resumeWorkspace();- applyState(result.state);- setAddingNew(false);- setOffer(null);- // Report what actually came back, not what was hoped for. A pane that- // reopened empty looks exactly like one that continued until it is asked- // a follow-up question, so the counts have to be said out loud — and so- // does any workspace that could not come back at all.- const spaces = result.workspace_count;- const panes = result.terminal_count;- const head =- `Resumed ${spaces} workspace${spaces === 1 ? "" : "s"}` +- ` · ${panes} terminal${panes === 1 ? "" : "s"}`;- const conversations =- result.started_fresh === 0- ? "every conversation continued"- : `${result.resumable_count} continued, ${result.started_fresh} started fresh`;- pushToast("success", `${head} — ${conversations}.`);- for (const missing of result.skipped) {- pushToast("warning", `${missing.folder}: ${missing.detail}`);- }- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setBusy(false);- }- };+ const createWorkspace = () => void run(async () => {+ if (!workspaceProject || workspaceAgents.length === 0 || workspaceAgents.some((agent) => !agent)) throw new Error("Choose an installed coding agent for every session.");+ const next = await startIdeSession(workspaceProject.path, workspaceAgents.map((agent) => ({ agent })), {+ projectId: workspaceProject.id, name: workspaceName.trim() || undefined,+ });+ setState(next);+ setWorkspaceProject(null);+ });- const dismissOffer = async () => {- // Cleared on screen first: the user said no, and that should not wait for a- // round-trip. A failed delete only means the offer returns next visit.- setOffer(null);- try {- await forgetResumeOffer();- } catch (e) {- pushToast("error", (e as Error).message);- }- };+ const addAgent = (agentName?: string) => void run(async () => {+ if (!session) return;+ if (session.terminals.length >= 8) throw new Error("This workspace already has eight sessions.");+ const next = await addTerminal({ workspace_id: session.id, agent: agentName ?? installed[0]?.name, direction: "down" });+ setState((current) => current ? { ...current, session: next } : current);+ });- const toggleFocus = async (enabled: boolean) => {- // Remember a deliberate opt-out, or the auto-enable effect above would turn- // the mode straight back on and the switch would look broken.- optedOutRef.current = !enabled;- // Touching the switch takes ownership of the mode either way: switching it- // on by hand means "keep it on when I leave", switching it off means there- // is nothing left for the leave-handler to undo.- autoEnabledRef.current = false;- try {- setFocus(await setFocusMode(enabled));- } catch (e) {- pushToast("error", (e as Error).message);- }- };+ const closeAgent = (terminal: TerminalState) => void run(async () => {+ if (!session || !window.confirm(`Close ${terminal.name}? Its coding agent will stop.`)) return;+ await closeTerminal(terminal.name, session.id);+ });- /*- * The workspace bar sits above BOTH states, always in the same place.- *- * It is the one part of this view that is not about the workspace you are in- * — it is about which one you are in — so it stays put whether the grid or- * the wizard is below it. A bar that moved (or vanished while adding one)- * would leave the user without a way back to the workspaces still running.- *- * With a workspace open it is handed to the grid rather than rendered here,- * so the tabs and that workspace's controls share ONE row (see the grid's- * `workspaceBar` prop). Same bar, same place on screen — one line instead of- * two, which in a view full of terminals is a pane's worth of output.- *- * Pane actions return the updated session, while the compact workspace cards- * remain the snapshot from the last full-state request. Replace the active- * card's count from that live session so closing or adding a terminal updates- * the badge immediately instead of leaving the original spawn count behind.- */- const barWorkspaces = workspaces.map((workspace) =>- session && workspace.id === session.id- ? { ...workspace, terminals: session.terminals.length }- : workspace,- );- const renderBar = (embedded: boolean) => (- <WorkspaceBar- embedded={embedded}- workspaces={barWorkspaces}- activeId={session?.id ?? null}- addingNew={addingNew}- maxWorkspaces={maxWorkspaces}- onSelect={(id) => void switchTo(id)}- onAdd={() => void startAdding()}- onRename={renameOne}- onClose={(id) => void closeOne(id)}- onDropFiles={(id, payload) => void dropOnWorkspace(id, payload)}- busy={busy}- />- );+ const saveFont = (size: number) => { const next = Math.max(9, Math.min(22, size)); setFontSize(next); localStorage.setItem(FONT_KEY, String(next)); };+ const saveAppearance = (next: "light" | "dark" | null) => { setAppearance(next); if (next) localStorage.setItem(APPEARANCE_KEY, next); else localStorage.removeItem(APPEARANCE_KEY); };+ const closeVoice = () => { setVoiceOpen(false); storeVoiceBubbleOpen(false); };+ const jumpToPane = (workspaceId: string, pane: string) => void run(async () => {+ if (workspaceId !== session?.id) setState(await activateWorkspace(workspaceId));+ setSelected(pane);+ });+ const saveWorkspaceName = () => void run(async () => {+ if (!session || !renameValue.trim()) return;+ setState(await renameWorkspace(session.id, renameValue.trim()));+ setRenameOpen(false);+ });+ const stopWorkspace = () => void run(async () => {+ if (!session || !window.confirm(`Close ${session.name ?? session.project.name}? Its coding agents will stop.`)) return;+ setState(await closeWorkspace(session.id));+ setWorkspaceMenu(false);+ });- // ------------------------------------------------------------ running mode- if (session && !addingNew) {- return (- <div className="flex h-full flex-col">- <div className="min-h-0 min-w-0 flex-1">- {/*- Keyed by workspace, so switching tabs REPLACES the grid instead of- re-using it. That is deliberate: each pane's terminal is wired to- one call-sign for its whole life, and re-using the component across- workspaces would leave xterm instances pointed at the panes of the- workspace that just left.- */}- <AgenticGrid- key={session.id}- session={session}- workspaceBar={renderBar(true)}- onJumpToWorkspace={(id, pane) => void jumpToPane(id, pane)}- jumpTo={jumpTo}- focusMode={focusMode}- onToggleFocus={(v) => void toggleFocus(v)}- onClose={() => void close()}- busy={busy}- maxTerminals={maxTerminals}- agents={splitChoices}- /* An install started from a split menu changes the one thing this- list answers, and the sweep behind it is cached — so the re-read- is explicit rather than waited for. */- onAgentsChanged={() => void reloadAgents()}- onSessionChanged={setSession}- accounts={ideAccounts}- onStateChanged={applyStateFromSettings}- onScreen={onScreen}- onPromptTargetChange={setPromptTarget}- voiceOpen={voiceOpen}- onToggleVoice={toggleVoiceBubble}- />- </div>- {/*- The floating voice bubble: talk to the assistant while the agents- work. A fixed overlay rather than a column, so the terminals keep- the whole width in every view mode; OUTSIDE the per-workspace grid- on purpose — the conversation belongs to the app, not to a- workspace, so switching tabs must not reset the orb mid-sentence.- */}- <VoiceBubble- open={voiceOpen}- onClose={closeVoiceBubble}- onScreen={onScreen}- // The same jump the bell's list performs, from the bubble's update- // card: switch workspace if the pane lives in another one, then bring- // that pane into view.- onJumpToPane={(id, pane) => void jumpToPane(id, pane)}- promptTarget={- session.terminals.some(- (terminal) =>- terminal.name === promptTarget && terminal.accepts_prompts !== false,- )- ? promptTarget- : session.terminals.find(- (terminal) => terminal.accepts_prompts !== false,- )?.name ?? ""- }- />- {modeIntroFor === session.id && (- <CodingModeIntro- terminals={session.terminals.map((x) => x.name)}- project={session.project.name}- onDismiss={() => {- rememberModeIntro();- setModeIntroFor(null);- }}- />- )}- </div>- );- }+ if (state === null) return <div data-testid="agentic-ide-loading" className="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" />Loading projects…</div>;- /*- * ------------------------------------------------------------- still asking- *- * Before the first read lands, this view does not know whether a workspace is- * open — and "I do not know yet" must not be drawn as "there is none".- *- * It used to fall straight through to the wizard and merely add a line of- * "Checking this machine…" to it, which put the four-step ONBOARDING flow- * ("Which folder should the agents work in?") in front of a user whose eleven- * agents were running the whole time (maintainer report 2026-07-29). Being- * asked to start over is a far worse answer than being told to wait a moment,- * and the two states are indistinguishable to whoever is reading the screen.- *- * `loading` is a first-read flag: it is set once, cleared in `refresh`, and- * never raised again — so this never covers a workspace that is already up,- * and later refreshes redraw in place.- */- if (loading) {- return (- <div- className="flex h-full w-full items-center justify-center"- data-testid="agentic-ide-loading"- aria-busy="true"- >- <div className="flex items-center gap-2 text-sm text-muted-foreground">- <Loader2 className="h-4 w-4 animate-spin" />- Checking this machine…+ return <div className="relative flex h-full min-h-0 flex-col bg-background text-foreground" data-testid="igentic-ide">+ <header className="flex min-h-14 shrink-0 items-center gap-3 border-b border-border/70 px-4">+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2 text-sm font-medium">+ <span className="truncate">{activeProject?.name ?? "Projects"}</span>+ {session && <><span className="text-muted-foreground">/</span><span className="truncate text-muted-foreground">{session.name ?? session.project.name}</span></>}</div>+ {session && <div className="truncate text-[11px] text-muted-foreground" title={session.folder}>{session.folder}</div>}</div>- );- }-- // ---------------------------------------------------------------- launcher- return (- <div className="flex h-full min-h-0 flex-col" ref={shellRef}>- {renderBar(false)}- <div className="min-h-0 flex-1">- <WorkspaceLauncher- addingNew={addingNew}- busy={busy}- folder={folder}- onSelectFolder={setFolder}- onSelectRecent={replayRecent}- count={count}- maxTerminals={maxTerminals}- suggestedNames={suggested}- workspaceWidthPx={shellWidth}- onCount={chooseCount}- planned={planned}- onPlanned={setPlanned}- agents={agents}- accountsFor={accountsFor}- onAgentsChanged={() => void reloadAgents()}- /* Before the sweep lands `meta` is null, and this screen is not- reached in that state at all (see the `loading` branch above). The- optimistic default is still the right one: a machine is assumed- capable until it has said otherwise, never accused on no evidence. */- terminalAvailable={meta ? meta.terminal_available : true}- nothingInstalled={Boolean(meta) && installed.length === 0}- onOpenClis={() => setActiveSection("clis")}- offer={offer}- onResume={() => void resumeAll()}- onDismissOffer={() => void dismissOffer()}- view={view}- onView={setView}- onStart={() => void start()}- />- </div>- </div>- );-}--/*- * One-time explanation of what entering a workspace changes.- *- * Shown once per machine, not once per session: after the first time the user- * knows, and a modal that reappears every time is the thing people learn to- * dismiss without reading. Stored in localStorage rather than in config —- * "has this person seen a UI hint" is a property of this browser profile, not- * something worth a round-trip and a config write.- */-const MODE_INTRO_KEY = "jarvis.agenticIde.codingModeIntroSeen";--function hasSeenModeIntro(): boolean {- try {- return window.localStorage.getItem(MODE_INTRO_KEY) === "1";- } catch {- // Private mode / storage disabled: showing the hint again is a far smaller- // problem than crashing the view.- return false;- }-}--function rememberModeIntro(): void {- try {- window.localStorage.setItem(MODE_INTRO_KEY, "1");- } catch {- /* nothing to do — the hint will simply appear again */- }-}--/**- * What just changed, once, in four sentences.- *- * It used to be four bullets with bolded lead-ins — "**Talk to the agents by- * name.**", "**Jarvis writes the prompt.**" — each followed by a sentence- * explaining the lead-in. That is feature-list prose: it advertises a thing the- * reader has already chosen and opened, and the bolding makes the eye skip- * precisely the half that carries the information. The same four facts as four- * plain sentences take a third of the room and are actually read.- *- * It stays a dialog rather than becoming a toast because it appears exactly once- * per machine and describes a mode change the user did not ask for — which is- * the one thing on this screen worth interrupting for.- */-function CodingModeIntro({- terminals,- project,- onDismiss,-}: {- terminals: string[];- project: string;- onDismiss: () => void;-}) {- const first = terminals[0] ?? "T1";- const second = terminals[1] ?? terminals[0] ?? "T2";- return (- <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/70 p-6 backdrop-blur-sm">- <div className="w-full max-w-md rounded-lg bg-popover shadow-float p-5">- <h3 className="font-display text-base font-semibold">- Coding mode is on- </h3>- <p className="mt-1 text-xs text-muted-foreground">- While this workspace is open, Jarvis works inside {project}.- </p>-- <ul className="mt-4 space-y-2 text-sm leading-relaxed text-foreground/90">- <li>- Talk to the agents by name — “tell {first} to look at the wake word- code” goes straight into that terminal.- </li>- <li>- What you say is turned into a proper instruction, with the relevant- files of this repository attached as{" "}- <code className="font-mono text-xs">@</code> references.- </li>- <li>- “What is {second} up to?” is answered from what that terminal- actually printed.- </li>- <li>- Nothing is started in the background: work you give a terminal stays- with that terminal. Turn the mode off any time from the toolbar.- </li>- </ul>-- <div className="mt-5 flex justify-end">- <Button variant="primary" onClick={onDismiss}>- Got it- </Button>+ {session && <>+ <span className="hidden text-xs tabular-nums text-muted-foreground sm:inline">{session.terminals.length} / 8 agents</span>+ <div className="relative"><button type="button" aria-label="Add coding agent" title="Add coding agent" aria-expanded={agentMenu} disabled={busy || session.terminals.length >= 8 || installed.length === 0} onClick={() => setAgentMenu((value) => !value)} className="rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-40"><Plus className="h-4 w-4" /></button>+ {agentMenu && <div className="absolute right-0 top-full z-30 mt-1 min-w-40 rounded-lg border border-border bg-popover p-1 shadow-lg">{installed.map((agent) => <button key={agent.name} type="button" onClick={() => { setAgentMenu(false); addAgent(agent.name); }} className="block w-full rounded px-2 py-1.5 text-left text-xs hover:bg-accent">{agent.display_name}</button>)}</div>}</div>- </div>- </div>- );+ <div className="mx-1 h-4 w-px bg-border" />+ <button type="button" aria-label="Decrease terminal text size" onClick={() => saveFont(fontSize - 1)} className="rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground"><ZoomOut className="h-4 w-4" /></button>+ <span className="w-5 text-center text-xs tabular-nums text-muted-foreground">{fontSize}</span>+ <button type="button" aria-label="Increase terminal text size" onClick={() => saveFont(fontSize + 1)} className="rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground"><ZoomIn className="h-4 w-4" /></button>+ <button type="button" aria-label="Toggle terminal appearance" title="Toggle terminal light and dark appearance" onClick={() => saveAppearance((appearance ?? "dark") === "dark" ? "light" : "dark")} className="ml-1 rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground">{appearance === "light" ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}</button>+ <div className="relative"><button type="button" aria-label="Workspace actions" aria-expanded={workspaceMenu} onClick={() => setWorkspaceMenu((value) => !value)} className="rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground"><MoreHorizontal className="h-4 w-4" /></button>+ {workspaceMenu && <div className="absolute right-0 top-full z-30 mt-1 min-w-40 rounded-lg border border-border bg-popover p-1 shadow-lg">+ <button type="button" onClick={() => { setWorkspaceMenu(false); setRenameValue(session.name ?? session.project.name); setRenameOpen(true); }} className="block w-full rounded px-2 py-1.5 text-left text-xs hover:bg-accent">Rename workspace</button>+ <button type="button" onClick={stopWorkspace} className="block w-full rounded px-2 py-1.5 text-left text-xs text-destructive hover:bg-accent">Close workspace</button>+ </div>}+ </div>+ </>}+ <button type="button" aria-label="Jarvis Live" title="Jarvis Live" onClick={() => { const next = !voiceOpen; setVoiceOpen(next); storeVoiceBubbleOpen(next); }} className="rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground"><Mic className="h-4 w-4" /></button>+ </header>++ <main className="min-h-0 flex-1">+ {session ? <WorkspaceTerminalGrid key={session.id} session={session} onChanged={(next) => setState((current) => current?.session?.id === next.id ? { ...current, session: next } : current)}+ onAdd={() => setAgentMenu(true)} onClose={closeAgent} onSelect={setSelected} selected={selected} fontSize={fontSize} appearance={appearance} />+ : <div className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center">+ <FolderPlus className="h-8 w-8 text-muted-foreground/70" />+ <h1 className="text-lg font-medium">{projects.some((project) => !project.scratch && !project.archived) ? "Choose a workspace" : "Connect a project"}</h1>+ <p className="max-w-md text-sm text-muted-foreground">{projects.some((project) => !project.scratch && !project.archived) ? "Select a workspace from Projects, or create one with + beside its project." : "Connect a folder to bring its coding agents and Jarvis into one workspace."}</p>+ <button type="button" onClick={() => setProjectDialog(true)} className="mt-2 rounded-md border border-border px-3 py-1.5 text-sm hover:bg-accent">Connect folder</button>+ </div>}+ </main>++ <VoiceBubble open={voiceOpen} onClose={closeVoice} onScreen={onScreen} onJumpToPane={jumpToPane} promptTarget={selected} />++ {projectDialog && <div className="fixed inset-0 z-[80] flex items-center justify-center bg-background/75 p-4 backdrop-blur-sm" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) setProjectDialog(false); }}>+ <section data-ide-dialog tabIndex={-1} role="dialog" aria-modal="true" aria-label="Connect project" className="flex max-h-[85vh] w-full max-w-2xl flex-col overflow-hidden rounded-xl border border-border bg-card shadow-2xl">+ <div className="flex items-center justify-between border-b border-border px-5 py-3"><h2 className="text-sm font-semibold">Connect project folder</h2><button type="button" aria-label="Close" onClick={() => setProjectDialog(false)}><X className="h-4 w-4" /></button></div>+ <div className="min-h-0 flex-1 overflow-auto px-5 py-3"><FolderPicker selected={projectPath} onSelect={setProjectPath} /></div>+ <div className="border-t border-border px-5 py-3"><label className="block text-xs text-muted-foreground">Project name (optional)<input value={projectName} onChange={(event) => setProjectName(event.target.value)} placeholder={projectPath?.split(/[\\/]/).filter(Boolean).at(-1) ?? "Project name"} className="mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground" /></label>+ <div className="mt-3 flex justify-end gap-2"><button type="button" onClick={() => setProjectDialog(false)} className="rounded-md px-3 py-1.5 text-sm text-muted-foreground hover:bg-accent">Cancel</button><button type="button" disabled={busy || !projectPath} onClick={connect} className="rounded-md bg-primary px-3 py-1.5 text-sm text-primary-foreground disabled:opacity-50">Connect project</button></div>+ </div>+ </section>+ </div>}++ {workspaceProject && <div className="fixed inset-0 z-[80] flex items-center justify-center bg-background/75 p-4 backdrop-blur-sm" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) setWorkspaceProject(null); }}>+ <section data-ide-dialog tabIndex={-1} role="dialog" aria-modal="true" aria-label="New workspace" className="w-full max-w-md rounded-xl border border-border bg-card p-5 shadow-2xl">+ <div className="mb-4 flex items-center justify-between"><h2 className="text-base font-semibold">New workspace</h2><button type="button" aria-label="Close" onClick={() => setWorkspaceProject(null)}><X className="h-4 w-4" /></button></div>+ <p className="mb-4 truncate text-xs text-muted-foreground" title={workspaceProject.path}>{workspaceProject.name} · {workspaceProject.path}</p>+ <label className="block text-xs text-muted-foreground">Name (optional)<input value={workspaceName} onChange={(event) => setWorkspaceName(event.target.value)} placeholder="Workspace" className="mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground" /></label>+ <label className="mt-3 block text-xs text-muted-foreground">Sessions<select value={workspaceAgents.length} onChange={(event) => setWorkspaceAgents((old) => Array.from({ length: Number(event.target.value) }, (_, index) => old[index] ?? installed[0]?.name ?? ""))} className="mt-1 w-full rounded-md border border-input bg-background px-2 py-2 text-sm text-foreground">{[1, 2, 3, 4, 5, 6, 7, 8].map((count) => <option value={count} key={count}>{count}</option>)}</select></label>+ <div className="mt-3 max-h-48 space-y-2 overflow-auto">{workspaceAgents.map((agent, index) => <label key={index} className="flex items-center gap-3 text-xs text-muted-foreground"><span className="w-16 shrink-0">Agent {index + 1}</span><select value={agent} onChange={(event) => setWorkspaceAgents((old) => old.map((value, at) => at === index ? event.target.value : value))} className="min-w-0 flex-1 rounded-md border border-input bg-background px-2 py-2 text-sm text-foreground">{installed.map((choice) => <option value={choice.name} key={choice.name}>{choice.display_name}</option>)}</select></label>)}</div>+ {installed.length === 0 && <p className="mt-3 text-xs text-destructive">Install a coding agent from CLIs before creating a workspace.</p>}+ <div className="mt-5 flex justify-end gap-2"><button type="button" onClick={() => setWorkspaceProject(null)} className="rounded-md px-3 py-1.5 text-sm text-muted-foreground hover:bg-accent">Cancel</button><button type="button" disabled={busy || installed.length === 0} onClick={createWorkspace} className="rounded-md bg-primary px-3 py-1.5 text-sm text-primary-foreground disabled:opacity-50">Create workspace</button></div>+ </section>+ </div>}+ {renameOpen && <div className="fixed inset-0 z-[80] flex items-center justify-center bg-background/75 p-4 backdrop-blur-sm" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) setRenameOpen(false); }}>+ <form data-ide-dialog tabIndex={-1} role="dialog" aria-modal="true" aria-label="Rename workspace" onSubmit={(event) => { event.preventDefault(); saveWorkspaceName(); }} className="w-full max-w-sm rounded-xl border border-border bg-card p-5 shadow-2xl">+ <h2 className="mb-4 text-sm font-semibold">Rename workspace</h2>+ <label className="block text-xs text-muted-foreground">Workspace name<input autoFocus value={renameValue} onChange={(event) => setRenameValue(event.target.value)} className="mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground" /></label>+ <div className="mt-4 flex justify-end gap-2"><button type="button" onClick={() => setRenameOpen(false)} className="rounded-md px-3 py-1.5 text-sm text-muted-foreground hover:bg-accent">Cancel</button><button type="submit" disabled={busy || !renameValue.trim()} className="rounded-md bg-primary px-3 py-1.5 text-sm text-primary-foreground disabled:opacity-50">Save</button></div>+ </form>+ </div>}+ </div>;}diff --git a/tests/contract/test_workspace_orchestration.py b/tests/contract/test_workspace_orchestration.pynew file mode 100644index 0000000000..b72ed25a00--- /dev/null+++ b/tests/contract/test_workspace_orchestration.py@@ -0,0 +1,294 @@+"""Addressed coding delivery is independent of UI focus and voice provider."""++from __future__ import annotations++import asyncio+import time+from types import SimpleNamespace+from uuid import uuid4++import pytest++from jarvis.agentic_ide import library, resume_store+from jarvis.agentic_ide.folders import probe_project+from jarvis.agentic_ide.orchestration import WorkspaceOrchestrator+from jarvis.agentic_ide.session import Registry, Session, SessionError, Terminal+from jarvis.brain.tool_gateway import BrainSupervisorToolGateway+from jarvis.brain.workspace_tool import WorkspaceOrchestrationTool+from jarvis.core.protocols import ExecutionContext, SupervisorToolRequest+from jarvis.live.state import LiveLedger+from jarvis.live.tools import LiveTools+from tests.fakes.fake_pty_manager import FakePtyManager+++class Sessions:+ def __init__(self):+ self.calls = []+ self.fail = False+ self.refused = False++ async def run(self, args):+ self.calls.append(args)+ await asyncio.sleep(0)+ if self.refused:+ raise SessionError("The selected coding agent is busy; nothing was sent.")+ if self.fail:+ raise RuntimeError("transport interrupted after possible write")+ return {"delivery": "accepted", "submitted": True, "completed": False}+++def rig(tmp_path, monkeypatch):+ monkeypatch.setattr(library, "_root", lambda: tmp_path / "library")+ monkeypatch.setattr(resume_store, "_store_path", lambda: tmp_path / "snapshot.json")+ registry = Registry(pty_manager=FakePtyManager())+ for name in ("Personal Jarvis", "Other project"):+ path = tmp_path / name+ path.mkdir()+ project = library.ensure_project(path)+ term = Terminal(+ "t1",+ "Alex",+ "codex",+ "Codex",+ 0,+ status="live",+ activity="idle",+ activity_at=time.time(),+ )+ workspace = Session(+ id=uuid4().hex,+ folder=str(path),+ name=name,+ profile=probe_project(path),+ terminals=[term],+ created_at=1,+ project_id=project.id,+ )+ registry._sessions[workspace.id] = workspace+ registry._active = workspace.id+ ledger = LiveLedger(tmp_path / "receipts.db")+ sessions = Sessions()+ orchestrator = WorkspaceOrchestrator(registry, sessions, ledger)+ yield orchestrator, registry, sessions+ ledger.close()+++async def target(rig, **refs):+ result = await rig[0].run({"action": "resolve", **refs})+ assert result["status"] == "resolved", result+ return result["target"]+++async def test_named_background_workspace_wins_without_ui_switch(rig):+ before = rig[1].active_id+ resolved = await target(rig, workspace="Personal Jarvis")+ receipt = await rig[0].run(+ {+ "action": "send",+ **resolved,+ "prompt": "Fix the Linux installer",+ "request_id": uuid4().hex,+ }+ )+ assert receipt["target"] == {+ k: resolved[k] for k in ("project_id", "workspace_id", "terminal_id")+ }+ assert receipt["submitted"] and receipt["completed"] is False+ assert rig[2].calls[0]["workspace_id"] != before+ assert rig[1].active_id == before+++async def test_no_reference_uses_visible_workspace_without_focused_pane(rig):+ resolved = await target(rig)+ assert resolved["workspace_id"] == rig[1].active_id+ assert rig[1].session.surface_terminal == ""+++async def test_unique_named_agent_can_be_addressed_in_background_workspace(rig):+ owner = rig[1].sessions[0]+ owner.terminals[0].name = "Installer expert"+ resolved = await target(rig, agent="Installer expert")+ assert resolved["workspace_id"] == owner.id+ assert rig[1].active_id != owner.id+++async def test_duplicate_workspace_names_require_clarification(rig):+ for workspace in rig[1].sessions:+ workspace.name = "Installer"+ result = await rig[0].run({"action": "resolve", "workspace": "Installer"})+ assert result["status"] == "needs_clarification"+ assert len(result["candidates"]) == 2+ assert not rig[2].calls+ resolved = await target(rig, workspace="Installer", project="Personal Jarvis")+ assert resolved["project_id"] == rig[1].sessions[0].project_id+++async def test_duplicate_agent_names_fail_closed_but_idle_choice_is_stable(rig):+ owner = rig[1].session+ owner.terminals.append(Terminal("t2", "Alex", "codex", "Codex", 1, status="live"))+ result = await rig[0].run({"action": "resolve", "agent": "Alex"})+ assert result["status"] == "needs_clarification"+ resolved = await target(rig)+ assert resolved["terminal_id"] == "pane:" + owner.terminals[0].history_id+++async def test_rename_and_workspace_switch_cannot_retarget_send(rig):+ resolved = await target(rig, project="Personal Jarvis")+ owner = rig[1].get(resolved["workspace_id"])+ owner.name = "Renamed workspace"+ owner.terminals[0].name = "Renamed agent"+ result = await rig[0].run(+ {"action": "send", **resolved, "request_id": uuid4().hex, "prompt": "Task"}+ )+ assert result["status"] == "accepted"+ assert rig[2].calls[0]["terminal_id"] == resolved["terminal_id"]+++async def test_closed_or_cross_project_target_cannot_fall_back(rig):+ resolved = await target(rig)+ del rig[1]._sessions[resolved["workspace_id"]]+ result = await rig[0].run(+ {"action": "send", **resolved, "request_id": uuid4().hex, "prompt": "Task"}+ )+ assert result["status"] == "stale_target"+ assert not rig[2].calls+++async def test_concurrent_and_reopened_receipts_never_duplicate_delivery(rig):+ resolved = await target(rig)+ args = {"action": "send", **resolved, "request_id": uuid4().hex, "prompt": "Task"}+ first, second = await asyncio.gather(rig[0].run(args), rig[0].run(args))+ assert len(rig[2].calls) == 1+ assert "accepted" in {first.get("status"), second.get("status")}+ reopened = WorkspaceOrchestrator(rig[1], rig[2], rig[0].ledger)+ assert (await reopened.run(args))["status"] == "accepted"+ collision = await reopened.run({**args, "prompt": "Different task"})+ assert collision["success"] is False+ assert len(rig[2].calls) == 1+++async def test_uncertain_delivery_stays_uncertain_and_is_not_replayed(rig):+ resolved = await target(rig)+ rig[2].fail = True+ args = {"action": "send", **resolved, "request_id": uuid4().hex, "prompt": "Task"}+ assert (await rig[0].run(args))["status"] == "uncertain"+ assert (await rig[0].run(args))["status"] == "uncertain"+ assert len(rig[2].calls) == 1++[email protected]("available", [True, False])+async def test_capability_probe_is_provider_and_os_independent(rig, monkeypatch, available):+ from jarvis.workspace import agents++ monkeypatch.setattr(agents, "pty_available", lambda: available)+ graph = await rig[0].run({"action": "inspect"})+ assert graph["available"] is available+ assert len(graph["projects"]) == 2+++class Executor:+ def __init__(self):+ self.calls = []++ async def execute(self, tool, args, **kwargs):+ self.calls.append((tool.name, args))+ ctx = ExecutionContext(kwargs["trace_id"], kwargs["user_utterance"], {}, None)+ return await tool.execute(args, ctx)+++async def test_live_roundtrip_uses_gateway_executor_and_durable_addressed_receipt(rig, tmp_path):+ executor = Executor()+ tool = WorkspaceOrchestrationTool(rig[0])+ gateway = BrainSupervisorToolGateway(+ SimpleNamespace(_tools={"agentic-ide-prompt": tool}, _tool_executor=executor),+ workspace_tool=tool,+ )+ catalog = {row.name for row in gateway.voice_catalog()}+ assert tool.name in catalog and "agentic-ide-prompt" not in catalog+ # The controller is not put in a worker's ordinary catalog.+ assert tool.name not in {row.name for row in gateway.catalog()}+ ledger = LiveLedger(tmp_path / "live.db")+ try:+ live = LiveTools(gateway, ledger, "voice", language="en", backend_model="")+ live.user_text = "Fix the Linux installer in the Personal Jarvis workspace"+ resolved = await live.execute(+ "resolve",+ tool.name,+ {+ "action": "resolve",+ "workspace": "Personal Jarvis",+ },+ 0,+ )+ assert resolved["success"], resolved+ args = {+ "action": "send",+ **resolved["output"]["target"],+ "request_id": resolved["output"]["request_id"],+ "prompt": live.user_text,+ }+ # The resolved display labels are UI metadata, not accepted send fields.+ args = {k: v for k, v in args.items() if k in tool.schema["properties"]}+ receipt = await live.execute("send", tool.name, args, 0)+ assert receipt["success"] and receipt["output"]["status"] == "accepted"+ assert (await live.execute("send", tool.name, args, 0)) == receipt+ assert len(rig[2].calls) == 1+ assert len(executor.calls) == 2+ denied = await gateway.execute(+ tool.name, args, SupervisorToolRequest(uuid4(), "mission", "Task")+ )+ assert not denied.success+ finally:+ ledger.close()+++def test_send_requires_application_permission_and_reads_remain_safe(rig):+ tool = WorkspaceOrchestrationTool(rig[0])+ assert tool.risk_tier_for_args({"action": "send"}) == "ask"+ for action in ("inspect", "resolve", "context"):+ assert tool.risk_tier_for_args({"action": action}) == "safe"+++async def test_prewrite_refusal_is_recorded_without_claiming_uncertainty(rig):+ resolved = await target(rig)+ rig[2].refused = True+ args = {"action": "send", **resolved, "request_id": uuid4().hex, "prompt": "Task"}+ first = await rig[0].run(args)+ assert first["status"] == "not_accepted"+ assert await rig[0].run(args) == first+ assert len(rig[2].calls) == 1+++async def test_later_same_task_has_an_app_minted_distinct_request(rig):+ for _ in range(2):+ resolved = await rig[0].run({"action": "resolve"})+ await rig[0].run(+ {+ "action": "send",+ **resolved["target"],+ "request_id": resolved["request_id"],+ "prompt": "Run tests",+ }+ )+ assert len(rig[2].calls) == 2+++def test_confirmation_identifies_target_and_task(rig):+ tool = WorkspaceOrchestrationTool(rig[0])+ impact = tool.describe_args(+ {+ "action": "send",+ "project_id": "project-1",+ "workspace_id": "workspace-2",+ "terminal_id": "pane:3",+ "prompt": "Fix Linux installer",+ }+ )+ assert impact == {+ "level": "modify",+ "project": "project-1",+ "workspace": "workspace-2",+ "agent": "pane:3",+ "task": "Fix Linux installer",+ }diff --git a/tests/unit/agentic_ide/test_cold_start_gate.py b/tests/unit/agentic_ide/test_cold_start_gate.pyindex d1e1c00621..24063a8454 100644--- a/tests/unit/agentic_ide/test_cold_start_gate.py+++ b/tests/unit/agentic_ide/test_cold_start_gate.py@@ -88,12 +88,12 @@ async def test_a_full_workspace_starts_in_waves(pool.hold_s = 0.05registry = ide.Registry(pty_manager=pool)session = await registry.start(- str(tmp_path), [{"agent": "claude"} for _ in range(12)]+ str(tmp_path), [{"agent": "claude"} for _ in range(ide.MAX_TERMINALS)])await _attach_all(registry, session)- assert len(pool.spawns) == 12, "every pane still gets its agent"+ assert len(pool.spawns) == ide.MAX_TERMINALS, "every pane still gets its agent"assert pool.peak <= 3, f"{pool.peak} agents were starting at once"@@ -115,9 +115,7 @@ async def test_codex_shared_store_starts_are_serial_until_the_input_line()monkeypatch.setattr(ide, "has_conversation", lambda *_args, **_kwargs: True)for index, term in enumerate(session.terminals):- term.resume = ide.ResumeHandle(- kind="codex_rollout", id=f"resume-{index}", captured_at=0.0- )+ term.resume = ide.ResumeHandle(kind="codex_rollout", id=f"resume-{index}", captured_at=0.0)mounting = asyncio.create_task(_attach_all(registry, session))for _ in range(50):@@ -156,9 +154,7 @@ async def test_rejoining_a_running_agent_never_waits_for_a_starting_one(monkeypatch.setattr(ide, "COLD_START_SETTLE_S", 0.0)monkeypatch.setattr(ide, "COLD_START_HOLD_MAX_S", 0.0)registry = ide.Registry(pty_manager=pool)- session = await registry.start(- str(tmp_path), [{"agent": "claude"}, {"agent": "claude"}]- )+ session = await registry.start(str(tmp_path), [{"agent": "claude"}, {"agent": "claude"}])first, second = session.terminalsasync def sink(_text: str) -> None:@@ -194,9 +190,7 @@ async def test_a_failed_start_hands_its_slot_back_at_once(monkeypatch.setattr(ide, "COLD_START_SETTLE_S", 30.0)pool.spawn_error = "no pseudo-terminal on this host"registry = ide.Registry(pty_manager=pool)- session = await registry.start(- str(tmp_path), [{"agent": "claude"}, {"agent": "claude"}]- )+ session = await registry.start(str(tmp_path), [{"agent": "claude"}, {"agent": "claude"}])async def sink(_text: str) -> None:return Nonediff --git a/tests/unit/agentic_ide/test_many_terminals.py b/tests/unit/agentic_ide/test_many_terminals.pyindex dea659d1b1..45a863ca5c 100644--- a/tests/unit/agentic_ide/test_many_terminals.py+++ b/tests/unit/agentic_ide/test_many_terminals.py@@ -1,11 +1,4 @@-"""What holds — and what does not — once a workspace has far more than 12 panes.--The pane cap was 12 and is now 100 per workspace, while workspace count itself-is unrestricted. Twelve panes was small enough that several things could get-away with being O(n) in disguise or quietly bounded; a hundred is not. These-tests pin the parts that must scale and name the ones that are deliberately-bounded, so raising the pane cap again is a measurement rather than a hope.-"""+"""Workspace capacity, independent sessions and bounded persistent metadata."""from __future__ import annotations@@ -40,7 +33,7 @@ def test_the_call_sign_pool_covers_one_full_workspace() -> None:assert len(set(pool)) == ide.MAX_TERMINALS, "a repeated call-sign is ambiguous"-async def test_opening_a_hundred_panes_gives_each_a_distinct_name(+async def test_opening_a_full_workspace_gives_each_a_distinct_name(registry: ide.Registry, tmp_path: Path) -> None:session = await registry.start(@@ -53,7 +46,7 @@ async def test_opening_a_hundred_panes_gives_each_a_distinct_name(assert "" not in keys-async def test_a_hundred_panes_can_each_be_found_by_name(+async def test_a_full_workspace_can_each_be_found_by_name(registry: ide.Registry, tmp_path: Path) -> None:"""Voice reaches a pane by its call-sign; that must not degrade with size."""@@ -66,7 +59,7 @@ async def test_a_hundred_panes_can_each_be_found_by_name(# --------------------------------------------------------------------- layout-async def test_the_grid_stays_gapless_at_a_hundred_panes(+async def test_the_grid_stays_gapless_at_a_full_workspace(registry: ide.Registry, tmp_path: Path) -> None:"""A hole in the coordinates renders as a blank stripe in the UI."""@@ -85,42 +78,38 @@ async def test_closing_the_middle_of_a_large_workspace_repacks_it(registry: ide.Registry, tmp_path: Path) -> None:session = await registry.start(- str(tmp_path), [{"agent": "claude"} for _ in range(40)]+ str(tmp_path), [{"agent": "claude"} for _ in range(ide.MAX_TERMINALS)])- victim = session.terminals[17].name+ victim = session.terminals[ide.MAX_TERMINALS // 2].nameawait registry.close_terminal(victim)- assert len(session.terminals) == 39+ assert len(session.terminals) == ide.MAX_TERMINALS - 1columns = sorted({t.column for t in session.terminals})assert columns == list(range(len(columns)))- assert [t.index for t in session.terminals] == list(range(39))+ assert [t.index for t in session.terminals] == list(range(ide.MAX_TERMINALS - 1))async def test_the_cap_is_enforced_rather_than_exceeded(registry: ide.Registry, tmp_path: Path) -> None:"""Whatever the cap is, it has to be the real ceiling."""- await registry.start(- str(tmp_path), [{"agent": "claude"} for _ in range(ide.MAX_TERMINALS)]- )+ await registry.start(str(tmp_path), [{"agent": "claude"} for _ in range(ide.MAX_TERMINALS)])with pytest.raises(ide.SessionError, match="maximum"):await registry.add_terminal()-async def test_a_batch_past_the_cap_reports_being_capped(+async def test_a_batch_past_the_cap_is_rejected_without_partial_creation(registry: ide.Registry, tmp_path: Path) -> None:- """Asking for more than fits is a partial success the caller must surface."""- await registry.start(- str(tmp_path), [{"agent": "claude"} for _ in range(ide.MAX_TERMINALS - 3)]- )- created, capped = await registry.add_terminals(10)- assert len(created) == 3- assert capped is True+ """An oversized batch must not silently create a smaller agent group."""+ await registry.start(str(tmp_path), [{"agent": "claude"} for _ in range(ide.MAX_TERMINALS - 3)])+ with pytest.raises(ide.SessionError, match="at most"):+ await registry.add_terminals(10)+ assert len(registry.session.terminals) == ide.MAX_TERMINALS - 3# ------------------------------------------------------------------- resuming-async def test_a_hundred_panes_survive_the_snapshot_round_trip(+async def test_a_full_workspace_survive_the_snapshot_round_trip(registry: ide.Registry, tmp_path: Path) -> None:"""The restore point has to carry a full workspace, not a readable prefix."""@@ -132,13 +121,11 @@ async def test_a_hundred_panes_survive_the_snapshot_round_trip(loaded = resume_store.load()assert loaded is not Noneassert loaded.terminal_count == ide.MAX_TERMINALS- stored = [- (t.name, t.column, t.slot) for t in loaded.workspaces[0].terminals- ]+ stored = [(t.name, t.column, t.slot) for t in loaded.workspaces[0].terminals]assert stored == expected-async def test_restoring_a_hundred_panes_keeps_every_position(+async def test_restoring_a_full_workspace_keeps_every_position(registry: ide.Registry, tmp_path: Path) -> None:panes = [@@ -146,11 +133,9 @@ async def test_restoring_a_hundred_panes_keeps_every_position(key=f"t{i}",name=f"T{i}",agent="claude",- column=i // 5,- slot=i % 5,- resume=ResumeHandle(- kind="claude_session", id=f"conv-{i}", captured_at=1.0- ),+ column=i % 4,+ slot=i // 4,+ resume=ResumeHandle(kind="claude_session", id=f"conv-{i}", captured_at=1.0),)for i in range(ide.MAX_TERMINALS)]@@ -166,10 +151,10 @@ async def test_restoring_a_hundred_panes_keeps_every_position(result = await registry.restore(snapshot)session = result.sessions[0]assert len(session.terminals) == ide.MAX_TERMINALS- # Every pane sits exactly where it sat — twenty columns of five — read+ # Every pane sits exactly where it sat — four columns of two — read# back across the bands rather than down the columns, because a grid# stands on its rows once it is restored (`layout_tree.rows_outermost`).- across = ide.MAX_TERMINALS // 5+ across = 4assert [(t.column, t.slot) for t in session.terminals] == [(i % across, i // across) for i in range(ide.MAX_TERMINALS)]@@ -199,28 +184,24 @@ async def test_a_full_house_across_every_workspace_round_trips(folder = tmp_path / f"repo{index}"folder.mkdir()folders.append(folder)- await registry.start(- str(folder), [{"agent": "claude"} for _ in range(20)]- )+ await registry.start(str(folder), [{"agent": "claude"} for _ in range(ide.MAX_TERMINALS)])loaded = resume_store.load()assert loaded is not Noneassert len(loaded.workspaces) == workspace_count- assert loaded.terminal_count == 20 * workspace_count+ assert loaded.terminal_count == ide.MAX_TERMINALS * workspace_countfor workspace in loaded.workspaces:names = [t.name for t in workspace.terminals]- assert names == default_names(20), "each workspace numbers its own panes"+ assert names == default_names(ide.MAX_TERMINALS), "each workspace numbers its own panes"async def test_the_snapshot_of_a_full_house_stays_a_sane_size(registry: ide.Registry, tmp_path: Path) -> None:"""It is read on the first screen of the IDE, so it must stay small."""- await registry.start(- str(tmp_path), [{"agent": "claude"} for _ in range(ide.MAX_TERMINALS)]- )+ await registry.start(str(tmp_path), [{"agent": "claude"} for _ in range(ide.MAX_TERMINALS)])raw = resume_store._store_path().read_text(encoding="utf-8")- # A hundred panes of metadata, not a transcript: comfortably under 100 KB.+ # Eight panes of metadata, not a transcript: comfortably under 100 KB.assert len(raw) < 100_000# And still valid JSON rather than something truncated.assert json.loads(raw)["workspaces"][0]["terminals"]diff --git a/tests/unit/agentic_ide/test_pane_batch.py b/tests/unit/agentic_ide/test_pane_batch.pyindex c931fc6c3e..648b19df30 100644--- a/tests/unit/agentic_ide/test_pane_batch.py+++ b/tests/unit/agentic_ide/test_pane_batch.py@@ -6,6 +6,7 @@ how many panes appear, which agent they run, and whether the caller is told thetruth when the pane cap within a workspace cuts the request short. A batch thatsilently opened three of five would report success for work that did not happen."""+from __future__ import annotationsfrom pathlib import Path@@ -23,7 +24,9 @@ from tests.fakes.fake_pty_manager import FakePtyManager@pytest.fixture(autouse=True)-def _isolated_recents(tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch) -> None:+def _isolated_recents(+ tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch+) -> None:"""Keep the recents file out of the developer's real data directory.Opening a workspace records it as "most recently used", and that file lives@@ -46,9 +49,7 @@ def registry(monkeypatch: pytest.MonkeyPatch) -> Registry:async def _open(registry: Registry, folder: Path, count: int, agent: str = "claude"):- return await registry.start(- str(folder), [{"agent": agent} for _ in range(count)]- )+ return await registry.start(str(folder), [{"agent": agent} for _ in range(count)])def _names(registry: Registry) -> list[str]:@@ -56,9 +57,7 @@ def _names(registry: Registry) -> list[str]:return [t.name for t in registry.session.terminals]-async def test_a_batch_opens_every_requested_pane(- registry: Registry, tmp_path: Path-) -> None:+async def test_a_batch_opens_every_requested_pane(registry: Registry, tmp_path: Path) -> None:await _open(registry, tmp_path, 2)created, capped = await registry.add_terminals(3)assert len(created) == 3@@ -69,19 +68,14 @@ async def test_a_batch_opens_every_requested_pane(assert len(set(_names(registry))) == 5-async def test_the_cap_truncates_and_says_so(+async def test_the_cap_rejects_the_batch_without_creating_any_pane(registry: Registry, tmp_path: Path) -> None:- """Nine panes open, five requested: three appear and ``capped`` is True.-- This is the maintainer's live case (nine panes on screen). Silent truncation- is the failure mode — the flag is what lets the spoken reply be honest.- """+ """The eight-session workspace limit is checked before creating the batch."""await _open(registry, tmp_path, MAX_TERMINALS - 3)- created, capped = await registry.add_terminals(5)- assert len(created) == 3- assert capped is True- assert len(_names(registry)) == MAX_TERMINALS+ with pytest.raises(SessionError, match="at most"):+ await registry.add_terminals(5)+ assert len(_names(registry)) == MAX_TERMINALS - 3async def test_a_full_workspace_refuses_instead_of_reporting_nothing(@@ -89,14 +83,12 @@ async def test_a_full_workspace_refuses_instead_of_reporting_nothing() -> None:"""With no room at all the caller gets an error it can read out loud."""await _open(registry, tmp_path, MAX_TERMINALS)- with pytest.raises(SessionError, match="maximum"):+ with pytest.raises(SessionError, match="at most"):await registry.add_terminals(2)-async def test_the_agent_is_inherited_unless_named(- registry: Registry, tmp_path: Path-) -> None:- """"Two more" means two more OF THESE; naming an agent overrides that."""+async def test_the_agent_is_inherited_unless_named(registry: Registry, tmp_path: Path) -> None:+ """ "Two more" means two more OF THESE; naming an agent overrides that."""await _open(registry, tmp_path, 1, agent="codex")inherited, _ = await registry.add_terminals(2)assert [t.agent for t in inherited] == ["codex", "codex"]diff --git a/tests/unit/agentic_ide/test_panes.py b/tests/unit/agentic_ide/test_panes.pyindex b3bbd1e53c..0daf75e69e 100644--- a/tests/unit/agentic_ide/test_panes.py+++ b/tests/unit/agentic_ide/test_panes.py@@ -6,6 +6,7 @@ a pane to the anchor's OWN column and leaves every other column at full height.These tests pin that arithmetic, because an off-by-one renders as a blank stripein the grid, or squashes panes that should not have moved."""+from __future__ import annotationsfrom pathlib import Path@@ -29,9 +30,7 @@ def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> Regisasync def _open(registry: Registry, folder: Path, count: int = 2):- return await registry.start(- str(folder), [{"agent": "claude"} for _ in range(count)]- )+ return await registry.start(str(folder), [{"agent": "claude"} for _ in range(count)])async def _open_in_a_row(registry: Registry, folder: Path, count: int):@@ -69,24 +68,15 @@ async def _noop_exit(_code: int) -> None:# --------------------------------------------------------------- initial rows-async def test_a_fresh_workspace_fills_columns_two_deep(+async def test_a_fresh_workspace_uses_row_major_terminal_order(registry: Registry, tmp_path: Path) -> None:- """The wizard's panes stack two to a column before a new one is opened.-- A row of columns shares the window's width between every pane, so six- terminals left each about 410 px on the maintainer's display — under the- width their agent needs, so each pane was clipped at its tile edge and the- six read as overlapping (2026-08-11). Two deep halves the columns and so- doubles each pane's width. The odd third pane opens a column of its own.- """+ """Three sessions share one row in the project workspace grid."""await _open(registry, tmp_path, 3)- assert _layout(registry) == [("T1", 0, 0), ("T2", 0, 1), ("T3", 1, 0)]+ assert _layout(registry) == [("T1", 0, 0), ("T2", 1, 0), ("T3", 2, 0)]-async def test_a_single_terminal_still_opens_alone(- registry: Registry, tmp_path: Path-) -> None:+async def test_a_single_terminal_still_opens_alone(registry: Registry, tmp_path: Path) -> None:"""Nothing is stacked that has nothing to stack with."""await _open(registry, tmp_path, 1)assert _layout(registry) == [("T1", 0, 0)]@@ -103,18 +93,14 @@ async def test_split_right_opens_a_column_next_to_the_anchor(assert _layout(registry) == [("T1", 0, 0), (term.name, 1, 0), ("T2", 2, 0)]-async def test_split_right_inherits_the_anchor_agent(- registry: Registry, tmp_path: Path-) -> None:+async def test_split_right_inherits_the_anchor_agent(registry: Registry, tmp_path: Path) -> None:"""Splitting a Codex pane means "another Codex", not the default agent."""await registry.start(str(tmp_path), [{"agent": "codex", "name": "Cody"}])term = await registry.add_terminal(anchor="Cody", direction="right")assert term.agent == "codex"-async def test_an_explicit_agent_wins_over_the_anchor(- registry: Registry, tmp_path: Path-) -> None:+async def test_an_explicit_agent_wins_over_the_anchor(registry: Registry, tmp_path: Path) -> None:await _open(registry, tmp_path, 1)term = await registry.add_terminal(anchor="T1", direction="right", agent="codex")assert term.agent == "codex"@@ -146,9 +132,7 @@ async def test_split_down_pushes_the_existing_stack_down(# --------------------------------------------------------------------- naming-async def test_new_panes_take_the_next_free_call_sign(- registry: Registry, tmp_path: Path-) -> None:+async def test_new_panes_take_the_next_free_call_sign(registry: Registry, tmp_path: Path) -> None:await _open(registry, tmp_path, 2) # T1, T2term = await registry.add_terminal(direction="right")assert term.name == "T3"@@ -163,9 +147,7 @@ async def test_a_taken_position_moves_to_the_next_free_number(assert term.name == "T2"-async def test_an_explicit_custom_name_is_deduplicated(- registry: Registry, tmp_path: Path-) -> None:+async def test_an_explicit_custom_name_is_deduplicated(registry: Registry, tmp_path: Path) -> None:"""A name the user chose keeps the familiar numeric suffix."""await _open(registry, tmp_path, 1)await registry.add_terminal(name="Mika", direction="right")@@ -302,9 +284,7 @@ async def test_a_batch_reports_unknown_names_but_closes_valid_ones(assert [term.name for term in registry.session.terminals] == ["T2"]-async def test_a_closed_pane_refuses_further_prompts(- registry: Registry, tmp_path: Path-) -> None:+async def test_a_closed_pane_refuses_further_prompts(registry: Registry, tmp_path: Path) -> None:await _open(registry, tmp_path, 2)await registry.attach("T1", 80, 24, _noop, _noop_exit)await registry.close_terminal("T1")@@ -312,9 +292,7 @@ async def test_a_closed_pane_refuses_further_prompts(await registry.send_prompt("T1", "still there?")-async def test_a_reopened_call_sign_is_a_fresh_pane(- registry: Registry, tmp_path: Path-) -> None:+async def test_a_reopened_call_sign_is_a_fresh_pane(registry: Registry, tmp_path: Path) -> None:"""Closing T1 and splitting again must not resurrect the old transcript."""await _open(registry, tmp_path, 1)await registry.attach("T1", 80, 24, _noop, _noop_exit)diff --git a/tests/unit/agentic_ide/test_quick_agent_catalog.py b/tests/unit/agentic_ide/test_quick_agent_catalog.pynew file mode 100644index 0000000000..d470204b99--- /dev/null+++ b/tests/unit/agentic_ide/test_quick_agent_catalog.py@@ -0,0 +1,63 @@+"""Workspace launch choices never wait for CLI version or model subprocesses."""++from __future__ import annotations++import threading++import pytest++from jarvis.ui.web import agentic_ide_routes as routes+from jarvis.workspace import agents, launch_picks++[email protected]("pty_available", [False, True])+async def test_quick_catalog_resolves_off_loop_without_expensive_probes(+ monkeypatch: pytest.MonkeyPatch,+ pty_available: bool,+) -> None:+ specs = [+ agents.WorkspaceAgent(+ name="example",+ display_name="Example Agent",+ description="A custom coding agent",+ custom=True,+ logo_url="/logo.svg",+ accepts_typed_prompts=False,+ ),+ agents.WorkspaceAgent(name="missing", display_name="Missing Agent"),+ ]+ by_name = {spec.name: spec for spec in specs}+ monkeypatch.setattr(agents, "coding_agents", lambda: specs)+ monkeypatch.setattr(agents, "get_agent", by_name.get)+ monkeypatch.setattr(agents, "pty_available", lambda: pty_available)++ async def forbidden_probe():+ pytest.fail("The quick catalog must not execute CLI version/model probes")++ monkeypatch.setattr(agents, "detect_agents", forbidden_probe)+ monkeypatch.setattr(launch_picks, "live_models", forbidden_probe)+ event_loop_thread = threading.get_ident()+ resolved = []++ def resolve_agent(name):+ assert threading.get_ident() != event_loop_thread+ resolved.append(name)+ return ("example",) if name == "example" else None++ monkeypatch.setattr(routes, "agent_argv", resolve_agent)+ result = await routes.get_agents(quick=True)+ assert resolved == ["example", "missing"]+ assert result.terminal_available is pty_available+ assert result.max_terminals == 8+ assert len(result.suggested_names) == 8+ example, missing = result.agents+ assert example.installed is True+ assert missing.installed is False+ assert example.version is None+ assert example.install_command is None+ assert example.kind == "cli"+ assert example.description == "A custom coding agent"+ assert example.custom is True+ assert example.logo_url == "/logo.svg"+ assert example.accepts_prompts is False+ assert missing.accepts_prompts is Truediff --git a/tests/unit/agentic_ide/test_resume_session.py b/tests/unit/agentic_ide/test_resume_session.pyindex da9cd4f53c..dbf38fa020 100644--- a/tests/unit/agentic_ide/test_resume_session.py+++ b/tests/unit/agentic_ide/test_resume_session.py@@ -350,9 +350,7 @@ def _workspace(folder: Path) -> resume_store.SnapshotWorkspace:resume=ResumeHandle(kind="claude_session", id="t4-conv", captured_at=1.0),prompts_sent=2,),- resume_store.SnapshotTerminal(- key="t1", name="T1", agent="claude", column=0, slot=0- ),+ resume_store.SnapshotTerminal(key="t1", name="T1", agent="claude", column=0, slot=0),],)@@ -604,9 +602,7 @@ async def test_closing_workspaces_one_by_one_keeps_all_of_them_on_offer(folder = tmp_path / f"repo{index}"folder.mkdir()folders.append(folder)- await registry.start(- str(folder), [{"agent": "claude", "name": f"Pane{index}"}]- )+ await registry.start(str(folder), [{"agent": "claude", "name": f"Pane{index}"}])# One at a time, the way a person closes tabs.while await registry.end():@@ -622,8 +618,8 @@ async def test_a_new_workspace_does_not_erase_the_folders_you_closed() -> None:"""The reported loss, in miniature.- Work twelve panes in one folder, close them, then open a single pane- somewhere to check one thing — and the twelve used to be gone for good,+ Work eight panes in one folder, close them, then open a single pane+ somewhere to check one thing — and the eight used to be gone for good,because a save replaced the file outright. A save UPDATES: the folder that isopen now overwrites its own record, every other remembered folder is leftalone.@@ -631,9 +627,7 @@ async def test_a_new_workspace_does_not_erase_the_folders_you_closed(big, quick = tmp_path / "big", tmp_path / "quick"big.mkdir()quick.mkdir()- await registry.start(- str(big), [{"agent": "claude"} for _ in range(12)]- )+ await registry.start(str(big), [{"agent": "claude"} for _ in range(ide.MAX_TERMINALS)])await registry.end()await registry.start(str(quick), [{"agent": "claude", "name": "Solo"}])@@ -641,13 +635,13 @@ async def test_a_new_workspace_does_not_erase_the_folders_you_closed(saved = resume_store.load()assert saved is not Nonefolders = {w.folder: len(w.terminals) for w in saved.workspaces}- assert folders == {str(quick): 1, str(big): 12}+ assert folders == {str(quick): 1, str(big): ide.MAX_TERMINALS}-async def test_reopening_the_same_folder_replaces_its_own_record(+async def test_reopening_the_same_folder_preserves_independent_workspace_records(registry: ide.Registry, tmp_path: Path) -> None:- """The newest arrangement of a folder is the truth about that folder."""+ """Independent workspace groups in one project each keep their restore point."""await registry.start(str(tmp_path), [{"agent": "claude"} for _ in range(5)])await registry.end()@@ -655,7 +649,7 @@ async def test_reopening_the_same_folder_replaces_its_own_record(saved = resume_store.load()assert saved is not None- assert [len(w.terminals) for w in saved.workspaces] == [1]+ assert [len(w.terminals) for w in saved.workspaces] == [1, 5]async def test_the_closed_workspace_history_stays_bounded(diff --git a/tests/unit/agentic_ide/test_spawn_intent.py b/tests/unit/agentic_ide/test_spawn_intent.pyindex f0bbadcd5b..b015df25b8 100644--- a/tests/unit/agentic_ide/test_spawn_intent.py+++ b/tests/unit/agentic_ide/test_spawn_intent.py@@ -84,15 +84,11 @@ def test_a_number_above_the_cap_is_clamped_not_refused() -> None:assert found.count == MAX_TERMINALS-def test_an_ordinary_large_count_is_taken_at_face_value() -> None:- """ "as many as you want" is the point — 20 panes must not be trimmed to 12.-- Guards the 2026-07-26 directive: the old cap of 12 silently rewrote what the- user asked for, which is worse than refusing it.- """+def test_a_large_requested_count_obeys_the_workspace_capacity() -> None:+ """Spoken counts share the same eight-session ceiling as the launch picker."""found = intent.detect_spawn("Spawne 20 Terminals") # i18n-allow: spoken input under testassert found is not None- assert found.count == 20+ assert found.count == MAX_TERMINALS@pytest.mark.parametrize(@@ -207,7 +203,7 @@ def test_recombined_completed_turn_does_not_hide_a_later_spawn_clause() -> None:def test_question_inside_the_spawn_clause_still_never_opens_panes() -> None:- utterance = "Was passiert, wenn ich 5 Claude-Code-Terminals spawne?" # i18n-allow: spoken input under test+ utterance = "Was passiert, wenn ich 5 Claude-Code-Terminals spawne?" # i18n-allow: speechassert intent.detect_spawn(utterance, names=NAMES) is Noneassert intent.owns_turn(utterance, names=NAMES) is False@@ -436,7 +432,7 @@ def test_a_briefed_position_never_becomes_a_fleet_size() -> None:"there is no terminal two" — rather than opening panes the user neverasked for."""- utterance = "prompt wird du terminal tft zwei, dass es ein deep dive machen soll" # i18n-allow: production transcript under test+ utterance = "prompt wird du terminal tft zwei, dass es ein deep dive machen soll" # i18n-allowassert intent.detect_spawn(utterance, names=["T1"]) is Noneassert (diff --git a/tests/unit/agentic_ide/test_spawn_misheard_agent_name.py b/tests/unit/agentic_ide/test_spawn_misheard_agent_name.pyindex a61ccf457f..524ac2630e 100644--- a/tests/unit/agentic_ide/test_spawn_misheard_agent_name.py+++ b/tests/unit/agentic_ide/test_spawn_misheard_agent_name.py@@ -15,6 +15,7 @@ Two properties are pinned here, and they pull against each other on purpose:its own — otherwise the fix would turn every sentence about the cloud into arequest for a Claude pane."""+from __future__ import annotationsimport pytest@@ -67,9 +68,7 @@ def test_an_everyday_word_counts_only_with_the_products_second_word(def test_live_hyphenated_cloth_code_transcript_names_claude() -> None:"""The exact 2026-08-09 pipeline transcript must keep its count and CLI."""- assert _groups(- "Geil, kannst du bitte 5 Cloth-Code-Terminal spawnen?"- ) == [(5, "claude")]+ assert _groups("Geil, kannst du bitte 5 Cloth-Code-Terminal spawnen?") == [(5, "claude")]@pytest.mark.parametrize("separator", [" - ", "- ", " – "])@@ -136,7 +135,7 @@ def test_a_plural_product_name_still_names_its_cli() -> None:def test_a_group_without_a_cli_keeps_its_own_count() -> None:- """"two terminals and one Codex" is THREE panes, not two."""+ """ "two terminals and one Codex" is THREE panes, not two."""assert _groups("Open two terminals and one Codex terminal") == [(2, None),(1, "codex"),@@ -153,19 +152,19 @@ def test_a_group_without_a_cli_keeps_its_own_count() -> None:("abre cincuenta terminales", 50), # i18n-allow: spoken input under test],)-def test_a_spoken_count_past_a_dozen_is_heard(utterance: str, expected: int) -> None:- """Numbers above twelve had no words, so they silently became ONE pane."""+def test_a_large_spoken_count_is_heard_and_bounded(utterance: str, expected: int) -> None:+ """Large number words are recognized, then capped by workspace capacity."""+ from jarvis.agentic_ide.session import MAX_TERMINALS+request = intent.detect_spawn(utterance)assert request is not None, utterance- assert request.count == expected+ assert request.count == min(expected, MAX_TERMINALS)def test_the_workspace_maximum_is_the_only_ceiling() -> None:from jarvis.agentic_ide.session import MAX_TERMINALS- request = intent.detect_spawn(- f"open {MAX_TERMINALS + 40} Codex terminals"- )+ request = intent.detect_spawn(f"open {MAX_TERMINALS + 40} Codex terminals")assert request is not Noneassert request.count == MAX_TERMINALS@@ -179,7 +178,7 @@ def test_naming_a_cli_without_counting_it_is_not_a_pane_request() -> None:def test_spawning_agents_is_still_a_background_request() -> None:- """"Spawn" means a worker, even when it names a coding CLI (AP-5 margin)."""+ """ "Spawn" means a worker, even when it names a coding CLI (AP-5 margin)."""# i18n-allow: spoken input under testassert intent.detect_spawn("Spawne 5 Claude Codes") is None@@ -192,9 +191,7 @@ def test_spawning_agents_is_still_a_background_request() -> None:def test_a_cli_the_workspace_does_not_have_is_named_not_dropped() -> None:- request = intent.detect_spawn(- "open two Claude Code terminals and one Gemini terminal"- )+ request = intent.detect_spawn("open two Claude Code terminals and one Gemini terminal")assert request is not Noneassert [(g.count, g.agent) for g in request.groups] == [(2, "claude")]assert request.unsupported == ("Gemini",)diff --git a/tests/unit/agentic_ide/test_workspace_graph.py b/tests/unit/agentic_ide/test_workspace_graph.pynew file mode 100644index 0000000000..3410088f17--- /dev/null+++ b/tests/unit/agentic_ide/test_workspace_graph.py@@ -0,0 +1,271 @@+"""The durable Project -> Workspace -> coding-session navigation contract."""++from __future__ import annotations++import threading+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from jarvis.agentic_ide import library, resume_store, session, workspace_catalog+from jarvis.ui.web import agentic_ide_routes as routes+from tests.fakes.fake_pty_manager import FakePtyManager+++def test_concurrent_readers_initialize_one_lazy_registry(monkeypatch: pytest.MonkeyPatch):+ ready = threading.Barrier(8)+ release_constructor = threading.Event()+ initialized = []++ class SlowRegistry:+ def __init__(self):+ initialized.append(self)+ # Release the GIL while simultaneous REST/tool readers reach the+ # constructor, making an unguarded singleton race reproducible.+ release_constructor.wait(timeout=0.05)++ monkeypatch.setattr(session, "_REGISTRY", None)+ monkeypatch.setattr(session, "Registry", SlowRegistry)+ assert initialized == []++ def read_registry(_index):+ ready.wait(timeout=5)+ return session.get_registry()++ with ThreadPoolExecutor(max_workers=8) as pool:+ results = list(pool.map(read_registry, range(8)))+ assert len(initialized) == 1+ assert all(result is initialized[0] for result in results)+++def registry(monkeypatch: pytest.MonkeyPatch) -> session.Registry:+ monkeypatch.setattr(session, "agent_argv", lambda agent: (f"/usr/bin/{agent}",))+ instance = session.Registry(pty_manager=FakePtyManager())+ monkeypatch.setattr(routes, "get_registry", lambda: instance)+ return instance+++def request() -> SimpleNamespace:+ return SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(bus=None)))+++async def test_empty_project_needs_no_workspace_or_process(registry, tmp_path):+ project = library.ensure_project(tmp_path, name="Example")+ graph = workspace_catalog.project_graph(registry)+ assert graph["projects"][0]["id"] == project.id+ assert graph["projects"][0]["workspaces"] == []+ assert graph["active_workspace_id"] is None+ assert registry._pty.spawns == []+++async def test_two_workspaces_share_project_but_keep_independent_sessions(registry, tmp_path):+ project = library.ensure_project(tmp_path)+ first = await registry.start(+ str(tmp_path),+ [{"agent": "claude"}],+ project_id=project.id,+ name="Installer",+ )+ second = await registry.start(+ str(tmp_path),+ [{"agent": "codex"}],+ project_id=project.id,+ name="Interface",+ )+ assert first.id != second.id+ assert first.project_id == second.project_id == project.id+ assert first.terminals[0].history_id != second.terminals[0].history_id+ graph = workspace_catalog.project_graph(registry)+ assert graph["active_project_id"] == project.id+ assert [w["name"] for w in graph["projects"][0]["workspaces"]] == ["Installer", "Interface"]+ assert graph["active_workspace_id"] == second.id+ assert first.to_dict()["project_id"] == project.id+ assert first.to_card(active=False)["project_id"] == project.id+++async def test_project_ownership_rejects_another_folder(registry, tmp_path):+ first = tmp_path / "one"+ second = tmp_path / "two"+ first.mkdir()+ second.mkdir()+ project = library.ensure_project(first)+ with pytest.raises(session.SessionError, match="belong"):+ await registry.start(str(second), [{"agent": "claude"}], project_id=project.id)+ assert registry.sessions == []+++async def test_eight_cap_applies_to_create_add_and_batch(registry, tmp_path):+ with pytest.raises(session.SessionError, match="At most 8"):+ await registry.start(str(tmp_path), [{"agent": "claude"}] * 9)+ space = await registry.start(str(tmp_path), [{"agent": "claude"}] * 7)+ with pytest.raises(session.SessionError, match="at most 8"):+ await registry.add_terminals(2)+ assert len(space.terminals) == 7+ await registry.add_terminal(agent="claude")+ with pytest.raises(session.SessionError, match="maximum of 8"):+ await registry.add_terminal(agent="claude")+ assert len(space.terminals) == 8+++async def test_closed_sibling_stays_restorable_when_project_has_an_open_workspace(+ registry, tmp_path+):+ first = await registry.start(str(tmp_path), [{"agent": "claude"}], name="First")+ second = await registry.start(str(tmp_path), [{"agent": "codex"}], name="Second")+ await registry.end(first.id)+ await registry.rename(second.id, "Still running")+ saved = resume_store.load()+ assert {space.session_id for space in saved.workspaces} == {first.id, second.id}+ graph = workspace_catalog.project_graph(registry)+ cards = {card["id"]: card for card in graph["projects"][0]["workspaces"]}+ assert cards[first.id]["status"] == "closed"+ assert cards[first.id]["restorable"] is True+ assert cards[second.id]["status"] == "open"+ restored = await registry.restore_workspace(first.id)+ assert restored.id == first.id+ assert restored.terminals[0].history_id == first.terminals[0].history_id+ assert restored.project_id == first.project_id+ assert registry._pty.spawns == []+ assert await registry.restore_workspace(first.id) is restored+ assert len(registry.sessions) == 2+++async def test_order_survives_close_and_restore_without_changing_terminal_identity(+ registry, tmp_path+):+ space = await registry.start(str(tmp_path), [{"agent": "claude"}] * 6)+ ids = [term.history_id for term in reversed(space.terminals)]+ keys = {term.history_id: term.key for term in space.terminals}+ names = {term.history_id: term.name for term in space.terminals}+ result = await routes.reorder_workspace_terminals(+ request(),+ space.id,+ routes.TerminalOrderRequest(terminal_ids=ids),+ )+ assert [t["history_id"] for t in result["workspace"]["terminals"]] == ids+ assert max(term.column for term in space.terminals) <= 3+ assert max(term.slot for term in space.terminals) <= 1+ assert {term.history_id: term.key for term in space.terminals} == keys+ assert {term.history_id: term.name for term in space.terminals} == names+ await registry.end(space.id)+ restored = await routes.restore_saved_workspace(request(), space.id)+ assert [t["history_id"] for t in restored["session"]["terminals"]] == ids+ assert registry._pty.spawns == []++[email protected]("invalid", [[], ["unknown"], ["duplicate", "duplicate"]])+async def test_invalid_order_is_rejected_without_mutation(registry, tmp_path, invalid):+ space = await registry.start(str(tmp_path), [{"agent": "claude"}] * 2)+ before = [term.history_id for term in space.terminals]+ with pytest.raises(HTTPException) as caught:+ await routes.reorder_workspace_terminals(+ request(),+ space.id,+ routes.TerminalOrderRequest(terminal_ids=invalid),+ )+ assert caught.value.status_code == 422+ assert [term.history_id for term in space.terminals] == before+++def test_legacy_snapshot_derives_stable_workspace_and_project_ids(tmp_path: Path):+ raw = {"folder": str(tmp_path), "terminals": [{"name": "T1", "agent": "claude"}]}+ first = resume_store.SnapshotWorkspace.from_dict(raw)+ second = resume_store.SnapshotWorkspace.from_dict(raw)+ assert first.session_id == second.session_id+ assert first.session_id.startswith("ide_")+ assert first.project_id == library.project_id_for(tmp_path)+ assert first.to_dict()["project_id"] == first.project_id+++async def test_duplicate_legacy_workspace_ids_do_not_overwrite_another_project(registry, tmp_path):+ first, second = tmp_path / "one", tmp_path / "two"+ first.mkdir()+ second.mkdir()+ raw = {+ "version": 2,+ "workspaces": [+ {+ "session_id": "ide_legacy",+ "folder": str(folder),+ "terminals": [{"name": "T1", "agent": "claude"}],+ }+ for folder in (first, second)+ ],+ }+ snapshot = resume_store.Snapshot.from_dict(raw)+ again = resume_store.Snapshot.from_dict(raw)+ ids = [space.session_id for space in snapshot.workspaces]+ assert ids[0] == "ide_legacy"+ assert ids[0] != ids[1]+ assert ids == [space.session_id for space in again.workspaces]+ restored = await registry.restore(snapshot)+ assert len(restored.sessions) == len(registry.sessions) == 2+ assert {space.folder for space in registry.sessions} == {str(first), str(second)}+ assert {card["id"] for card in registry.state()["workspaces"]} == set(ids)+ saved = resume_store.load()+ assert {space.session_id for space in saved.workspaces} == set(ids)+++async def test_oversized_legacy_workspace_is_preserved_without_partial_restore(registry, tmp_path):+ saved = resume_store.SnapshotWorkspace(+ session_id="legacy-large",+ folder=str(tmp_path),+ terminals=[+ resume_store.SnapshotTerminal(key=f"t{i}", name=f"T{i}", agent="claude")+ for i in range(9)+ ],+ )+ resume_store.save(resume_store.snapshot_now([saved]))+ with pytest.raises(session.SessionError, match="limit is 8"):+ await registry.restore_workspace(saved.session_id)+ assert len(resume_store.load().workspaces[0].terminals) == 9+ assert registry.sessions == []+++async def test_session_route_accepts_project_and_workspace_name(registry, tmp_path):+ project = library.ensure_project(tmp_path)+ result = await routes.start_session(+ request(),+ routes.StartSessionRequest(+ folder=str(tmp_path),+ project_id=project.id,+ name="Linux installer",+ terminals=[routes.TerminalRequest(agent="claude")],+ ),+ )+ assert result["session"]["name"] == "Linux installer"+ assert result["session"]["project_id"] == project.id+++async def test_add_agent_is_pinned_to_workspace_even_when_another_is_visible(registry, tmp_path):+ first = await registry.start(str(tmp_path), [{"agent": "claude"}])+ second = await registry.start(str(tmp_path), [{"agent": "codex"}])+ result = await routes.add_terminal(+ routes.AddTerminalRequest(+ workspace_id=first.id,+ agent="claude",+ )+ )+ assert len(first.terminals) == 2+ assert len(second.terminals) == 1+ assert result["state"]["active_id"] == second.id+ await registry.add_terminals(2, workspace_id=first.id)+ assert len(first.terminals) == 4+ assert len(second.terminals) == 1++[email protected]("count", range(1, 9))+async def test_initial_grid_order_survives_restore_at_every_supported_size(+ registry, tmp_path, count+):+ space = await registry.start(str(tmp_path), [{"agent": "claude"}] * count)+ ids = [term.history_id for term in space.terminals]+ await registry.end(space.id)+ restored = await registry.restore_workspace(space.id)+ assert [term.history_id for term in restored.terminals] == ids+ assert max(term.column for term in restored.terminals) <= 3+ assert max(term.slot for term in restored.terminals) <= 1diff --git a/tests/unit/web/test_agentic_ide_batch_route.py b/tests/unit/web/test_agentic_ide_batch_route.pyindex d01b15f76b..810291d8d9 100644--- a/tests/unit/web/test_agentic_ide_batch_route.py+++ b/tests/unit/web/test_agentic_ide_batch_route.py@@ -6,6 +6,7 @@ second one is why the route publishes an event at all — the workspace viewfetches its state once when it mounts, so panes it did not create itself areinvisible to it until something tells it to look again."""+from __future__ import annotationsfrom pathlib import Path@@ -31,9 +32,7 @@ def _request(bus: object | None) -> SimpleNamespace:def _terminal(name: str, agent: str = "claude") -> SimpleNamespace:- return SimpleNamespace(- name=name, agent=agent, to_dict=lambda: {"name": name, "agent": agent}- )+ return SimpleNamespace(name=name, agent=agent, to_dict=lambda: {"name": name, "agent": agent})class FakeRegistry:@@ -42,13 +41,22 @@ class FakeRegistry:def __init__(self, created: list[object], capped: bool, folder: Path) -> None:self._created = createdself._capped = capped- self.calls: list[tuple[int, str | None, str | None]] = []+ self.calls: list[tuple[int, str | None, str | None, str | None]] = []self.session = SimpleNamespace(id="ide_test", folder=str(folder))+ self.active_id = self.session.id++ def get(self, workspace_id: str | None):+ return self.session if workspace_id == self.active_id else Noneasync def add_terminals(- self, count: int, *, agent: str | None = None, account: str | None = None+ self,+ count: int,+ *,+ agent: str | None = None,+ account: str | None = None,+ workspace_id: str | None = None,):- self.calls.append((count, agent, account))+ self.calls.append((count, agent, account, workspace_id))return self._created, self._cappeddef state(self) -> dict:@@ -73,7 +81,7 @@ async def test_a_batch_opens_the_panes_and_tells_the_clients(assert [t["name"] for t in result["terminals"]] == ["Juno", "Milo"]# No account named — the registry then opens every pane of the batch on the# workspace's active subscription (see Registry.add_terminal).- assert registry.calls == [(2, "claude", None)]+ assert registry.calls == [(2, "claude", None, "ide_test")]# Exactly one event for the batch, naming every pane — five panes must not# make the open view refetch five times.@@ -90,9 +98,7 @@ async def test_the_cap_is_reported_not_hidden(registry = FakeRegistry([_terminal("Zara")], capped=True, folder=tmp_path)monkeypatch.setattr(routes, "get_registry", lambda: registry)- result = await routes.add_terminals(- _request(FakeBus()), routes.AddTerminalsRequest(count=5)- )+ result = await routes.add_terminals(_request(FakeBus()), routes.AddTerminalsRequest(count=5))assert result["capped"] is Trueassert result["requested"] == 5@@ -106,11 +112,17 @@ async def test_a_refusal_becomes_a_conflict_with_the_reason(class Refusing:session = None+ active_id = Noneasync def add_terminals(- self, count: int, *, agent: str | None = None, account: str | None = None+ self,+ count: int,+ *,+ agent: str | None = None,+ account: str | None = None,+ workspace_id: str | None = None,):- raise SessionError("This workspace already has the maximum of 12 terminals.")+ raise SessionError("This workspace already has the maximum of 8 terminals.")def state(self) -> dict:return {}@@ -118,9 +130,7 @@ async def test_a_refusal_becomes_a_conflict_with_the_reason(monkeypatch.setattr(routes, "get_registry", lambda: Refusing())with pytest.raises(routes.HTTPException) as caught:- await routes.add_terminals(- _request(None), routes.AddTerminalsRequest(count=3)- )+ await routes.add_terminals(_request(None), routes.AddTerminalsRequest(count=3))assert caught.value.status_code == 409assert "maximum" in caught.value.detail@@ -132,9 +142,7 @@ async def test_no_bus_still_opens_the_panes(registry = FakeRegistry([_terminal("Juno")], capped=False, folder=tmp_path)monkeypatch.setattr(routes, "get_registry", lambda: registry)- result = await routes.add_terminals(- _request(None), routes.AddTerminalsRequest(count=1)- )+ result = await routes.add_terminals(_request(None), routes.AddTerminalsRequest(count=1))assert result["ok"] is Trueassert len(result["terminals"]) == 1diff --git a/tests/unit/web/test_agentic_ide_workspaces.py b/tests/unit/web/test_agentic_ide_workspaces.pyindex 58e23d1241..1aaac32cb6 100644--- a/tests/unit/web/test_agentic_ide_workspaces.py+++ b/tests/unit/web/test_agentic_ide_workspaces.py@@ -98,7 +98,7 @@ async def test_the_bar_lists_every_open_workspace_with_the_front_one_marked(await _open(registry, tmp_path / "alpha")await _open(registry, tmp_path / "beta", panes=2)- listed = await routes.get_workspaces()+ listed = routes.get_workspaces()assert [w.name for w in listed.workspaces] == ["alpha", "beta"]assert [w.active for w in listed.workspaces] == [False, True]@@ -121,7 +121,7 @@ async def test_a_tab_counts_the_panes_that_are_really_running(assert session is not Noneawait registry.attach(session.terminals[0].name, 80, 24, _noop, _noop_exit)- card = (await routes.get_workspaces()).workspaces[0]+ card = (routes.get_workspaces()).workspaces[0]assert card.terminals == 2assert card.live_terminals == 1@@ -152,7 +152,7 @@ async def test_switching_starts_and_stops_nothing(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.+ """ "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 itclosed anything, pressing + and then changing your mind would cost you a@@ -207,9 +207,7 @@ async def test_closing_one_workspace_stops_only_its_agents(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:+async def test_closing_an_unknown_workspace_is_a_404(registry: Registry, tmp_path: Path) -> None:from fastapi import HTTPExceptionawait _open(registry, tmp_path / "alpha")@@ -230,9 +228,7 @@ async def test_the_plain_close_still_closes_the_front_one(assert result["closed"] is Trueremaining = [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"]- ]+ assert second["session"]["id"] not in [w["id"] for w in result["state"]["workspaces"]]# -------------------------------------------------------------------- state@@ -243,7 +239,7 @@ async def test_state_carries_the_bar_and_the_front_workspace_together(await _open(registry, tmp_path / "alpha")beta = await _open(registry, tmp_path / "beta")- state = await routes.get_state()+ state = routes.get_state()assert state["session"]["id"] == beta["session"]["id"]assert state["active_id"] == beta["session"]["id"]