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): stop live changes from needing a page reload
Ruben Lütke9b243a69a379
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex 7fc820648e..abd3303424 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -779,6 +779,19 @@ class Terminal:last_output_at: float | None = Noneprompts_sent: int = 0last_prompt: str = ""+ # When the last prompt was handed to this pane, as a wall-clock timestamp.+ #+ # The receipt the user is shown is built from THIS rather than from the+ # terminal stream, and that is the whole point. A pane proves a prompt+ # arrived by echoing it, which requires a chain of things to have gone+ # right at one particular moment: the pane on screen, its output un-parked,+ # its socket up, the emulator painted. Every link in that chain has failed+ # in production at least once, and each failure looks identical from the+ # user's chair — Jarvis says it sent the brief and the pane shows nothing,+ # so the honest conclusion is that Jarvis lied. A timestamp in the state+ # cannot be missed: it is read at mount, at every reconnect and at every+ # poll, so the receipt is still there when somebody looks ten minutes later.+ last_prompt_at: float | None = None# Did the last prompt actually leave the input line? None = none sent yet.submitted: bool | None = None# Did it arrive with its line structure intact? False means the pane@@ -841,6 +854,39 @@ class Terminal:# Bound at spawn, cleared on detach, replaced on re-attach.viewer_output: Any = Noneviewer_exit: Any = None+ # EVERY viewer currently attached to this pane, as ``(output, exit)`` pairs,+ # newest last. ``viewer_output`` above is the newest of them — the OWNER,+ # which is a different question from who gets to see the screen.+ #+ # One slot was enough only while a pane could be open in one place. It can+ # be open in several: the desktop app and a browser tab, two windows, a+ # contributor's dev server beside the app. Every one of them attaches to the+ # same pane, and with a single slot the last to connect took the output and+ # every other viewer went silent for good — an agent typing away behind a+ # screen that never moved again, indistinguishable from a dead terminal, and+ # only a reload brought it back (reported 2026-07-28, where a leftover tab+ # from an earlier session quietly held the output of the panes the user was+ # watching).+ #+ # Output is therefore fanned out to all of them, while the OWNER keeps the+ # decisions that must have exactly one answer: the pseudo-terminal's size,+ # and who is allowed to hand the slot back (see ``resize`` and ``detach``).+ watchers: list[tuple[Any, Any]] = field(default_factory=list, repr=False, compare=False)+ # Viewers that want to be TOLD when this pane is handed a prompt, rather+ # than having to notice it in the output stream.+ #+ # Separate from ``watchers`` because it answers a different question. That+ # list carries the agent's screen, and a screen is exactly what fails to+ # prove a delivery: the pane may be parked, its emulator unpainted, its+ # socket reconnecting, or the CLI may simply redraw its input box without+ # the text ever scrolling into view. Every one of those has happened, and+ # each time the user was told the brief was sent and saw nothing.+ #+ # So delivery is announced on its own channel, and the state carries it too+ # (``last_prompt_at``) for the viewer that was not connected at that+ # instant. Neither is a substitute for the other: this one is immediate and+ # lossy, the state is durable and up to one poll late.+ prompt_viewers: list[Any] = field(default_factory=list, repr=False, compare=False)# Serializes THIS pane's attach path — see `SessionRegistry.attach`.## A pane is routinely connected to more than once in the same instant: the@@ -902,6 +948,17 @@ class Terminal:# poll AND every model-facing status payload — per pane. 200 chars# matches the focus block's per-pane budget."last_prompt": self.last_prompt[:200],+ # How long the delivered text really is, so a client can say "1 of+ # 2 400 characters" instead of presenting the 200-char excerpt as+ # if it were everything that was sent.+ "last_prompt_chars": len(self.last_prompt),+ # WHEN it was handed over. Cheap enough for every poll (one float),+ # and it is what turns "this pane has a last prompt" into "this pane+ # was given a prompt at 15:42:07" — a claim the user can check+ # against what they just heard Jarvis say. See the field's own+ # comment for why the receipt may not be built from the terminal+ # stream instead.+ "last_prompt_at": self.last_prompt_at,"submitted": self.submitted,"lines_captured": len(lines),# What this pane is doing, in the two lengths the header needs: one@@ -1070,6 +1127,89 @@ class RestoreResult:return sum(len(s.terminals) for s in self.sessions)+#: How many viewers one pane may feed at once.+#:+#: Generous, because the legitimate number is small (an app window, a browser+#: tab, a second screen) and the point of the cap is not thrift — it is that a+#: client leaking sockets must not grow this list without end. The oldest is+#: dropped, which is also the one least likely to still have a human in front+#: of it.+MAX_WATCHERS = 8+++def _same_viewer(left: Any, right: Any) -> bool:+ """Whether two viewer callbacks are the same one.++ By equality as well as identity: a bound method is a brand new object on+ every attribute access, so ``is`` alone answers "different" for two reads of+ one socket's callback.+ """+ return left is right or left == right+++def _watch(term: Terminal, on_output: Any, on_exit: Any) -> None:+ """Attach a viewer to ``term`` and make it the owner.++ Newest last, and never twice: a socket that re-attaches (a resize, a resume+ retry) replaces its own entry rather than being fed the same bytes twice.+ """+ term.watchers = [w for w in term.watchers if not _same_viewer(w[0], on_output)]+ term.watchers.append((on_output, on_exit))+ if len(term.watchers) > MAX_WATCHERS:+ del term.watchers[0 : len(term.watchers) - MAX_WATCHERS]+ term.viewer_output = on_output+ term.viewer_exit = on_exit+++def _viewers(term: Terminal) -> list[Any]:+ """Every output callback this pane should write to, newest last.++ Falls back to the owner slot alone when nothing registered — a test (or any+ caller) that sets ``viewer_output`` by hand still gets its output.+ """+ if term.watchers:+ return [out for out, _ in term.watchers]+ return [term.viewer_output] if term.viewer_output is not None else []+++def _exit_viewers(term: Terminal) -> list[Any]:+ """The same, for the one-shot "the agent stopped" callback."""+ if term.watchers:+ return [done for _, done in term.watchers if done is not None]+ return [term.viewer_exit] if term.viewer_exit is not None else []+++async def announce_prompt(term: Terminal) -> None:+ """Tell every attached viewer that this pane was just handed a prompt.++ Best-effort by construction, and deliberately so: a viewer that has gone+ away, a socket mid-close, a handler that raises — none of them may cost the+ delivery that already happened. The durable half of the receipt is the+ pane's own ``last_prompt_at``, which every later state read picks up, so a+ notice lost here degrades to "the receipt appears at the next poll" rather+ than to "the user is told nothing".++ A failure is logged rather than swallowed silently: a channel that never+ reaches anyone looks, from the outside, exactly like the bug this exists to+ fix.+ """+ if not term.prompt_viewers:+ return+ payload = {+ "name": term.name,+ "at": term.last_prompt_at,+ "chars": len(term.last_prompt),+ "preview": term.last_prompt[:200],+ "submitted": term.submitted,+ "prompts_sent": term.prompts_sent,+ }+ for notify in list(term.prompt_viewers):+ try:+ await notify(payload)+ except Exception: # noqa: BLE001 - one dead viewer never sinks the others+ logger.debug("Agentic IDE: a prompt notice could not be delivered to a viewer")++class SessionError(RuntimeError):"""A request the registry refuses, with a user-facing English message."""@@ -1820,6 +1960,8 @@ class Registry:term.stopping = True # deliberate kills, not crashed resumesterm.viewer_output = Noneterm.viewer_exit = None+ term.watchers.clear()+ term.prompt_viewers.clear()if manager is not None:for term in session.terminals:if term.pty_id:@@ -2034,8 +2176,11 @@ class Registry:# by this one, so the newest viewer always wins. The one it replaces# may still be TIDYING UP — see ``detach``, which is what stops that# tidy-up from clearing the slot this line just filled.- term.viewer_output = on_output- term.viewer_exit = on_exit+ #+ # Winning the slot is about OWNERSHIP (the size, the handover), not+ # about who may look: a viewer that was here first keeps receiving+ # this pane's output until its own socket goes away.+ _watch(term, on_output, on_exit)term.reattached = Trueterm.stopping = Falseterm.transcript.resize(cols, rows)@@ -2102,8 +2247,7 @@ class Registry:# in the replay buffer belongs to a terminal that no longer exists, and# replaying it to the next viewer would show output from a dead agent.term.replay.clear()- term.viewer_output = on_output- term.viewer_exit = on_exit+ _watch(term, on_output, on_exit)term.reattached = False# This pane is wanted again, so the last deliberate kill is history.term.stopping = False@@ -2131,8 +2275,11 @@ class Registry:term.transcript.feed(text)term.replay.feed(text)term.last_output_at = time.time()- viewer = term.viewer_output- if viewer is not None:+ # To EVERY viewer, not only the newest one. A pane open in two+ # places has two screens and both are supposed to show the same+ # agent; sending to one of them is how a window ends up frozen+ # while the work behind it runs on.+ for viewer in _viewers(term):await viewer(text)async def _closed(_tid: str, code: int) -> None:@@ -2170,8 +2317,7 @@ class Registry:returnterm.status = "exited"term.exit_code = code- viewer = term.viewer_exit- if viewer is not None:+ for viewer in _exit_viewers(term):await viewer(code)# One of a few starts at a time (see COLD_START_LIMIT). The wait covers@@ -2493,20 +2639,38 @@ class Registry:if found is None:returnterm = found[1]+ # This viewer stops receiving output either way — it is the one going+ # away. Done before the ownership check below, because a viewer that was+ # displaced from the slot but is still WATCHING must not keep being+ # written to after its socket closed.+ if viewer is not None:+ term.watchers = [w for w in term.watchers if not _same_viewer(w[0], viewer)]current = term.viewer_output# Compared by equality, not only by identity: a bound method is a brand# new object on every attribute access, so `is` would answer "you are# not the viewer" to the very callback sitting in the slot.if viewer is not None and current is not viewer and current != viewer:- # Somebody else is watching this pane now. Leaving quietly is the- # whole job — the slot belongs to the newer viewer.+ # Somebody else OWNS this pane now. Leaving quietly is the whole job+ # — the slot belongs to the newer viewer.logger.debug("Agentic IDE: a departing viewer left {} to the one that replaced it",term.name,)return+ # The owner is leaving. Whoever else is still attached takes the slot —+ # the pane is not unwatched just because the newest window closed, and+ # handing ownership to a viewer that is still there is what keeps the+ # remaining screen able to set the agent's size.+ #+ # Naming no viewer keeps its original meaning: "nobody is watching this+ # pane", full stop. A teardown says that, and promoting a survivor there+ # would leave a torn-down pane holding callbacks.+ if viewer is not None and term.watchers:+ term.viewer_output, term.viewer_exit = term.watchers[-1]+ returnterm.viewer_output = Noneterm.viewer_exit = None+ term.watchers = []# ------------------------------------------------------------- panesasync def add_terminal(@@ -2800,6 +2964,8 @@ class Registry:term.status = "exited"term.viewer_output = Noneterm.viewer_exit = None+ term.watchers.clear()+ term.prompt_viewers.clear()session.terminals.remove(term)# The recap cache is keyed by pane, and pane keys are reused# (a new "Mika" in the same workspace). Dropping it here is what@@ -2911,6 +3077,10 @@ class Registry:term.prompts_sent += 1term.last_prompt = payload+ # Stamped before anything is announced, so the notice and the state can+ # never disagree about when this happened — and so a viewer that arrives+ # a second later reads the same instant the notice carried.+ term.last_prompt_at = time.time()term.submitted = submittedterm.sent_multiline = multiline and submitted is True# Somebody is driving this pane again, whatever the prompt said. Cleared@@ -2929,6 +3099,11 @@ class Registry:"multi-line" if term.sent_multiline else "one line",payload[:120],)+ # The receipt goes out for every outcome, submitted or not. A prompt+ # sitting unsent in the input box is the case where seeing it matters+ # MOST — that pane looks identical to a working one, and the user is+ # the only one who can push it over the line.+ await announce_prompt(term)return termasync def _write_and_confirm(@@ -3157,6 +3332,60 @@ def terminals_added_event(session: Session, created: list[Terminal], *, source_l)+def workspace_changed_event(+ session: Session | None,+ reason: str,+ *,+ source_layer: str,+ open_workspaces: int | None = None,+) -> Any:+ """The bus event announcing that a WORKSPACE appeared, moved or went away.++ Same shape and the same reasoning as :func:`terminals_added_event`: built+ here so every caller that holds a bus sends an identical payload, and read+ by clients as a trigger to re-fetch rather than as the state itself.++ ``session`` may be None — "closed" is a perfectly good thing to announce,+ and the client needs to hear it most of all.+ """+ from jarvis.core.events import AgenticIdeWorkspaceChanged++ if open_workspaces is None:+ try:+ open_workspaces = len(get_registry().workspaces())+ except Exception: # noqa: BLE001 - a count must never cost the event+ open_workspaces = 0+ return AgenticIdeWorkspaceChanged(+ session_id=session.id if session is not None else "",+ reason=reason,+ folder=session.folder if session is not None else "",+ name=session.name if session is not None else "",+ open_workspaces=open_workspaces,+ source_layer=source_layer,+ )+++def prompt_sent_event(session: Session | None, term: Terminal, *, source_layer: str) -> Any:+ """The bus event announcing that Jarvis typed a prompt into a pane.++ The preview is deliberately short. This exists so a client can SAY that+ something was sent — the prompt itself is already on screen in the pane it+ went to, and putting a full brief on the bus would put it in every event+ log as well.+ """+ from jarvis.core.events import AgenticIdePromptSent++ preview = " ".join((term.last_prompt or "").split())+ return AgenticIdePromptSent(+ session_id=session.id if session is not None else "",+ terminal=term.name,+ agent=term.agent,+ submitted=term.submitted,+ preview=preview[:160],+ source_layer=source_layer,+ )++def coding_mode_active() -> bool:"""Is Jarvis an Agentic IDE right now?@@ -3261,8 +3490,10 @@ __all__ = ["coding_mode_event","get_registry","is_runnable",+ "prompt_sent_event","reset_registry","running_call_signs","sanitize_prompt","terminals_added_event",+ "workspace_changed_event",]diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex dd2928ba3a..8e5a079940 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -10,7 +10,7 @@ from __future__ import annotationsimport timefrom dataclasses import dataclass, fieldfrom enum import StrEnum-from typing import Any, Literal+from typing import Any, Final, Literalfrom uuid import UUID, uuid4from .protocols import HarnessResult, HarnessTask, RiskTier, Transcript@@ -159,6 +159,82 @@ class DictationCompleted(Event):error: str | None = None+#: Every reason a dictation start can be refused. Declared ONCE here, next to+#: the event that carries it, because this value crosses the pipeline, the bus,+#: the REST/WS surface and the UI — the exact shape of drift that has bitten+#: this repo four times (AP-4 / BUG-008). Consumers import this tuple instead+#: of restating the strings.+#:+#: ``microphone_unavailable``+#: The local capture gate is closed — the desktop app is not visible, or+#: microphone permission has not been granted.+#: ``no_stt``+#: No speech-to-text provider is wired, so nothing could transcribe.+#: ``already_running``+#: A dictation is already recording; the second start is a no-op.+#: ``voice_session_active``+#: A voice conversation (wake word or push-to-talk) owns the microphone.+#: ``pipeline_not_running``+#: The speech pipeline has no running event loop to host the session.+DICTATION_REFUSAL_REASONS: Final[tuple[str, ...]] = (+ "microphone_unavailable",+ "no_stt",+ "already_running",+ "voice_session_active",+ "pipeline_not_running",+)+++@dataclass(frozen=True, slots=True)+class DictationStarted(Event):+ """A dictation turn has begun — the counterpart of ``DictationCompleted``.++ Published the moment ``start_dictation()`` commits, BEFORE the first audio+ frame is captured, so a UI surface can show "listening" at key-down speed+ instead of waiting for the first partial transcript (which costs a partial+ interval plus an STT round-trip, and never arrives at all for a short+ press).++ ``target`` is the RAW target the caller asked for (``auto`` | ``insert`` |+ ``chat``); ``auto`` is deliberately resolved when the recording ENDS, not+ here, so the value carried by this event is the request, not the verdict.+ """++ target: str = ""+++@dataclass(frozen=True, slots=True)+class DictationTranscribing(Event):+ """Recording stopped; the final transcription is now running.++ Published when the microphone lease is released — the key was let go, the+ hands-free toggle stopped it, the duration cap expired, or a REST/WS stop+ arrived — and before the closing transcription call. It is the honest+ "no longer listening, not yet finished" phase: a UI surface switches from+ a level meter to a working indicator here, and ``DictationCompleted``+ always follows.+ """+++@dataclass(frozen=True, slots=True)+class DictationRefused(Event):+ """A dictation could NOT start, and the user is owed an explanation.++ Every refusal used to be a ``log.info`` in a file the desktop app cannot+ show (CLAUDE.md §9: the app is a WebView with no dev tools), so pressing+ the dictation shortcut with a closed microphone gate, no STT provider, or+ a live voice session did *nothing* at all. This event makes each refusal+ observable on the bus so the caller can say why the key did nothing.++ ``reason`` is a stable token from ``DICTATION_REFUSAL_REASONS``; ``detail``+ is a complete, user-facing English sentence, matching the contract of+ ``DictationCompleted.detail``.+ """++ reason: str = ""+ detail: str = ""++# ----------------------------------------------------------------------# Intent & Routing# ----------------------------------------------------------------------@@ -452,6 +528,54 @@ class AgenticIdeTerminalsClosed(Event):folder: str = ""+@dataclass(frozen=True, slots=True)+class AgenticIdeWorkspaceChanged(Event):+ """A workspace itself was opened, reopened, switched to, or closed.++ The pane-level events above cover changes INSIDE a grid. This is the layer+ above them, and it was missing: opening a workspace, restoring one after a+ restart, switching tabs and closing a tab all happened in the registry with+ nothing said out loud. Any client that was not the one making the change —+ a second window, a browser tab, the app's own view after the backend+ restored a workspace in the background — kept rendering a grid the backend+ no longer had, and the panes of that grid then knocked at a workspace that+ was not there. Nothing recovered by itself; the user had to reload.++ ``reason`` is one of ``opened`` / ``restored`` / ``activated`` / ``closed``,+ so a client can tell "your tab was switched" from "everything is gone"+ without guessing from the payload. Clients re-read the authoritative state+ on any of them — the event is a trigger, never the source of truth.+ """+ session_id: str = ""+ reason: str = ""+ folder: str = ""+ name: str = ""+ open_workspaces: int = 0+++@dataclass(frozen=True, slots=True)+class AgenticIdePromptSent(Event):+ """A prompt was typed into one pane by Jarvis rather than by the user.++ The only thing that made a voice-driven prompt visible used to be the+ agent's own echo travelling back over that pane's terminal socket. When+ anything on that path was late or missing, the user watched an unchanged+ screen and concluded the instruction had gone nowhere — with no second+ signal anywhere in the app to say otherwise.++ So the fact is announced in its own right. ``submitted`` carries the honest+ three-way answer from ``send_prompt``: true (it went), false (it is sitting+ in the pane's input box), null (never seen to arrive). ``preview`` is a+ short excerpt, never the whole brief — this is a notification, not a copy+ of the prompt.+ """+ session_id: str = ""+ terminal: str = ""+ agent: str = ""+ submitted: bool | None = None+ preview: str = ""++@dataclass(frozen=True, slots=True)class AgenticIdeCodingModeChanged(Event):"""The focused coding mode was switched on or off.diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex d6f131cb31..bbd2dc52fb 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -90,8 +90,10 @@ from jarvis.agentic_ide.session import (agent_argv,coding_mode_event,get_registry,+ prompt_sent_event,sanitize_prompt,terminals_added_event,+ workspace_changed_event,)from jarvis.agentic_ide.terminal_input import is_terminal_report_only@@ -133,6 +135,35 @@ async def _announce_coding_mode(request: Request) -> None:except Exception as exc: # noqa: BLE001 - notification is not the worklog.debug("AgenticIdeCodingModeChanged publish failed: %s", exc)++async def _announce_workspace(request: Request, session: object | None, reason: str) -> None:+ """Tell every connected client that a workspace opened, moved or closed.++ The companion to ``_announce_coding_mode``, and it exists for a failure that+ one could not cover: the mode event drives a badge, while THIS drives the+ grid. A workspace opened by voice, restored after a restart, or closed in+ another window changed nothing on a screen that was not the one doing it —+ the panes on it went on knocking at a workspace that had been replaced, and+ the only way back was a reload.++ Same contract as its neighbour: best-effort (AP-18), read back from the+ registry, a trigger rather than a source of truth.+ """+ bus = getattr(request.app.state, "bus", None)+ if bus is None:+ return+ try:+ await bus.publish(+ workspace_changed_event(+ session, # type: ignore[arg-type]+ reason,+ source_layer="agentic_ide_routes",+ )+ )+ except Exception as exc: # noqa: BLE001 - notification is not the work+ log.debug("AgenticIdeWorkspaceChanged publish failed: %s", exc)++# One system folder window at a time — see ``open_native_picker``._native_picker_lock = asyncio.Lock()@@ -769,6 +800,34 @@ class RecapsResponse(BaseModel):terminals: list[TerminalRecap] = Field(default_factory=list)+class LastPrompt(BaseModel):+ """The exact text a pane was last handed — the receipt, in full.++ Its own request rather than a field of the workspace state, and that split+ is deliberate: a composed brief runs to several thousand characters, and+ carrying every pane's copy in every poll was measured as waste worth+ removing. What the state keeps is the SHORT half (an excerpt, a length, a+ timestamp), which is enough to render the receipt; this is what the user+ gets when they click it open, and it is the only claim that can be checked+ word for word against what the agent was told.+ """++ name: str+ text: str = Field(description="The prompt as it was written into the pane, unabridged.")+ chars: int = Field(default=0, description="Length of ``text``.")+ at: float | None = Field(+ default=None, description="When it was delivered (epoch seconds); null if none was."+ )+ submitted: bool | None = Field(+ default=None,+ description=(+ "True when the agent accepted it and started, false when it is still "+ "sitting in the pane's input box, null when it could not be confirmed."+ ),+ )+ prompts_sent: int = Field(default=0, description="How many prompts this pane has been sent.")++class RecapEdit(BaseModel):"""A recap the user is writing for one pane themselves."""@@ -1077,6 +1136,7 @@ async def activate_workspace(request: Request, req: ActivateWorkspaceRequest) -># Each workspace carries its own coding mode, so bringing a different one to# the front can change the answer without anyone touching the toggle.await _announce_coding_mode(request)+ await _announce_workspace(request, session, "activated")return {"ok": True,"active_id": session.id if session else None,@@ -1101,7 +1161,7 @@ async def rename_workspace(workspace_id: str, req: RenameWorkspaceRequest) -> di@router.post("/session", summary="Open an Agentic-IDE workspace")-async def start_session(req: StartSessionRequest) -> dict:+async def start_session(request: Request, req: StartSessionRequest) -> dict:"""Open ``folder`` as another workspace, with one terminal per request entry.Whatever is already open STAYS open with its agents running — this adds a@@ -1130,6 +1190,10 @@ async def start_session(req: StartSessionRequest) -> dict:)except Exception: # noqa: BLE001 - history must never block opening a folderlog.warning("Agentic IDE recent-folder history was not updated", exc_info=True)+ # Every other window has to hear this. One of them may be showing the grid+ # of a workspace this one just replaced at the front, and a grid nobody+ # corrects is a grid whose panes attach to the wrong workspace.+ await _announce_workspace(request, session, "opened")return {"ok": True, "session": session.to_dict(), "state": get_registry().state()}@@ -1149,6 +1213,7 @@ async def end_session(request: Request) -> dict:# Closing the front workspace ends its coding mode — or hands it to whichever# workspace takes the front, which may have a different one.await _announce_coding_mode(request)+ await _announce_workspace(request, get_registry().session, "closed")return {"ok": True, "closed": closed, "state": get_registry().state()}@@ -1172,6 +1237,7 @@ async def close_workspace(request: Request, workspace_id: str) -> dict:raise HTTPException(status_code=404, detail="That workspace is not open.")await registry.end(workspace_id)await _announce_coding_mode(request)+ await _announce_workspace(request, registry.session, "closed")return {"ok": True, "closed": workspace_id, "state": registry.state()}@@ -1222,7 +1288,7 @@ async def get_resume_offer() -> ResumeOffer:@router.post("/resume", summary="Reopen the last Agentic-IDE workspace")-async def resume_workspace() -> dict:+async def resume_workspace(request: Request) -> dict:"""Reopen everything that was open: same panes, same places, same coding CLIs.Every workspace in the restore point, not just whichever was on screen —@@ -1281,6 +1347,12 @@ async def resume_workspace() -> dict:],)total_panes = result.terminal_count+ # A restore is the transition most likely to happen while nobody is looking+ # — it is what follows an app restart — so it is also the one a client is+ # most likely to miss. Reopened workspaces carry NEW ids, which means a view+ # that keeps the old ones has panes addressing workspaces that no longer+ # exist; saying so here is what turns that into a re-fetch.+ await _announce_workspace(request, registry.session, "restored")return {"ok": True,"state": registry.state(),@@ -1765,6 +1837,38 @@ async def refresh_terminal_recap(name: str, workspace_id: str | None = None) ->return _recap_row(term, summary)+ "/terminals/{name}/prompt",+ response_model=LastPrompt,+ summary="The exact prompt a terminal was last sent",+)+async def get_last_prompt(name: str, workspace_id: str | None = None) -> LastPrompt:+ """What terminal ``name`` was last told to do, word for word.++ This is the proof half of a delivery. Jarvis composes a brief, types it+ into a pane and says it did — and until this existed, the only evidence was+ the pane's own screen, which is exactly what is missing in every case worth+ checking: a pane that had parked its output, an emulator that never+ painted, a socket that reconnected a moment later, a CLI that redrew its+ input box without the text ever scrolling into view. "I sent it" and "you+ can read what I sent" are different claims, and only the second one can be+ verified by the person who has to trust it.++ Answers for a pane that has never been sent anything too, with an empty+ ``text`` and a null ``at`` — "nothing was sent here" is itself an answer,+ and a 404 would read as "no such pane".+ """+ term, _session = _pane_for_recap(name, workspace_id)+ return LastPrompt(+ name=term.name,+ text=term.last_prompt,+ chars=len(term.last_prompt),+ at=term.last_prompt_at,+ submitted=term.submitted,+ prompts_sent=term.prompts_sent,+ )++@router.get("/terminals/{name}/report", summary="What one terminal is doing")async def terminal_report(name: str, lines: int = 40) -> dict:"""Status plus the recent readable output of the terminal called ``name``."""@@ -2015,6 +2119,11 @@ async def fanout(request: Request, req: FanOutRequest) -> dict:if registry.session is None:raise HTTPException(status_code=409, detail="No Agentic-IDE session is running.")+ # Bound once, up here: the announcements at the end of this route apply to+ # every fan-out, and the fleet path that briefs EXISTING panes never enters+ # the spawn branch below.+ bus = getattr(request.app.state, "bus", None)+created: list = []if req.spawn:for group in req.spawn:@@ -2027,7 +2136,6 @@ async def fanout(request: Request, req: FanOutRequest) -> dict:created.extend(opened)if capped:break- bus = getattr(request.app.state, "bus", None)session = registry.sessionif session is not None and bus is not None and created:try:@@ -2102,6 +2210,22 @@ async def fanout(request: Request, req: FanOutRequest) -> dict:instruction=req.instruction,assignments=assignments,)+ # One announcement per pane that was actually briefed — the fleet path is+ # where a spoken "prompt terminal two and three" lands, and it is exactly+ # the path where the user has no other way of knowing it happened: they are+ # talking, not looking at a prompt bar. See the same publish in+ # ``terminal_prompt`` for why the pane's own echo is not enough.+ if bus is not None and session is not None:+ for delivery in result.delivered:+ term = session.find(delivery.terminal)+ if term is None:+ continue+ try:+ await bus.publish(+ prompt_sent_event(session, term, source_layer="agentic_ide_routes")+ )+ except Exception as exc: # noqa: BLE001 - notification is not the work+ log.debug("AgenticIdePromptSent publish failed: %s", exc)return {"ok": result.all_delivered,"dry_run": False,@@ -2176,7 +2300,7 @@ def _unknown_terminal_detail(registry: object, wanted: str) -> str:@router.post("/terminals/{name}/prompt", summary="Send a prompt to one terminal")-async def terminal_prompt(name: str, req: PromptRequest) -> dict:+async def terminal_prompt(request: Request, name: str, req: PromptRequest) -> dict:"""Type ``prompt`` into the terminal called ``name`` and press Enter.With ``compose=true`` the text is first rewritten into a prompt worth@@ -2261,6 +2385,26 @@ async def terminal_prompt(name: str, req: PromptRequest) -> dict:term = await registry.send_prompt(name, text)except SessionError as exc:raise HTTPException(status_code=409, detail=str(exc)) from exc++ # Say out loud that a prompt went in.+ #+ # Until now the ONLY sign was the agent echoing it back down that pane's own+ # terminal socket — one path, with no second opinion anywhere in the app. So+ # whenever that path was interrupted (a viewer that had lost its pane, a+ # window that was not looking, a socket in the middle of a slow reconnect)+ # the user was told the prompt had been sent and watched a screen where+ # nothing whatsoever happened, which reads as "it did nothing" (reported+ # 2026-07-28). This event is independent of the pane: it arrives on the app+ # socket every client already holds.+ bus = getattr(request.app.state, "bus", None)+ if bus is not None:+ try:+ await bus.publish(+ prompt_sent_event(found[0], term, source_layer="agentic_ide_routes")+ )+ except Exception as exc: # noqa: BLE001 - notification is not the work+ log.debug("AgenticIdePromptSent publish failed: %s", exc)+# `submitted` is the honest part of this answer, and it has THREE states:# True the agent accepted the prompt and started, False the text is provably# still in its input box, null the pane never visibly took it and no claim@@ -2354,12 +2498,63 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:except Exception: # noqa: BLE001, S110 - viewer gonepass+ async def on_prompt(notice: dict) -> None:+ """This pane was just handed a prompt — tell the viewer outright.++ The alternative is what every earlier version relied on: let the user+ recognise the delivery in the agent's own output. That reliably fails+ in the states nobody can see from here — a parked pane, an emulator+ that has not painted, a socket that reconnected a moment ago, or a CLI+ that redraws its input box without the text ever scrolling into view.+ The user is then told the brief was sent and looks at a pane where+ nothing happened, which is indistinguishable from Jarvis making it up.++ Lossy on purpose: a viewer that is not connected in this instant misses+ it and picks the same receipt up from ``last_prompt_at`` on its next+ state read. This channel buys immediacy, not delivery.+ """+ async with send_lock:+ try:+ await ws.send_json({"t": "prompt", **notice})+ except Exception: # noqa: BLE001, S110 - viewer gone; the state still carries it+ pass+# Pin the workspace ONCE, before anything is attached. A client that sent no# id means "the one showing right now", and that has to be resolved here# rather than on every later message: the front workspace can change while# this socket is open, and a keystroke must keep going to the pane it was# typed into.pinned = registry.get(workspace_id)+ if workspace_id and pinned is None and registry.get(None) is not None:+ # **A pane whose workspace is gone must not land in a different one.**+ #+ # Call-signs are positional: every workspace numbers its panes from T1.+ # So a socket still holding a closed workspace's id used to resolve+ # against whatever is at the FRONT now and attach to a stranger's T2 —+ # in another folder, run by another agent. And because attaching makes+ # you the owner, it took that pane's output away from the window the+ # user was actually looking at, which then sat frozen until it was+ # reloaded (measured 2026-07-28: a leftover tab from before an app+ # restart quietly took over four live panes, and a prompt typed into+ # them appeared nowhere).+ #+ # Answering "that workspace is gone" instead lets the client do the one+ # correct thing: re-read the state and come back with the grid that+ # exists. Distinguished from the 4503 above on purpose — nothing is+ # coming back here, so waiting would be waiting for nothing.+ log.info(+ "Agentic IDE: %r asked for workspace %s, which is closed — telling it to re-read",+ name,+ workspace_id,+ )+ await ws.send_json(+ {+ "t": "error",+ "message": "That workspace was closed — reloading the terminals.",+ }+ )+ await ws.close(code=4409, reason="stale workspace")+ returnpane_workspace = pinned.id if pinned is not None else Nonetry:@@ -2414,9 +2609,24 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:# workspaces are switched between — saying "started a new# conversation" there would be plainly false."reattached": term.reattached,+ # What this pane was last told to do, and when — handed over with+ # the handshake so a viewer that arrives AFTER the prompt (a+ # reload, a reconnect, a second window opened later) still shows+ # the receipt. Without it the proof would exist only for whoever+ # happened to be connected in that one instant, which is precisely+ # the user who did not need proving to.+ "last_prompt_at": term.last_prompt_at,+ "last_prompt_chars": len(term.last_prompt),+ "last_prompt_preview": term.last_prompt[:200],+ "submitted": term.submitted,})+ # Register only once the handshake is out. A notice arriving before the+ # pane knows its own name would be dropped by the client as belonging to+ # nothing, and the state read that follows would then be its first hint.+ term.prompt_viewers.append(on_prompt)+try:while True:try:@@ -2472,6 +2682,14 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:# and releasing it then would leave a live agent painting into nothing# (BUG-113).registry.detach(term.key, pane_workspace, viewer=on_output)+ # Unregistered by identity for the same reason: a pane open in two+ # windows has two notice channels, and removing "the last one" would+ # silence the window that is still watching. Guarded because the pane+ # may already have been torn down (closing a workspace clears these).+ try:+ term.prompt_viewers.remove(on_prompt)+ except ValueError:+ passdef _safe_int(value: object, default: int) -> int:diff --git a/jarvis/ui/web/frontend/src/__tests__/ws.test.ts b/jarvis/ui/web/frontend/src/__tests__/ws.test.tsindex 2de40dbfe0..e94ed1c8a1 100644--- a/jarvis/ui/web/frontend/src/__tests__/ws.test.ts+++ b/jarvis/ui/web/frontend/src/__tests__/ws.test.ts@@ -216,4 +216,56 @@ describe("WSClient", () => {}});});+ describe("a socket that stops carrying anything", () => {+ // The app-wide freeze. Every live update in Jarvis rides this one socket,+ // and a half-open connection — the peer gone without a FIN, which is what a+ // sleep, a network change or a killed backend leaves behind — keeps+ // `readyState` at OPEN and never fires `close`. Nothing reconnected, the+ // UI kept claiming it was connected, and only a reload brought it back.+ it("replaces itself after two missed pings", async () => {+ vi.useFakeTimers();+ try {+ const onClose = vi.fn();+ const client = new WSClient({ onClose });+ client.connect();+ await Promise.resolve();+ const dead = MockWebSocket.last;+ expect(dead).toBeTruthy();++ // Time passes; the socket answers nothing. The pings go out into it.+ await vi.advanceTimersByTimeAsync(30_000 * 3);++ expect(dead!.close).toHaveBeenCalled();+ expect(onClose).toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(500);+ expect(MockWebSocket.last).not.toBe(dead);+ client.close();+ } finally {+ vi.useRealTimers();+ }+ });++ it("leaves a socket alone while it is still answering", async () => {+ vi.useFakeTimers();+ try {+ const client = new WSClient({});+ client.connect();+ await Promise.resolve();+ const live = MockWebSocket.last;++ for (let i = 0; i < 4; i += 1) {+ await vi.advanceTimersByTimeAsync(30_000);+ // The backend's answer to the ping — the only frame an idle but+ // healthy connection produces, and therefore the evidence.+ live!.deliver({ type: "pong", payload: {} });+ }++ expect(live!.close).not.toHaveBeenCalled();+ expect(MockWebSocket.last).toBe(live);+ client.close();+ } finally {+ vi.useRealTimers();+ }+ });+ });});diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.ts b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.tsindex 7bb2142c37..3d96d8bac7 100644--- a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.ts@@ -59,6 +59,7 @@ function handlers() {onReady: vi.fn(),onExit: vi.fn(),onTrouble: vi.fn(),+ onPrompt: vi.fn(),};}@@ -326,3 +327,175 @@ describe("openPaneSocket", () => {socket.close();});});++/*+ * A delivered prompt travels on a frame of its own instead of being left to be+ * recognised in the agent's output. The output is exactly what goes missing in+ * the cases that matter — a parked pane, an unpainted emulator, a socket that+ * was reconnecting — and each time the user was told a brief had been sent and+ * had no way to check.+ */+describe("openPaneSocket delivery receipts", () => {+ const originalWs = globalThis.WebSocket;++ beforeEach(() => {+ (globalThis as unknown as { WebSocket: unknown }).WebSocket = MockWebSocket;+ (globalThis as unknown as { window: unknown }).window = globalThis;+ (window as unknown as { location: unknown }).location = {+ protocol: "http:",+ host: "localhost:5173",+ };+ MockWebSocket.last = null;+ MockWebSocket.opened = [];+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ (globalThis as unknown as { WebSocket: unknown }).WebSocket = originalWs;+ });++ it("reports a prompt the moment the server says it landed", () => {+ const cb = handlers();+ const socket = openPaneSocket({ name: "Mika", cols: 80, rows: 24 }, cb);+ MockWebSocket.last!.fire("open");++ MockWebSocket.last!.deliver({+ t: "prompt",+ at: 1_700_000_000,+ chars: 2_400,+ preview: "## Task\nReview the ranking pipeline",+ submitted: true,+ prompts_sent: 2,+ });++ expect(cb.onPrompt).toHaveBeenCalledWith({+ at: 1_700_000_000,+ chars: 2_400,+ text: "## Task\nReview the ranking pipeline",+ submitted: true,+ prompts_sent: 2,+ });+ socket.close();+ });++ it("hands over the prompt that arrived BEFORE this socket existed", () => {+ // The viewer with real reason to doubt a delivery is the one that was not+ // connected when it happened — a reload, a reconnect, a second window.+ const cb = handlers();+ const socket = openPaneSocket({ name: "Mika", cols: 80, rows: 24 }, cb);+ MockWebSocket.last!.fire("open");++ MockWebSocket.last!.deliver({+ t: "ready",+ resumed: false,+ reattached: true,+ last_prompt_at: 1_700_000_000,+ last_prompt_chars: 900,+ last_prompt_preview: "Refactor the parser",+ submitted: false,+ });++ expect(cb.onReady).toHaveBeenCalledWith({+ resumed: false,+ reattached: true,+ lastPrompt: {+ at: 1_700_000_000,+ chars: 900,+ text: "Refactor the parser",+ submitted: false,+ prompts_sent: 0,+ },+ });+ socket.close();+ });++ it("reports no prior prompt as null rather than as a delivery at time zero", () => {+ const cb = handlers();+ const socket = openPaneSocket({ name: "Mika", cols: 80, rows: 24 }, cb);+ MockWebSocket.last!.fire("open");++ MockWebSocket.last!.deliver({ t: "ready", resumed: false, reattached: false });++ expect(cb.onReady).toHaveBeenCalledWith({+ resumed: false,+ reattached: false,+ lastPrompt: null,+ });+ socket.close();+ });++ it("survives a client that registered no prompt handler", () => {+ // `onPrompt` is optional so an older embedder keeps working; an unhandled+ // frame must not take the pane's whole message loop down with it.+ const cb = handlers();+ const socket = openPaneSocket(+ { name: "Mika", cols: 80, rows: 24 },+ { ...cb, onPrompt: undefined },+ );+ MockWebSocket.last!.fire("open");++ MockWebSocket.last!.deliver({ t: "prompt", at: 1, chars: 3, preview: "hi" });+ MockWebSocket.last!.deliver({ t: "o", d: "still alive" });++ expect(cb.onOutput).toHaveBeenCalledWith("still alive");+ socket.close();+ });+ it("asks the view to re-read when its workspace has been closed", () => {+ // The leftover-window case (2026-07-28). Retrying cannot help and waiting+ // is waiting for nothing: what the pane is holding no longer exists, so the+ // only useful move is to make the view fetch the grid that does.+ const asked = vi.fn();+ window.addEventListener("jarvis:agentic-ide-changed", asked);+ const cb = handlers();+ const socket = openPaneSocket(+ { name: "T1", cols: 80, rows: 24, workspaceId: "ide_gone" },+ cb,+ );++ MockWebSocket.last!.dropped(4409);+ vi.advanceTimersByTime(60_000);++ expect(asked).toHaveBeenCalled();+ expect(MockWebSocket.opened).toHaveLength(1);+ window.removeEventListener("jarvis:agentic-ide-changed", asked);+ socket.close();+ });++ it("asks the view to re-read when the open workspace has no such pane", () => {+ // A pane the workspace does not have means the GRID is out of date — this+ // pane is merely where it became visible. Without the re-read it stays on+ // screen as a dead rectangle for the rest of the session.+ const asked = vi.fn();+ window.addEventListener("jarvis:agentic-ide-changed", asked);+ const cb = handlers();+ const socket = openPaneSocket({ name: "T6", cols: 80, rows: 24 }, cb);++ MockWebSocket.last!.dropped(4404);++ expect(asked).toHaveBeenCalled();+ expect(cb.onTrouble).toHaveBeenCalledWith(expect.any(String), false);+ window.removeEventListener("jarvis:agentic-ide-changed", asked);+ socket.close();+ });++ it("re-reads the state once before settling into the slow knock", async () => {+ // Nine "not yet" answers is the moment a pane drops to one attempt every+ // half minute. A workspace that opened meanwhile announces itself — but an+ // announcement missed while this socket was reconnecting would then take+ // thirty seconds to be noticed, or never.+ const asked = vi.fn();+ window.addEventListener("jarvis:agentic-ide-changed", asked);+ const cb = handlers();+ const socket = openPaneSocket({ name: "T1", cols: 80, rows: 24 }, cb);++ for (let i = 0; i < 9; i += 1) {+ MockWebSocket.last!.dropped(4503);+ await vi.advanceTimersByTimeAsync(30_000);+ }++ expect(asked).toHaveBeenCalledTimes(1);+ window.removeEventListener("jarvis:agentic-ide-changed", asked);+ socket.close();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.tsindex 1701b2c23a..77f2eeefc7 100644--- a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts@@ -63,6 +63,34 @@ const CLOSE_NO_SUCH_PANE = 4404;* workspace of terminals gave up for good (BUG-113).*/const CLOSE_NOT_READY = 4503;+/**+ * Server close code: this pane's workspace is closed, and another one is open.+ *+ * The third verdict, and the one that used to be missing. "Not here" and "not+ * yet" both assume the client's picture of the world is right; this one says it+ * is out of date. Retrying cannot fix that and neither can waiting — the answer+ * is to go and re-read which workspace is open, which is what+ * {@link WORKSPACE_CHANGED_EVENT} asks the view to do.+ */+const CLOSE_STALE_WORKSPACE = 4409;++/**+ * The window event the Agentic-IDE view re-fetches its whole state on.+ *+ * Dispatched from here as well as from the app's WebSocket, because a pane is+ * often the FIRST place a divergence shows up: the view still believes in a+ * grid the backend no longer has, and the only component that finds out is the+ * socket being turned away.+ */+const WORKSPACE_CHANGED_EVENT = "jarvis:agentic-ide-changed";++/** Ask the view to re-read the workspace state. Safe to call more than once. */+function askForFreshState(reason: string): void {+ if (typeof window === "undefined") return;+ window.dispatchEvent(+ new CustomEvent(WORKSPACE_CHANGED_EVENT, { detail: { reason } }),+ );+}const MIN_BACKOFF = 500;const MAX_BACKOFF = 8_000;@@ -117,12 +145,47 @@ export interface PaneSocketOptions {appearance?: string | null;}+/**+ * A pane was handed a prompt: what was sent, when, and whether it started.+ *+ * Carried on its own frame rather than left to be recognised in the agent's+ * output, because the output is what goes missing in every case where this+ * matters — see the server's `on_prompt` for the list. `text` is an excerpt;+ * the unabridged prompt is one request away (`getLastPrompt`), which keeps a+ * multi-thousand-character brief off a channel that is otherwise keystrokes.+ */+export interface PromptDelivery {+ /** Epoch SECONDS, as the server stamps it. */+ at: number | null;+ /** Full length of the delivered prompt, not of `text`. */+ chars: number;+ /** The opening of the prompt — enough for a receipt line. */+ text: string;+ /** True = the agent started; false = still in its input box; null = unknown. */+ submitted: boolean | null;+ prompts_sent: number;+}+export interface PaneSocketHandlers {/** The socket is up; the pane may send its measured size. */onOpen?: () => void;onOutput: (text: string) => void;- /** The agent is attached — freshly started, resumed, or re-joined. */- onReady: (info: { resumed: boolean; reattached: boolean }) => void;+ /**+ * The agent is attached — freshly started, resumed, or re-joined.+ *+ * `lastPrompt` is what this pane was told to do BEFORE this socket existed,+ * handed over with the handshake. It is what lets a reload, a reconnect or a+ * second window show the receipt for a prompt they were not connected for —+ * which is the viewer that most needs it, since the one who watched it+ * arrive never doubted it.+ */+ onReady: (info: {+ resumed: boolean;+ reattached: boolean;+ lastPrompt: PromptDelivery | null;+ }) => void;+ /** This pane was handed a prompt just now. */+ onPrompt?: (delivery: PromptDelivery) => void;/** The agent itself finished. Final: nothing reconnects after this. */onExit: (code: number) => void;/**@@ -246,10 +309,26 @@ export function openPaneSocket(};const handleDrop = (code: number) => {+ if (code === CLOSE_STALE_WORKSPACE) {+ // Not this pane's fault and not worth a red badge: the view is simply+ // showing a workspace that has been closed. Stop, and ask for the real+ // one — the grid that comes back brings its own panes with it.+ stopped = true;+ handlers.onTrouble("This workspace was closed — reloading…", true);+ askForFreshState("stale-workspace");+ return;+ }if (code === CLOSE_NO_SUCH_PANE) {// The server is not saying "not right now", it is saying "not here".// No number of retries turns that into a terminal.giveUp("This terminal is no longer part of the open workspace.");+ // A pane that the open workspace does not have means the grid on screen+ // is out of date — one pane is merely where that became visible. Left+ // alone it stays visible as a dead rectangle for the rest of the session+ // (measured 2026-07-28: two panes from a six-pane workspace kept knocking+ // at a four-pane one for minutes). Re-reading the state is what removes+ // it, and it costs one request.+ askForFreshState("no-such-pane");return;}if (code === CLOSE_NOT_READY) {@@ -261,6 +340,13 @@ export function openPaneSocket(// of an hour later still finds its panes waiting.waits += 1;handlers.onTrouble("Waiting for the workspace to come back…", true);+ // Before settling into the slow knock, ask once whether the world still+ // looks the way this pane thinks it does. A workspace that opened while+ // the panes were waiting announces itself, but a pane that has already+ // dropped to one attempt every half minute would take that long to+ // notice — and an announcement missed for any reason (a socket that was+ // reconnecting, a window that was hidden) would never be noticed at all.+ if (waits === MAX_ATTEMPTS + 1) askForFreshState("waited-out");schedule(waits > MAX_ATTEMPTS? IDLE_BACKOFF@@ -300,7 +386,22 @@ export function openPaneSocket(});socket.addEventListener("message", (ev) => {- let msg: { t?: string; d?: string; code?: number; message?: string; resumed?: boolean; reattached?: boolean };+ let msg: {+ t?: string;+ d?: string;+ code?: number;+ message?: string;+ resumed?: boolean;+ reattached?: boolean;+ at?: number | null;+ chars?: number;+ preview?: string;+ submitted?: boolean | null;+ prompts_sent?: number;+ last_prompt_at?: number | null;+ last_prompt_chars?: number;+ last_prompt_preview?: string;+ };try {msg = JSON.parse((ev as MessageEvent).data as string);} catch {@@ -317,6 +418,27 @@ export function openPaneSocket(handlers.onReady({resumed: Boolean(msg.resumed),reattached: Boolean(msg.reattached),+ // Only when this pane has actually been sent something. A null here+ // means "nothing was ever delivered", which the receipt must not+ // render as a delivery with a missing timestamp.+ lastPrompt:+ typeof msg.last_prompt_at === "number"+ ? {+ at: msg.last_prompt_at,+ chars: msg.last_prompt_chars ?? 0,+ text: msg.last_prompt_preview ?? "",+ submitted: msg.submitted ?? null,+ prompts_sent: 0,+ }+ : null,+ });+ } else if (msg.t === "prompt") {+ handlers.onPrompt?.({+ at: typeof msg.at === "number" ? msg.at : null,+ chars: msg.chars ?? 0,+ text: msg.preview ?? "",+ submitted: msg.submitted ?? null,+ prompts_sent: msg.prompts_sent ?? 0,});} else if (msg.t === "exit") {agentExited = true;diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.tsindex 5a4f3a6cf4..79efa95e48 100644--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts@@ -258,7 +258,14 @@ export function useWebSocket(): void {if (env.event_name === "AgenticIdeTerminalsAdded" ||- env.event_name === "AgenticIdeTerminalsClosed"+ env.event_name === "AgenticIdeTerminalsClosed" ||+ // A whole workspace opened, was restored after a restart, came to the+ // front, or closed. Same treatment as a pane change and for a+ // stronger reason: a view holding a workspace that no longer exists+ // has panes that connect to nothing, so it does not merely look+ // stale — it stops working, and until this event existed nothing but+ // a reload told it (2026-07-28).+ env.event_name === "AgenticIdeWorkspaceChanged") {// Panes were changed by voice or the CLI. The workspace view loads its// state once on mount, so without this it would keep showing the old@@ -270,6 +277,28 @@ export function useWebSocket(): void {);}+ if (env.event_name === "AgenticIdePromptSent") {+ // Jarvis typed an instruction into a pane. The pane will show it as+ // the agent echoes it back, but that is one path and the user is+ // usually not looking at it while speaking — so the fact is stated+ // here too, on the socket every screen already holds.+ const p = env.payload as {+ terminal?: string;+ submitted?: boolean | null;+ };+ if (typeof p.terminal === "string" && p.terminal.length > 0) {+ pushToast(+ p.submitted === true ? "success" : "warning",+ p.submitted === true+ ? `${translate("use_web_socket.prompt_sent")} ${p.terminal}`+ : `${p.terminal}: ${translate("use_web_socket.prompt_not_submitted")}`,+ );+ window.dispatchEvent(+ new CustomEvent("jarvis:agentic-ide-prompt", { detail: p }),+ );+ }+ }+if (env.event_name === "AgenticIdeCodingModeChanged") {// Coding mode changes how Jarvis answers on EVERY screen, so the// app-wide indicator has to hear about a switch made anywhere — bydiff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 89c95e8fd9..37fddba1ea 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -2556,7 +2556,9 @@"no_tools_explainer": "Sobald der {name}-Agent-Worker ein Tool triggert (z. B. dispatch_to_harness, run_shell, screenshot), erscheint es hier als Icon-Node."},"use_web_socket": {- "jarvis_opened": "{name} öffnete"+ "jarvis_opened": "{name} öffnete",+ "prompt_sent": "Prompt gesendet an",+ "prompt_not_submitted": "der Prompt steht im Eingabefeld, abgeschickt wurde er nicht"},"chat_thread": {"message_to": "Nachricht an",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 9b2437fd8b..33b8b19304 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -2557,7 +2557,9 @@"no_tools_explainer": "As soon as the {name}-Agent worker triggers a tool (e.g. dispatch_to_harness, run_shell, screenshot), it appears here as an icon node."},"use_web_socket": {- "jarvis_opened": "{name} opened"+ "jarvis_opened": "{name} opened",+ "prompt_sent": "Prompt sent to",+ "prompt_not_submitted": "the prompt is in its input box, not sent"},"chat_thread": {"message_to": "Message to",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 911c7caa02..28b3259fb6 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -2556,7 +2556,9 @@"no_tools_explainer": "En cuanto el {name}-Agent worker activa una herramienta (p. ej. dispatch_to_harness, run_shell, screenshot), aparece aquí como un nodo de icono."},"use_web_socket": {- "jarvis_opened": "{name} abrió"+ "jarvis_opened": "{name} abrió",+ "prompt_sent": "Prompt enviado a",+ "prompt_not_submitted": "el prompt está en su campo de entrada, no se envió"},"chat_thread": {"message_to": "Mensaje a",diff --git a/jarvis/ui/web/frontend/src/lib/ws.ts b/jarvis/ui/web/frontend/src/lib/ws.tsindex 23fb4c0ac1..28cdc363bf 100644--- a/jarvis/ui/web/frontend/src/lib/ws.ts+++ b/jarvis/ui/web/frontend/src/lib/ws.ts@@ -61,6 +61,28 @@ const MIN_BACKOFF = 500;const MAX_BACKOFF = 10_000;const PING_INTERVAL = 30_000;+/**+ * How long an OPEN socket may stay completely silent before it is declared+ * dead and replaced.+ *+ * A ping that nothing checks is decoration. The failure it has to catch is the+ * half-open socket: the peer is gone (the machine slept, the network changed,+ * the backend was killed rather than closed) but no FIN ever arrived, so+ * `readyState` stays OPEN, no `close` event fires, and the reconnect below is+ * never scheduled. Every live update in the app rides this one socket, so the+ * whole UI then freezes while claiming to be connected — and only a reload+ * brings it back. That is precisely the "nothing happens until I reload"+ * report.+ *+ * The backend answers every ping with a pong, so an idle-but-healthy socket+ * still produces a frame every {@link PING_INTERVAL}. Two and a half intervals+ * of total silence is therefore two missed answers, not a slow moment — and+ * generous enough that a hidden window's clamped timer (Chromium stretches+ * `setInterval` to about once a minute in a document nobody is looking at)+ * cannot trip it on its own.+ */+const SILENCE_LIMIT = PING_INTERVAL * 2.5;+export class WSClient {private ws: WebSocket | null = null;private backoff = MIN_BACKOFF;@@ -70,6 +92,9 @@ export class WSClient {private lastCloseCode: number | undefined;private pendingTicket: string | null = null;private authRetryStreak = 0;+ /** When the last frame of any kind arrived — the liveness evidence. */+ private lastFrameAt = 0;+ private wakeListening = false;private readonly url: string;private readonly onMessage?: WSHandler;private readonly onOpen?: () => void;@@ -91,9 +116,90 @@ export class WSClient {connect(): void {this.stopped = false;+ this.listenForWake();this.openSocket();}+ /**+ * Two events that are better evidence than any timer: the window came back,+ * and the machine is on a network again.+ *+ * Both mean the socket may have died unnoticed while nobody could tell — a+ * laptop that slept, a Wi-Fi that changed, a window that sat behind an editor+ * for an hour with its timers clamped to a crawl. Checking here is what turns+ * "frozen until the user reloads" into "live again the moment they look".+ */+ private listenForWake(): void {+ if (this.wakeListening || typeof window === "undefined") return;+ this.wakeListening = true;+ window.addEventListener("online", this.wake);+ if (typeof document !== "undefined") {+ document.addEventListener("visibilitychange", this.wake);+ }+ }++ private stopListeningForWake(): void {+ if (!this.wakeListening || typeof window === "undefined") return;+ this.wakeListening = false;+ window.removeEventListener("online", this.wake);+ if (typeof document !== "undefined") {+ document.removeEventListener("visibilitychange", this.wake);+ }+ }++ /**+ * Reconnect NOW rather than at the end of whatever wait is running.+ *+ * An arrow property so it can be added and removed as a listener by+ * identity. Deliberately does nothing while the document is hidden: this is+ * about the moment attention returns, and a background tab has no reason to+ * hurry.+ */+ private readonly wake = (): void => {+ if (this.stopped) return;+ if (typeof document !== "undefined" && document.hidden) return;+ if (this.ws?.readyState === WebSocket.OPEN) {+ // Open, but is it alive? A socket that has been silent past the limit is+ // the half-open case — replace it instead of trusting readyState.+ if (this.lastFrameAt > 0 && Date.now() - this.lastFrameAt > SILENCE_LIMIT) {+ this.dropDeadSocket();+ }+ return;+ }+ if (this.ws?.readyState === WebSocket.CONNECTING) return;+ // A wait that was scheduled while the window was hidden has been stretched+ // by an unknown amount and may still be minutes out. Being looked at is+ // fresh evidence: start over at the fast end of the backoff, now.+ if (this.reconnectTimer) {+ clearTimeout(this.reconnectTimer);+ this.reconnectTimer = null;+ }+ this.backoff = MIN_BACKOFF;+ this.openSocket();+ };++ /**+ * Give up on a socket that is open but no longer carrying anything.+ *+ * Closing it explicitly is what produces the `close` event the reconnect+ * hangs off — a half-open socket never fires one by itself, which is the+ * whole reason the UI could sit frozen for hours.+ */+ private dropDeadSocket(): void {+ const socket = this.ws;+ this.ws = null;+ this.stopPing();+ this.lastFrameAt = 0;+ try {+ socket?.close();+ } catch {+ /* already gone */+ }+ this.onClose?.(undefined);+ this.backoff = MIN_BACKOFF;+ this.scheduleReconnect();+ }+private openSocket(): void {// A pending ticket is single-use: consume it for exactly this attempt.const ticket = this.pendingTicket;@@ -101,23 +207,42 @@ export class WSClient {const target = ticket? `${this.url}${this.url.includes("?") ? "&" : "?"}ticket=${encodeURIComponent(ticket)}`: this.url;+ let socket: WebSocket;try {- this.ws = new WebSocket(target);+ socket = new WebSocket(target);} catch {this.scheduleReconnect();return;}+ this.ws = socket;+ /*+ * Every handler below belongs to THIS attempt.+ *+ * A socket the client has already given up on (see `dropDeadSocket`) still+ * fires its own close, and letting that run would report a second+ * disconnect and schedule a second reconnect for a connection nobody is+ * waiting on any more. Comparing against the current socket makes a retired+ * one inert without needing a flag per handler.+ */+ const current = (): boolean => this.ws === socket;- this.ws.addEventListener("open", () => {+ socket.addEventListener("open", () => {+ if (!current()) return;this.backoff = MIN_BACKOFF;+ this.lastFrameAt = Date.now();this.startPing();this.onOpen?.();});- this.ws.addEventListener("message", (ev) => {+ socket.addEventListener("message", (ev) => {+ if (!current()) return;// Any real frame proves the handshake credential worked — the auth// retry streak only counts UNINTERRUPTED 4401 rejections.this.authRetryStreak = 0;+ // ...and proves the wire is still carrying, which is what the silence+ // watchdog in `startPing` measures against. A pong counts: it is the+ // only frame an idle backend produces.+ this.lastFrameAt = Date.now();if (ev.data === "pong") return;try {const parsed = JSON.parse(ev.data);@@ -134,7 +259,8 @@ export class WSClient {}});- this.ws.addEventListener("close", (ev) => {+ socket.addEventListener("close", (ev) => {+ if (!current()) return;this.stopPing();this.lastCloseCode = (ev as CloseEvent).code;if (this.lastCloseCode === WS_CLOSE_UNAUTHORIZED && !this.stopped) {@@ -151,8 +277,9 @@ export class WSClient {if (!this.stopped) this.scheduleReconnect();});- this.ws.addEventListener("error", () => {- this.ws?.close();+ socket.addEventListener("error", () => {+ if (!current()) return;+ socket.close();});}@@ -183,11 +310,18 @@ export class WSClient {private startPing(): void {this.stopPing();this.pingTimer = setInterval(() => {- if (this.ws?.readyState === WebSocket.OPEN) {- // Backend uses receive_json + WSCommand discriminator — a bare- // "ping" string would trigger a JSONDecodeError and tip over the session.- this.ws.send(JSON.stringify({ type: "command", action: "ping", payload: {} }));+ if (this.ws?.readyState !== WebSocket.OPEN) return;+ // Answer first, question second: a socket that has not produced a single+ // frame since the last two pings is not slow, it is gone. Replacing it+ // here is the only way back — a half-open socket never closes itself, so+ // nothing else in this class would ever run again.+ if (this.lastFrameAt > 0 && Date.now() - this.lastFrameAt > SILENCE_LIMIT) {+ this.dropDeadSocket();+ return;}+ // Backend uses receive_json + WSCommand discriminator — a bare+ // "ping" string would trigger a JSONDecodeError and tip over the session.+ this.ws.send(JSON.stringify({ type: "command", action: "ping", payload: {} }));}, PING_INTERVAL);}@@ -228,6 +362,7 @@ export class WSClient {close(): void {this.stopped = true;this.stopPing();+ this.stopListeningForWake();if (this.reconnectTimer) {clearTimeout(this.reconnectTimer);this.reconnectTimer = null;diff --git a/tests/unit/agentic_ide/test_stale_workspace_socket.py b/tests/unit/agentic_ide/test_stale_workspace_socket.pynew file mode 100644index 0000000000..f347ba7ea3--- /dev/null+++ b/tests/unit/agentic_ide/test_stale_workspace_socket.py@@ -0,0 +1,146 @@+"""A pane socket must never be answered by a workspace it did not ask for.++Call-signs are positional: every workspace numbers its panes T1, T2, T3. The+same name is therefore a different terminal — different folder, different+agent, other work — in every open tab. A socket still carrying the id of a+workspace that has since been closed cannot be served by "whatever is at the+front now": it would attach to a stranger's pane, and because attaching makes+you that pane's owner it would take the pane away from the window the user is+actually looking at.++That is not theory. Measured 2026-07-28: an app restart left a page open whose+grid belonged to a six-pane workspace, a fresh four-pane workspace was opened,+and the leftover page's sockets bound to it one by one. Prompts typed into T2+and T3 by voice went to a screen nobody was watching, the visible panes sat+unchanged, and the only cure was reloading the page.++The answer is a verdict of its own — "that workspace is closed" (4409) — which+tells the client to re-read the state rather than retry or wait.++Written synchronously and driven through ``client.portal``: the registry's+per-pane locks and the app's PTY callbacks live on the SERVER loop, and setting+a workspace up on the test's own loop would leave them attached to a loop the+route never runs on (the same trap documented in ``test_wiki_ws``).+"""++from __future__ import annotations++from collections.abc import Iterator+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from starlette.websockets import WebSocketDisconnect++from jarvis.agentic_ide import session as session_mod+from jarvis.agentic_ide.session import Registry+from tests.fakes.fake_pty_manager import FakePtyManager++CLOSE_STALE_WORKSPACE = 4409+CLOSE_NOT_READY = 4503++[email protected](autouse=True)+def _isolated_recents(+ tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch+) -> None:+ from jarvis.agentic_ide import recents++ store = tmp_path_factory.mktemp("recents") / "recents.json"+ monkeypatch.setattr(recents, "_store_path", lambda: store)+++def registry(monkeypatch: pytest.MonkeyPatch) -> Registry:+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))+ reg = Registry(pty_manager=FakePtyManager())+ monkeypatch.setattr(session_mod, "get_registry", lambda: reg)+ from jarvis.ui.web import agentic_ide_routes++ monkeypatch.setattr(agentic_ide_routes, "get_registry", lambda: reg)+ # The handshake credential is a different question with its own tests; here+ # every socket is authorized so the workspace decision is the only thing+ # under test.+ monkeypatch.setattr(agentic_ide_routes, "credentials_valid", lambda _scope: True)+ return reg+++def client(registry: Registry) -> Iterator[TestClient]:+ from jarvis.ui.web.agentic_ide_routes import router++ app = FastAPI()+ app.include_router(router)+ with TestClient(app) as ready:+ yield ready+++def _open(client: TestClient, registry: Registry, folder: Path, count: int = 2) -> str:+ """Open a workspace ON THE SERVER LOOP and return its id."""+ folder.mkdir(parents=True, exist_ok=True)+ session = client.portal.call(+ registry.start, str(folder), [{"agent": "claude"} for _ in range(count)]+ )+ return session.id+++def _refusal(client: TestClient, url: str) -> tuple[int, list[dict]]:+ """Connect, read whatever the server says, and return (close code, frames).++ The handshake is ACCEPTED before a pane is refused — the reason travels as a+ frame first, so that a client can show a sentence rather than a bare number+ — which means the refusal only surfaces on the next read.+ """+ frames: list[dict] = []+ with pytest.raises(WebSocketDisconnect) as closed:+ with client.websocket_connect(url) as socket:+ while True:+ frames.append(socket.receive_json())+ return closed.value.code, frames+++def test_a_pane_of_a_closed_workspace_never_lands_in_the_open_one(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ gone = _open(client, registry, tmp_path / "old")+ client.portal.call(registry.end, gone)+ _open(client, registry, tmp_path / "new")++ code, frames = _refusal(client, f"/api/agentic-ide/pty/T1?workspace={gone}")++ assert code == CLOSE_STALE_WORKSPACE, (+ "a pane whose workspace is closed was served by the workspace at the "+ "front — that is how a leftover window steals a live pane"+ )+ assert frames and frames[0]["t"] == "error", "the refusal has to say why"+ # And the pane it reached for is untouched, which is the point of refusing:+ # nothing was started, and nobody's screen changed hands.+ assert registry.session is not None+ assert registry.session.terminals[0].viewer_output is None+++def test_a_pane_is_still_told_to_wait_while_nothing_is_open(+ client: TestClient, registry: Registry+) -> None:+ """The restart case keeps its patient answer (BUG-113).++ With no workspace open at all, an unknown id means "not yet" — the app is+ still coming up — and the pane must keep waiting rather than give up.+ """+ code, _frames = _refusal(client, "/api/agentic-ide/pty/T1?workspace=ide_longgone")++ assert code == CLOSE_NOT_READY+++def test_a_client_that_names_no_workspace_still_gets_the_front_one(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ """The single-workspace case, and every older client, must keep working."""+ _open(client, registry, tmp_path / "only", count=1)++ with client.websocket_connect("/api/agentic-ide/pty/T1") as socket:+ ready = socket.receive_json()++ assert ready["t"] == "ready"+ assert ready["name"] == "T1"diff --git a/tests/unit/agentic_ide/test_viewer_handover.py b/tests/unit/agentic_ide/test_viewer_handover.pyindex 3bbc01c373..d5f8cd809d 100644--- a/tests/unit/agentic_ide/test_viewer_handover.py+++ b/tests/unit/agentic_ide/test_viewer_handover.py@@ -165,3 +165,81 @@ async def test_a_pane_the_open_workspace_does_not_have_is_refused(await registry.attach("Nobody", 80, 24, Viewer().output, Viewer().exit)assert not isinstance(refused.value, SessionNotReady)+++# ------------------------------------------------- one pane, several screens+async def test_every_attached_viewer_sees_the_agent(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """A pane open in two places drives BOTH screens.++ The failure this pins is the one that made a live workspace look dead+ (reported 2026-07-28). A pane fed only its newest viewer, and viewers are+ not always the same window: the desktop app and a browser tab, two windows,+ a leftover page from an earlier session. Whichever attached last took the+ output and every other screen froze — agents working away behind rectangles+ that never changed, and nothing but a reload to bring them back.+ """+ _session, term = await _one_pane(registry, tmp_path)+ app, tab = Viewer(), Viewer()+ await registry.attach(term.name, 80, 24, app.output, app.exit)+ await registry.attach(term.name, 80, 24, tab.output, tab.exit)++ await fake_pty.emit(term.pty_id, "running the tests")++ assert "running the tests" in app.screen, (+ "the window that attached first went blind when a second one arrived"+ )+ assert "running the tests" in tab.screen+ # Ownership is still single, and still the newest: the pseudo-terminal has+ # exactly one size and two windows must not fight over it.+ assert term.viewer_output == tab.output+++async def test_the_survivor_keeps_the_pane_when_the_owner_leaves(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """Closing the newest window hands the pane back, it does not orphan it."""+ session, term = await _one_pane(registry, tmp_path)+ app, tab = Viewer(), Viewer()+ await registry.attach(term.name, 80, 24, app.output, app.exit)+ await registry.attach(term.name, 80, 24, tab.output, tab.exit)++ registry.detach(term.key, session.id, viewer=tab.output)+ await fake_pty.emit(term.pty_id, "still here")++ assert "still here" in app.screen+ assert "still here" not in tab.screen, "a closed viewer must stop being fed"+ assert term.viewer_output == app.output, (+ "the remaining window has to own the pane, or it can never set the "+ "agent's screen size again"+ )+++async def test_an_exit_reaches_every_screen(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """Both windows show the agent stopping — not just the newest one."""+ _session, term = await _one_pane(registry, tmp_path)+ app, tab = Viewer(), Viewer()+ await registry.attach(term.name, 80, 24, app.output, app.exit)+ await registry.attach(term.name, 80, 24, tab.output, tab.exit)++ await fake_pty.die(term.pty_id, 3)++ assert app.exits == [3]+ assert tab.exits == [3]+++async def test_one_socket_reattaching_is_not_two_viewers(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """A viewer that attaches again replaces itself rather than doubling."""+ _session, term = await _one_pane(registry, tmp_path)+ viewer = Viewer()+ await registry.attach(term.name, 80, 24, viewer.output, viewer.exit)+ await registry.attach(term.name, 80, 24, viewer.output, viewer.exit)++ await fake_pty.emit(term.pty_id, "once")++ assert viewer.seen.count("once") == 1, "the pane wrote the same bytes twice"