Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(agentic-ide): let only the viewer watching a pane set its screen size
Ruben Lütke22e371643a42
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex 280280d8ec..b45e5cae2f 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -76,6 +76,7 @@ from uuid import uuid4from loguru import logger+from jarvis.workspace import agents as workspace_agentsfrom . import recap_engine, resume_storefrom .agent_sessions import (@@ -92,13 +93,76 @@ from .terminal_input import THEME_COLOURS, TerminalQueryResponderfrom .transcript import ReplayBuffer, Transcriptif TYPE_CHECKING: # pragma: no cover - typing only+ from jarvis.agent_accounts import AgentAccountfrom jarvis.terminal.pty_manager import PtyManager-# Agents the IDE can run. Kept parallel to jarvis.workspace.agents (same two-# CLIs, same display names) but with argv built for a one-shot agent process-# rather than a persistent shell.+# The coding CLIs a pane can run, and the binary each one is. This table is what+# "an agent" means to the rest of this module: an account can be pinned to it, a+# conversation can be resumed in it, and a prompt can be typed into it.+#+# argv is built here rather than reused from jarvis.workspace.agents because the+# IDE runs the agent as the PTY's OWN process, not inside a persistent shell.AGENT_BINARIES: dict[str, str] = {"claude": "claude", "codex": "codex"}-AGENT_DISPLAY: dict[str, str] = {"claude": "Claude Code", "codex": "Codex"}++# A pane that runs the machine's own shell and nothing else — see `agent_argv`.+# It is NOT in AGENT_BINARIES on purpose: it has no account, no conversation to+# resume, and (deliberately) no prompt injection, and every one of those falls+# out of that single membership test instead of needing a special case.+PLAIN_TERMINAL: str = workspace_agents.PLAIN_TERMINAL++# What each runnable is called on screen. Read from the workspace registry so a+# newly registered CLI is offerable in the IDE without a second table to keep in+# step (jarvis.workspace.agents.register_agent).+AGENT_DISPLAY: dict[str, str] = {a.name: a.display_name for a in workspace_agents.list_agents()}+++def agent_display(agent: str) -> str:+ """What ``agent`` is called on screen — the name itself if nothing knows it.++ Asks the registry rather than only the snapshot above, so an entry+ registered after import still gets its proper label.+ """+ spec = workspace_agents.get_agent(agent)+ if spec is not None:+ return spec.display_name+ return AGENT_DISPLAY.get(agent, agent)+++def is_runnable(agent: str) -> bool:+ """May a pane run this? Every registered entry, plain terminal included."""+ return workspace_agents.get_agent(agent) is not None+++def accepts_prompts(agent: str) -> bool:+ """May Jarvis type into this pane from the outside (prompt bar, voice, CLI)?++ Only into an AGENT. A plain terminal is a live shell prompt, so an injected+ line would not be read by a coding agent — it would be EXECUTED, which turns+ the one keystroke channel this app exposes into arbitrary command execution+ by voice. That is precisely the boundary the module docstring's rule 1 draws,+ and it is why a plain terminal is typed into by hand or not at all.+ """+ if agent in AGENT_BINARIES:+ return True+ spec = workspace_agents.get_agent(agent)+ return spec is not None and spec.is_coding_agent+++def _unavailable(agent: str) -> str:+ """Why this pane cannot open, said in the terms of what it would have run.++ A missing coding CLI is installable and the message says where; a host with+ no shell at all is not something the user can fix from the CLIs page, and+ pointing them there would send them looking for a product that does not+ exist.+ """+ pretty = agent_display(agent)+ if accepts_prompts(agent):+ return (+ f"{pretty} is not installed or not on this machine's PATH. "+ "Install it from the CLIs page, then try again."+ )+ return f"{pretty} cannot open: this machine has no shell Jarvis can start."# How many panes one workspace may hold.#@@ -455,10 +519,23 @@ def account_home(agent: str, account_id: str | None) -> Path | None:def agent_argv(agent: str) -> tuple[str, ...] | None:- """argv that runs ``agent`` as the PTY's own process, or None if missing."""+ """argv that runs ``agent`` as the PTY's own process, or None if missing.++ A plain terminal resolves to this machine's own interactive shell+ (``discover_shells()`` order: pwsh > Windows PowerShell > cmd > Git Bash, or+ ``$SHELL`` first on macOS/Linux) — no agent wrapped around it, and None on a+ host that has no shell at all, which reads the same as a missing binary.+ """binary = AGENT_BINARIES.get(agent)if binary is None:- return None+ spec = workspace_agents.get_agent(agent)+ if spec is None:+ return None+ if not spec.is_coding_agent:+ return workspace_agents.plain_terminal_argv()+ # A CLI registered at runtime: run the command it declared, resolved+ # through the same shim handling the built-in agents get below.+ binary = spec.launch_command or spec.nametry:from jarvis.core.path_augment import ensure_cli_paths@@ -617,6 +694,11 @@ class Terminal:"name": self.name,"agent": self.agent,"display_name": self.display_name,+ # Can Jarvis type into this pane at all? False for a plain terminal,+ # which is a shell prompt rather than an agent — the prompt bar and+ # the voice path both have to know, or they would offer a target+ # that refuses every instruction sent to it.+ "accepts_prompts": accepts_prompts(self.agent),"index": self.index,"column": self.column,"slot": self.slot,@@ -794,6 +876,11 @@ class Registry:# changed.self._sessions: dict[str, Session] = {}self._active: str | None = None+ # Which subscription NEW panes of each coding CLI open on, chosen in the+ # workspace's own settings. Empty means "whatever the stored default+ # says" — `active_account_id` is the only reader and owns that fallback,+ # so an untouched install behaves exactly as it did before.+ self._active_accounts: dict[str, str] = {}# Injectable so tests can drive the registry against a fake PTY pool# without a real pseudo-terminal (and without a coding agent installed).self._pty: PtyManager | None = pty_manager@@ -812,7 +899,6 @@ class Registry:# run each case on a loop of its own.self._cold_start: asyncio.Semaphore | None = None-# ---------------------------------------------------------------- state@propertydef session(self) -> Session | None:@@ -849,8 +935,77 @@ class Registry:"max_workspaces": MAX_WORKSPACES,"active_id": self._active,"workspaces": self.workspaces(),+ "accounts": self.active_accounts(),}+ # ------------------------------------------------------------- accounts+ def active_account_id(self, agent: str) -> str | None:+ """Which subscription of ``agent`` the next new pane opens on.++ The workspace's own choice when one was made here, the stored default+ otherwise — and an id that no longer resolves degrades to the built-in+ login rather than to nothing (``resolve_account`` owns that fallback).+ ``None`` only for something that is not a coding CLI with accounts.+ """+ if agent not in AGENT_BINARIES:+ return None+ return resolve_account(agent, self._active_accounts.get(agent))++ def active_accounts(self) -> list[dict[str, Any]]:+ """The active subscription of every coding CLI, as the UI shows it.++ Labels rather than ids, because an id is not something anybody can read+ back — "Work seat" is the answer to "which plan does the next terminal+ spend?". The count travels with it so a surface can stay quiet for+ everyone holding a single login and only appear for the few holding two.+ """+ from jarvis import agent_accounts++ rows: list[dict[str, Any]] = []+ for agent in AGENT_BINARIES:+ account_id = self.active_account_id(agent)+ rows.append(+ {+ "agent": agent,+ "display_name": AGENT_DISPLAY.get(agent, agent),+ "active_account": account_id,+ "active_label": account_label(account_id),+ "account_count": len(agent_accounts.list_accounts(agent)), # type: ignore[arg-type]+ }+ )+ return rows++ async def set_active_account(self, agent: str, account_id: str) -> AgentAccount:+ """Point NEW panes of ``agent`` at ``account_id``. This is the switch.++ Nothing that is already open moves. A pane carries the account it was+ created with (see ``resolve_account``), so switching here can never+ re-point a running agent onto a plan whose history has never seen its+ conversation — the same promise the settings surface makes out loud.++ The choice is written through to the stored default as well, so it+ survives a restart and the app's own account page cannot end up+ disagreeing with the workspace about which seat is in use.+ """+ if agent not in AGENT_BINARIES:+ raise SessionError(f"Unknown agent: {agent}")+ from jarvis import agent_accounts++ account = await asyncio.to_thread(agent_accounts.resolve, account_id)+ if account is None or account.platform != agent:+ raise SessionError(+ f"{AGENT_DISPLAY.get(agent, agent)} has no account with id {account_id!r}."+ )+ self._active_accounts[agent] = account.id+ try:+ await asyncio.to_thread(agent_accounts.set_active, agent, account.id) # type: ignore[arg-type]+ except agent_accounts.AccountError as exc:+ # The pin above already governs this session; only its survival past+ # a restart is lost, and that is worth a log rather than a failure.+ logger.warning("Agentic IDE: the active account was not persisted: {}", exc)+ logger.info("Agentic IDE: new {} terminals will use {!r}", agent, account.label)+ return account+def _manager(self) -> PtyManager:if self._pty is None:# Lazy: keeps the terminal stack off the import/boot path (AP-26).@@ -897,7 +1052,9 @@ class Registry:"before opening another.")- unknown = {str(r.get("agent")) for r in requested} - set(AGENT_BINARIES)+ unknown = {+ str(r.get("agent")) for r in requested if not is_runnable(str(r.get("agent")))+ }if unknown:raise SessionError(f"Unknown agent(s): {', '.join(sorted(unknown))}")@@ -905,11 +1062,7 @@ class Registry:{str(r.get("agent")) for r in requested if agent_argv(str(r.get("agent"))) is None})if missing:- pretty = ", ".join(AGENT_DISPLAY.get(m, m) for m in missing)- raise SessionError(- f"{pretty} is not installed or not on this machine's PATH. "- "Install it from the CLIs page, then try again."- )+ raise SessionError(" ".join(_unavailable(m) for m in missing))# Call-signs are unique across ALL open workspaces, not just within# this one. A name is how the user addresses a pane out loud, and a@@ -937,7 +1090,7 @@ class Registry:key=normalize(name) or f"t{index}",name=name,agent=agent,- display_name=AGENT_DISPLAY.get(agent, agent),+ display_name=agent_display(agent),index=index,# A wizard-opened workspace is one row of columns; the# user's own "split down" is what creates a stack.@@ -1054,7 +1207,7 @@ class Registry:return sessionasync def restore(self, snapshot: resume_store.Snapshot) -> RestoreResult:- """Reopen EVERY workspace a snapshot describes, starting nothing.+ """Reopen the workspaces that were OPEN last, starting nothing.The panes come back with their call-signs, their coding CLIs, their gridcoordinates and their resume handles — and in ``pending``, because@@ -1203,7 +1356,7 @@ class Registry:key=entry.key or normalize(entry.name) or f"t{index}",name=entry.name,agent=entry.agent,- display_name=AGENT_DISPLAY.get(entry.agent, entry.agent),+ display_name=agent_display(entry.agent),index=index,column=entry.column,slot=entry.slot,@@ -1756,7 +1909,7 @@ class Registry:rows=rows,on_output=_output,on_closed=_closed,- env=_spawn_env(term),+ env=env,)except Exception as exc: # noqa: BLE001 - surfaced to the paneterm.status = "error"@@ -1965,13 +2118,58 @@ class Registry:except Exception as exc: # noqa: BLE001 - a stale screen beats a failed reconnectlogger.debug("Agentic IDE: could not nudge {} into a repaint: {}", term.name, exc)- def resize(self, key: str, cols: int, rows: int, workspace_id: str | None = None) -> bool:+ def resize(+ self,+ key: str,+ cols: int,+ rows: int,+ workspace_id: str | None = None,+ viewer: Any = None,+ ) -> bool:+ """Tell this pane's agent how big its screen is.++ ``viewer`` is the socket asking, and a pane accepts a size only from the+ viewer that is actually WATCHING it — the same identity check `detach`+ makes, for the same reason and one step further.++ **Why a size needs an owner.** A pseudo-terminal has exactly one size,+ while a pane may be open in more than one place: a second window, the+ browser UI beside the desktop app, a contributor's `--dev` tab. Those+ windows are different sizes, and this used to hand the agent whichever+ one wrote last. That alone would merely be untidy — what made it stick+ is the other half, in the pane itself: a viewer remembers the size it+ sent and stays quiet while its own measurement does not change (see+ `sentSize` in AgenticTerminal.tsx). So the moment a second viewer+ overwrote the size, the first one had no reason left to speak, and the+ agent kept formatting for a window nobody was looking at — a maximized+ pane drawing its interface into a narrow strip down the left-hand side+ (reported 2026-07-27), for as long as the pane stayed open.+ `viewer` settles it: the size comes from the viewer holding the slot,+ and a displaced one cannot move it any more than it can read from it.++ Passing nothing keeps the old unconditional behaviour, which is what an+ internal caller (a repaint nudge, a test) means by it.+ """found = self._locate(key, workspace_id)if found is None:return Falseterm = found[1]if not term.pty_id:return False+ current = term.viewer_output+ # Equality, not only identity — a bound method is a fresh object on+ # every attribute access (see `detach`).+ if (+ viewer is not None+ and current is not None+ and current is not viewer+ and current != viewer+ ):+ logger.debug(+ "Agentic IDE: ignored a resize for {} from a viewer that no longer holds it",+ term.name,+ )+ return False# The replayed screen has to follow the real one; otherwise the# transcript keeps wrapping at the old width.term.transcript.resize(cols, rows)@@ -2044,11 +2242,12 @@ class Registry:usually means "another one of these" — but a caller may name anyinstalled agent, which is how the UI offers a choice of coding CLI.- ``account`` names which subscription of that agent to run on; without one- the pane inherits the anchor's, falling back to the active account. The- inheritance matters more than it looks: splitting a pane that runs the- second plan should stay on the second plan, or a "split" would quietly- move the work onto a different bill.+ ``account`` names which subscription of that agent to run on. Without+ one, a pane split off a NAMED anchor inherits that anchor's account —+ splitting a pane that runs the second plan should stay on the second+ plan, or a "split" would quietly move the work onto a different bill —+ while every other new pane opens on the workspace's active account+ (``set_active_account``)."""async with self._lock:session = self.session@@ -2068,11 +2267,10 @@ class Registry:base = session.terminals[-1] if session.terminals else Nonechosen = agent or (base.agent if base else "claude")- if chosen not in AGENT_BINARIES:+ if not is_runnable(chosen):raise SessionError(f"Unknown agent: {chosen}")if agent_argv(chosen) is None:- pretty = AGENT_DISPLAY.get(chosen, chosen)- raise SessionError(f"{pretty} is not installed or not on this machine's PATH.")+ raise SessionError(_unavailable(chosen))# Unused ACROSS every open workspace: a split must not hand this# pane a call-sign another tab already answers to.@@ -2110,14 +2308,30 @@ class Registry:if other.column == column and other.slot >= slot:other.slot += 1- # Inherit the anchor's account only when the split stays on the same- # CLI — a Claude account id means nothing to Codex.- inherited = base.account if base is not None and base.agent == chosen else None+ # Which subscription the new pane opens on, when the caller named+ # none. Two different questions, so two different answers:+ #+ # * **A named anchor is a split** — "another one of these". It+ # inherits, and only when the CLI matches (a Claude account id+ # means nothing to Codex), so splitting a pane that runs the+ # second plan cannot quietly move the work onto a different bill.+ # * **Everything else is a NEW terminal** — the batch behind "open+ # five more", the empty grid's button, the CLI. Those follow the+ # workspace's active account, which is exactly the promise the+ # account switcher makes: switching applies to new terminals.+ #+ # Anchor-less used to inherit from whatever pane happened to be last,+ # which made the switch reach nothing a user could predict: flipping+ # to the second seat and opening a terminal still billed the first.+ if anchor and base is not None and base.agent == chosen:+ inherited = base.account+ else:+ inherited = self.active_account_id(chosen)term = Terminal(key=normalize(final) or f"t{len(session.terminals)}",name=final,agent=chosen,- display_name=AGENT_DISPLAY.get(chosen, chosen),+ display_name=agent_display(chosen),index=len(session.terminals),column=column,slot=slot,@@ -2148,7 +2362,8 @@ class Registry:Deliberately a loop over ``add_terminal`` rather than a second placementimplementation: the anchor, the call-sign pool, and the grid position arealready decided there, and a batch that placed panes its own way would- drift from what the split buttons do.+ drift from what the split buttons do. No anchor is named, so without an+ explicit ``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@@ -2375,6 +2590,16 @@ class Registry:if found is None:raise self._unknown_terminal(wanted)_session, term = found+ if not accepts_prompts(term.agent):+ # A plain terminal is a live SHELL prompt, so an injected line would+ # not be read by an agent — it would run as a command. This is the+ # one place the module docstring's rule 1 has to be enforced rather+ # than merely implied, because such a pane exists on purpose now.+ raise SessionError(+ f"{term.name} is a {agent_display(term.agent).lower()}, not a coding agent — "+ "Jarvis does not type into a shell. Type it there yourself, or send it "+ "to an agent terminal."+ )if term.status != "live" or not term.pty_id:raise SessionError(f"{term.name} is not running right now (status: {term.status}) — nothing was sent."@@ -2636,6 +2861,31 @@ def coding_mode_active() -> bool:return session is not None and bool(session.focus_mode)+def running_call_signs() -> list[str]:+ """Call-signs of the open workspace, or ``[]`` when none is open.++ ONE answer for every layer that has to know which names are currently+ speakable — the turn planner, the realtime session instructions, and the+ addressed-terminal detector. They must agree: a layer that reads a+ different roster than the detector either routes a turn nobody can serve or+ withholds one the workspace owns.++ Deliberately NOT gated on ``coding_mode_active``. The panes carry their+ call-signs the moment they exist, and a user who says "what has Dana done"+ with the focus toggle off means the same terminal they would mean with it+ on. Callers that need the stricter mode ask ``coding_mode_active`` as well.++ Never raises — an optional surface must not be able to break a caller.+ """+ try:+ session = get_registry().session+ except Exception: # noqa: BLE001 - optional surface, never fatal+ return []+ if session is None:+ return []+ return [term.name for term in session.terminals]++def coding_mode_event(session: Session | None, *, source_layer: str) -> Any:"""The bus event announcing the EFFECTIVE coding mode to every client.@@ -2678,16 +2928,21 @@ __all__ = ["MAX_PROMPT_CHARS","MAX_TERMINALS","MAX_WORKSPACES",+ "PLAIN_TERMINAL","Registry","Session","SessionError","SessionNotReady","Terminal",+ "accepts_prompts","agent_argv",+ "agent_display","coding_mode_active","coding_mode_event","get_registry",+ "is_runnable","reset_registry",+ "running_call_signs","sanitize_prompt","terminals_added_event",]diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex e64f67779f..769b90af09 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -23,8 +23,11 @@ Endpoints (prefix ``/api/agentic-ide``):* ``GET /interrupted`` → panes that came back and were never restarted* ``POST /interrupted/continue`` → tell them to carry on ("continue")* ``PUT /mode`` → focused coding mode on/off+* ``GET /accounts`` → which subscription new terminals use+* ``PUT /accounts/active`` → switch it (open panes keep theirs)* ``POST /terminals`` → open one more pane (split)* ``POST /terminals/batch`` → open N more panes at once+* ``DELETE /terminals/agent/{agent}`` → close every pane of one coding CLI* ``POST /fanout`` → run ONE task across several agents(open the panes, divide the work, brief each one, report who was reached)* ``GET /terminals/{name}/report`` → what one named terminal is doing@@ -56,6 +59,8 @@ from fastapi import (from pydantic import BaseModel, Fieldfrom jarvis.agentic_ide import (+ drop_analysis,+ drops,interrupted,native_picker,recap_engine,@@ -64,6 +69,11 @@ from jarvis.agentic_ide import ()from jarvis.agentic_ide.agent_sessions import has_conversationfrom jarvis.agentic_ide.device import device_name+from jarvis.agentic_ide.fleet_actions import (+ close_agent_terminals,+ terminals_closed_event,+ wait_for_prompt_ready,+)from jarvis.agentic_ide.folders import list_dir, search_folders, start_pointsfrom jarvis.agentic_ide.names import default_namesfrom jarvis.agentic_ide.session import (@@ -79,16 +89,25 @@ from jarvis.agentic_ide.session import (agent_argv,coding_mode_event,get_registry,+ sanitize_prompt,terminals_added_event,)-from jarvis.agentic_ide.terminal_input import is_terminal_report_only+from .surface_security import credentials_valid, is_loopback_requestlog = logging.getLogger(__name__)router = APIRouter(prefix="/api/agentic-ide", tags=["agentic-ide"])+#: How long a fan-out waits for panes it just opened to start their agents.+#: Shorter than the shared fleet budget on purpose: this one is spent inside an+#: HTTP request, and the registry-command tool that a voice turn goes through+#: gives up at 30 s — a wait that outlives its own caller reports nothing to+#: anybody. Panes still coming up after this are reported as undelivered rather+#: than waited for indefinitely.+SPAWN_READY_TIMEOUT_S = 20.0+async def _announce_coding_mode(request: Request) -> None:"""Tell every connected client what the coding mode is NOW.@@ -120,6 +139,13 @@ _native_picker_lock = asyncio.Lock()# --------------------------------------------------------------------------- ## Models ## --------------------------------------------------------------------------- #+#: Bounds on the analysed drops one prompt may carry back. Both mirror the+#: analysis module's own caps rather than restating numbers, so a change there+#: cannot leave this schema rejecting payloads the analyser legitimately+#: produces.+DROP_DETAIL_MAX_CHARS = drop_analysis.MAX_TEXT_CHARS+MAX_PROMPT_ATTACHMENTS = drops.MAX_FILES+#: Reused wherever a caller may pick which subscription a pane runs on._ACCOUNT_FIELD_DESCRIPTION = ("Which stored subscription of that agent to run on (see /api/agent-accounts). "@@ -222,6 +248,18 @@ class ModeRequest(BaseModel):)+class ActiveAccountRequest(BaseModel):+ """Which subscription new terminals of one coding CLI should open on."""++ agent: str = Field(description="Coding agent to switch: 'claude' or 'codex'.")+ account_id: str = Field(+ description=(+ "Id of a stored subscription of that agent (see /api/agent-accounts). "+ "Terminals that are already open keep the account they started with."+ )+ )++class ActivateWorkspaceRequest(BaseModel):"""Which workspace should be on screen."""@@ -324,6 +362,44 @@ class FanOutRequest(BaseModel):)+class PromptAttachment(BaseModel):+ """One analysed file the user dropped, on its way back into a prompt.++ Returned by ``POST /terminals/{name}/attach?analyze=true`` and handed back+ here unchanged. It travels through the caller rather than being held on the+ server because a drop and the sentence that explains it are one user action+ split across two requests: parking the analysis server-side would make two+ browser tabs, the CLI and a voice turn fight over whose attachment is+ "current".+ """++ name: str = Field(description="The dropped file's display name.")+ reference: str = Field(+ default="",+ description="How the agent should refer to the file (@path or a quoted path).",+ )+ kind: str = Field(+ default="other",+ description="What the file is: image, text, pdf, or other.",+ )+ detail: str = Field(+ default="",+ max_length=DROP_DETAIL_MAX_CHARS,+ description=(+ "The vision description of an image, or the extracted text of a "+ "document. Empty when neither could be produced."+ ),+ )+ described_by: str = Field(+ default="none",+ description="Which layer produced 'detail': vision, extraction, or none.",+ )+ note: str = Field(+ default="",+ description="Why 'detail' is empty or shortened. Empty on the happy path.",+ )++class PromptRequest(BaseModel):prompt: str = Field(max_length=MAX_PROMPT_CHARS,@@ -341,6 +417,16 @@ class PromptRequest(BaseModel):default=False,description="Compose and return the prompt WITHOUT sending it.",)+ attachments: list[PromptAttachment] = Field(+ default_factory=list,+ max_length=MAX_PROMPT_ATTACHMENTS,+ description=(+ "Files the user dropped with this instruction, as returned by the "+ "attach endpoint with analyze=true. Their descriptions and extracted "+ "text are folded into the composed prompt so the coding agent gets "+ "the content of a screenshot it may not be able to open itself."+ ),+ )class AgentStatus(BaseModel):@@ -349,6 +435,14 @@ class AgentStatus(BaseModel):installed: boolversion: str | None = Noneinstall_command: str | None = None+ kind: str = Field(+ default="cli",+ description=(+ "'cli' for a coding agent, 'shell' for a plain terminal. A client uses "+ "this to say what a pane will be, without hardcoding entry names."+ ),+ )+ description: str = Field(default="", description="One line for a picker.")class AgentsResponse(BaseModel):@@ -702,8 +796,10 @@ async def get_state() -> dict:@router.get("/agents", response_model=AgentsResponse, summary="Coding agents available")async def get_agents() -> AgentsResponse:- """Which coding-agent CLIs this machine can run, and how to install them.+ """What this machine can open in a terminal, and how to install it.+ Every registered entry (``jarvis.workspace.agents``): the coding-agent CLIs+ and the plain terminal, which is "installed" whenever this host has a shell.Detection reuses the shared CLI prober, then re-checks that the binary isresolvable the way the PTY will resolve it — a GUI process starts with aminimal PATH, so "installed" and "launchable from here" are not the same@@ -719,6 +815,8 @@ async def get_agents() -> AgentsResponse:installed=bool(info.installed and agent_argv(info.name) is not None),version=info.version,install_command=info.install_command,+ kind=info.kind,+ description=info.description,)for info in infos]@@ -945,9 +1043,7 @@ async def get_workspaces() -> WorkspacesResponse:@router.put("/workspaces/active", summary="Switch to another workspace")-async def activate_workspace(- request: Request, req: ActivateWorkspaceRequest-) -> dict:+async def activate_workspace(request: Request, req: ActivateWorkspaceRequest) -> dict:"""Bring one workspace to the front, or clear the front entirely.Nothing starts, stops or restarts: the agents in every open workspace keep@@ -1304,10 +1400,56 @@ async def set_mode(request: Request, req: ModeRequest) -> dict:except SessionError as exc:raise HTTPException(status_code=409, detail=str(exc)) from exc- await _announce_coding_mode(request)+ bus = getattr(request.app.state, "bus", None)+ if bus is not None:+ try:+ await bus.publish(+ coding_mode_event(registry.session, source_layer="agentic_ide_routes")+ )+ except Exception as exc: # noqa: BLE001 - the mode is set either way+ log.debug("AgenticIdeCodingModeChanged publish failed: %s", exc)+return {"ok": True, "focus_mode": enabled}[email protected]("/accounts", summary="Which subscription new terminals use")+async def get_accounts() -> dict:+ """The active subscription of every coding CLI, with its display name.++ The workspace's own view of the account switcher: which plan the next+ terminal will spend, and how many are registered — enough for a surface to+ stay quiet for everyone holding a single login. The full list, its sign-in+ state and the CRUD around it live under ``/api/agent-accounts``.+ """+ registry = get_registry()+ return {"ok": True, "accounts": await asyncio.to_thread(registry.active_accounts)}++[email protected]("/accounts/active", summary="Switch which subscription new terminals use")+async def set_active_account(req: ActiveAccountRequest) -> dict:+ """Point new terminals of one coding CLI at another subscription.++ Running panes are deliberately untouched: each carries the account it was+ opened with, so this can never move an agent mid-conversation onto a plan+ whose history does not contain that conversation. The choice also becomes+ the machine's stored default, so it survives a restart.+ """+ registry = get_registry()+ try:+ account = await registry.set_active_account(req.agent, req.account_id)+ except SessionError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ display = AGENT_DISPLAY.get(req.agent, req.agent)+ return {+ "ok": True,+ "agent": req.agent,+ "active_account": account.id,+ "active_label": account.label,+ "message": f"New {display} terminals will use {account.label}.",+ "state": registry.state(),+ }++@router.post("/terminals", summary="Open one more terminal")async def add_terminal(req: AddTerminalRequest) -> dict:"""Add a terminal to the running workspace, beside or below another one.@@ -1625,6 +1767,8 @@ async def terminal_attach(paths: str | None = Form(default=None), # noqa: B008submit: bool = Form(default=False), # noqa: B008note: str | None = Form(default=None), # noqa: B008+ analyze: bool = Form(default=False), # noqa: B008+ deliver: bool = Form(default=True), # noqa: B008) -> dict:"""Put dropped or pasted files in front of the agent in terminal ``name``.@@ -1641,9 +1785,20 @@ async def terminal_attach(The resulting references are TYPED into the pane, not submitted, so the usercan add a sentence before pressing Enter — which is what someone dropping ascreenshot almost always wants to do. ``submit=true`` sends it as-is.- """- from jarvis.agentic_ide import drops+ Two flags change what a drop is FOR, and the prompt bar uses both:++ * ``analyze=true`` reads the files' contents — a vision-capable model+ describes an image, a document has its text extracted — and returns that+ under ``analysis``. Hand it back to ``/terminals/{name}/prompt`` as+ ``attachments`` and the composed brief carries the picture's contents,+ which is what makes dropping a screenshot work against an agent that+ cannot open one.+ * ``deliver=false`` stores and analyses without typing anything into the+ pane, for a caller that is assembling a prompt rather than handing the+ agent a path right now. The files are on disk and referenced either way,+ so nothing is lost if the user then walks away.+ """registry = get_registry()# Resolved across every open workspace, not just the front one: call-signs# are unique across them, and a file dropped on a pane belongs to THAT@@ -1661,6 +1816,12 @@ async def terminal_attach(references: list[str] = []stored_names: list[str] = []copied = 0+ # (name, bytes, reference) for everything that ends up attached — collected+ # only when the caller asked for an analysis, because reading a file the+ # agent could simply open itself is work nobody is waiting for. The+ # reference travels with the bytes so the description and the path the agent+ # opens can never drift apart.+ readable: list[tuple[str, bytes, str]] = []# 1. Paths that came with the drag. A path already inside the workspace is# used as it lies; anything else is copied in.@@ -1671,8 +1832,19 @@ async def terminal_attach(continueinside = drops.within_workspace(candidate, session.folder)if inside is not None:- references.append(drops.reference(inside, agent=term.agent))+ reference = drops.reference(inside, agent=term.agent)+ references.append(reference)stored_names.append(Path(inside).name)+ if analyze:+ # Nothing is copied on this route, so the bytes have to be read+ # here to be described. A failure is not fatal: the reference+ # still ships, the file simply goes undescribed.+ try:+ body = await asyncio.to_thread((Path(session.folder) / inside).read_bytes)+ except OSError as exc:+ log.info("Agentic IDE attach: %r not readable for analysis (%s)", inside, exc)+ else:+ readable.append((Path(inside).name, body, reference))continue# expanduser() is string/env work, not a filesystem call; the read# itself goes to a worker thread (a dropped file may live on a slow@@ -1701,15 +1873,25 @@ async def terminal_attach(if data:to_copy.append((upload.filename or "file", data))+ # ``store`` silently skips empty entries, so they are dropped HERE instead —+ # that keeps ``stored[i]`` paired with ``to_copy[i]`` positionally. Pairing+ # by name would be wrong: two files that sanitize to the same name are+ # stored as two distinct files but would collapse into one key, and one drop+ # would be referenced twice while the other went missing.+ to_copy = [(name, data) for name, data in to_copy if data]+if to_copy:try:stored = await asyncio.to_thread(drops.store, session.folder, to_copy)except drops.DropError as exc:raise HTTPException(status_code=422, detail=str(exc)) from exccopied = len(stored)- for item in stored:- references.append(drops.reference(item.relative_path, agent=term.agent))+ for item, (_original, data) in zip(stored, to_copy, strict=True):+ reference = drops.reference(item.relative_path, agent=term.agent)+ references.append(reference)stored_names.append(item.name)+ if analyze:+ readable.append((item.name, data, reference))if not references:raise HTTPException(@@ -1717,13 +1899,23 @@ async def terminal_attach(detail="That drop carried nothing this pane could use.",)+ analysis: list[dict] = []+ if analyze and readable:+ analysis = [item.to_dict() for item in await _analyze_drops(readable)]+payload = " ".join(references)if note and note.strip():payload = f"{payload} {note.strip()}"+ delivered = Falsetry:- if submit:+ if not deliver:+ # Held deliberately: the caller is building a prompt around these+ # files and will send the whole thing itself.+ pass+ elif submit:await registry.send_prompt(term.name, payload)+ delivered = Trueelse:# Typed, not submitted: the user still wants to say what to DO with# the file. A leading space keeps it off whatever they already typed.@@ -1732,6 +1924,7 @@ async def terminal_attach(status_code=409,detail=f"{term.name} is not accepting input right now.",)+ delivered = Trueexcept SessionError as exc:raise HTTPException(status_code=409, detail=str(exc)) from exc@@ -1741,10 +1934,43 @@ async def terminal_attach("references": references,"files": stored_names,"copied": copied,- "submitted": bool(submit),+ "submitted": bool(submit and delivered),+ "delivered": delivered,+ "analysis": analysis,}+async def _analyze_drops(+ readable: list[tuple[str, bytes, str]],+) -> list[drop_analysis.DropAnalysis]:+ """Describe/extract the dropped files. Never raises — an analysis is a bonus.++ A drop that reached this point is already stored and referenced; the pane+ works with or without a description, so a provider outage here must cost the+ description and nothing else.+ """+ import mimetypes++ from jarvis.brain.drop_context import DroppedItem++ items = [+ (+ DroppedItem(+ name=name,+ mime=mimetypes.guess_type(name)[0] or "application/octet-stream",+ data=data,+ ),+ reference,+ )+ for name, data, reference in readable+ ]+ try:+ return await drop_analysis.analyze(items)+ except Exception as exc: # noqa: BLE001 - the drop itself already succeeded+ log.info("Agentic IDE attach: analysis failed (%s)", exc)+ return []++@router.post("/fanout", summary="Run one task across several coding agents")async def fanout(request: Request, req: FanOutRequest) -> dict:"""Brief a fleet: open the panes if asked, divide the work, deliver it.@@ -1794,9 +2020,41 @@ async def fanout(request: Request, req: FanOutRequest) -> dict:await bus.publish(terminals_added_event(session, created, source_layer="agentic_ide_routes"))+ # Bringing the workspace forward is not cosmetic here: a pane's+ # agent process starts when the VIEW mounts it, so a workspace+ # sitting behind another section never starts the panes this+ # call just opened — and briefing them would then be impossible+ # by construction.+ from jarvis.core.events import NavigateSidebar++ await bus.publish(+ NavigateSidebar(+ section="agentic-ide", source_layer="agentic_ide_routes"+ )+ )except Exception as exc: # noqa: BLE001 - notification is not the worklog.debug("AgenticIdeTerminalsAdded publish failed: %s", exc)+ if created and session is not None and bus is not None:+ # Wait for the panes to come up before typing into them. Without+ # this, "open one and brief it" opened the pane and briefed NOBODY:+ # a registry entry exists microseconds after the call, its agent+ # does not, and every delivery came back "not_running" (the known+ # limit this replaces). Bounded well under the command tool's HTTP+ # budget, and panes that never make it stay in `undelivered`.+ ready = await wait_for_prompt_ready(+ session,+ [t.name for t in created],+ timeout_s=SPAWN_READY_TIMEOUT_S,+ )+ late = [t.name for t in created if t.name not in ready]+ if late:+ log.info(+ "Agentic IDE fan-out: panes not ready within %.0fs: %s",+ SPAWN_READY_TIMEOUT_S,+ ", ".join(late),+ )+names = list(req.terminals or []) + [t.name for t in created]if not names:raise HTTPException(@@ -1874,6 +2132,34 @@ def _delivery_payload(delivery: object) -> dict:}+def _unknown_terminal_detail(registry: object, wanted: str) -> str:+ """The "no such pane" 404 for a prompt, with the move that RECOVERS it.++ Listing the running panes is not enough on its own. A caller that wanted to+ brief a pane called "Lee" reads a bare "not found" as "then open one" — and+ call-signs come from a fixed pool in a fixed order, so the pane it opens is+ called something else entirely and the very same prompt 404s again. A live+ voice session on 2026-07-27 went round that loop four times and left four+ blank panes behind, without ever briefing anyone.++ So the error names the one move that works: brief a pane that exists, or+ open AND brief a new one in a single fan-out call, which returns the+ call-sign it was actually given.+ """+ running = ", ".join(+ t.name for s in registry.sessions for t in s.terminals # type: ignore[attr-defined]+ )+ return (+ f"No terminal called {wanted!r}. Running: {running or 'none'}. "+ "Call-signs are assigned automatically and cannot be requested, so "+ "opening another pane will NOT produce this name and retrying this "+ "prompt after a spawn fails the same way. Either prompt one of the "+ "panes listed above, or open and brief a new one in ONE call: "+ "POST /api/agentic-ide/fanout with spawn=[{\"count\": 1}] and the "+ "instruction."+ )++@router.post("/terminals/{name}/prompt", summary="Send a prompt to one terminal")async def terminal_prompt(name: str, req: PromptRequest) -> dict:"""Type ``prompt`` into the terminal called ``name`` and press Enter.@@ -1886,14 +2172,33 @@ async def terminal_prompt(name: str, req: PromptRequest) -> dict:``dry_run=true`` returns the composed prompt without sending it, so a callercan show it for approval first.++ ``attachments`` carries files the user dropped with the instruction, already+ analysed by the attach endpoint. Their descriptions and extracted text go+ into the composition, which is the difference between an agent being told+ "fix the layout in the screenshot" and being told what the screenshot+ actually shows."""registry = get_registry()if not registry.sessions:raise HTTPException(status_code=409, detail="No Agentic-IDE session is running.")+ # Resolve the pane FIRST, so an unknown call-sign fails identically whether+ # or not composition was asked for. It used to 404 with composition on and+ # 409 with it off, which gave a caller two different-looking dead ends for+ # one cause — and neither of them said what to do about it.+ found = registry.find_terminal(name)+ if found is None:+ raise HTTPException(+ status_code=404, detail=_unknown_terminal_detail(registry, name)+ )+text = req.promptcomposed_by = "raw"files: list[str] = []+ attachments = [+ drop_analysis.DropAnalysis.from_dict(a.model_dump()) for a in req.attachments+ ]if req.compose:from jarvis.agentic_ide.prompt_composer import compose as compose_prompt@@ -1901,23 +2206,29 @@ async def terminal_prompt(name: str, req: PromptRequest) -> dict:# reads the codebase to attach `@file` references, and taking those# from the front workspace while sending to a pane in another one would# point the agent at files that are not in its tree.- found = registry.find_terminal(name)- if found is None:- known = ", ".join(t.name for s in registry.sessions for t in s.terminals) or "none"- raise HTTPException(- status_code=404,- detail=f"No terminal called {name!r}. Running: {known}.",- )session, term_for_compose = foundresult = await compose_prompt(req.prompt,session=session,terminal_name=term_for_compose.name,agent_display=AGENT_DISPLAY.get(term_for_compose.agent, term_for_compose.agent),+ attachments=attachments,)text, composed_by, files = result.text, result.composed_by, result.filesif not text:raise HTTPException(status_code=422, detail="The prompt was empty after composition.")+ elif attachments:+ # Attachments without composition still have to reach the agent. Silently+ # dropping them would be the worst reading of this request: the caller+ # said "here is what the user dropped" and the agent would receive a+ # sentence about a screenshot nobody described. The deterministic+ # renderer is the same one the no-provider path uses.+ from jarvis.agentic_ide import prompt_blueprint++ text = sanitize_prompt(+ prompt_blueprint.render_fallback(text, [], attachments), keep_newlines=True+ )[:MAX_PROMPT_CHARS]+ composed_by = "fallback"if req.dry_run:return {@@ -1927,6 +2238,7 @@ async def terminal_prompt(name: str, req: PromptRequest) -> dict:"composed": text,"composed_by": composed_by,"files": files,+ "attachments": [a.to_dict() for a in attachments],"dry_run": True,}@@ -2121,11 +2433,17 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:else:registry.write(term.key, data, pane_workspace)elif kind == "r":+ # ``on_output`` identifies THIS socket. A pane open in two+ # places has two viewers and one pseudo-terminal, so a size+ # from the viewer that no longer holds the pane would set the+ # agent's screen to a window nobody is reading — and the viewer+ # that IS being read has no way to notice or correct it.registry.resize(term.key,_safe_int(msg.get("cols"), cols),_safe_int(msg.get("rows"), rows),pane_workspace,+ viewer=on_output,)finally:# The viewer went away — switched tab, reloaded, closed the browser.@@ -2141,7 +2459,6 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:registry.detach(term.key, pane_workspace, viewer=on_output)-def _safe_int(value: object, default: int) -> int:try:n = int(str(value))diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsxindex d8fda36b09..b0477e39f7 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx@@ -518,6 +518,15 @@ export function AgenticTerminal({return;}if (term.cols < 2 || term.rows < 2) return;+ // Resizing a pane is the other half of the un-park story. Maximizing one,+ // dragging a seam, changing the font — all of them are a user opening up+ // a pane to READ it, and the pane it opens must not be a parked one still+ // holding its agent's screen. BEFORE the early return below, deliberately:+ // whether a size still needs announcing says nothing about whether the+ // pane is being looked at, and a pane that came back at exactly the size+ // it left would otherwise stay dark. The measurement inside only un-parks+ // a pane that really is on screen.+ revealIfOnScreen();const size = { cols: term.cols, rows: term.rows };// Already delivered and unchanged: the fit above was the whole job.// Re-announcing a size makes the agent on the other end redraw its@@ -526,13 +535,6 @@ export function AgenticTerminal({return;}if (socket?.send({ t: "r", ...size })) sentSize = size;- // Resizing a pane is the other half of the un-park story. Maximizing one,- // dragging a seam, changing the font — all of them are a user opening up- // a pane to READ it, and the pane it opens must not be a parked one still- // holding its agent's screen. The measurement above already proved the- // container has area, so this only ever un-parks a pane that is really- // there; a pane genuinely off screen stays parked.- revealIfOnScreen();};resizeRef.current = sendResize;diff --git a/tests/unit/agentic_ide/test_session.py b/tests/unit/agentic_ide/test_session.pyindex fa480a5373..93f5fb46b7 100644--- a/tests/unit/agentic_ide/test_session.py+++ b/tests/unit/agentic_ide/test_session.py@@ -490,3 +490,51 @@ async def test_report_includes_status_and_folder(assert data["name"] == "Alex"assert data["folder"] == str(tmp_path)assert data["status"] == "pending"+++async def test_a_displaced_viewer_cannot_resize_the_pane_it_lost(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """A pseudo-terminal has one size; only the viewer watching it may set it.++ A pane open in two places — a second window, the browser UI beside the+ desktop app — used to hand the agent whichever size arrived last. Combined+ with the pane's own "I already sent this size" memory, the viewer being read+ then had no reason left to correct it, and the agent kept formatting for a+ window nobody was looking at: a maximized pane drawing into a narrow strip+ (reported 2026-07-27).+ """+ await _open(registry, tmp_path, [{"agent": "claude"}])++ async def first_viewer(_text: str) -> None: ...+ async def second_viewer(_text: str) -> None: ...++ await registry.attach("Alex", 80, 24, first_viewer, _noop_exit)+ term = registry.session.terminals[0]+ # The second window takes the pane over — the newest viewer always wins.+ await registry.attach("Alex", 200, 50, second_viewer, _noop_exit)+ fake_pty.resizes.clear()++ # The displaced viewer keeps measuring its own window and reporting it.+ assert registry.resize(term.key, 40, 20, viewer=first_viewer) is False+ assert fake_pty.resizes == [], "a displaced viewer must not move the agent's screen"++ # The viewer that actually holds the pane still can.+ assert registry.resize(term.key, 200, 50, viewer=second_viewer) is True+ assert fake_pty.resizes == [(term.pty_id, 200, 50)]+++async def test_an_internal_resize_needs_no_viewer(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """A repaint nudge and a test speak for the pane itself, not for a window."""+ await _open(registry, tmp_path, [{"agent": "claude"}])++ async def viewer(_text: str) -> None: ...++ await registry.attach("Alex", 80, 24, viewer, _noop_exit)+ term = registry.session.terminals[0]+ fake_pty.resizes.clear()++ assert registry.resize(term.key, 120, 40) is True+ assert fake_pty.resizes == [(term.pty_id, 120, 40)]