Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(agentic-ide): stop a reconnecting pane from freezing its terminal

Ruben Lütkedefaab9caeba
diff --git a/docs/BUGS.md b/docs/BUGS.md
index c5bc507ace..aa1059216a 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -7827,3 +7827,82 @@ tool keeps current is that tool's choice and changes between its releases. And
an identity read for account A must never be satisfied from account B's file:
a confident wrong name sends work to the wrong plan, where the only feedback is
a number on a billing page nobody is watching.
+
+---
+
+## BUG-113: a workspace of Agentic-IDE terminals freezes on screen while every agent behind it keeps working (HIGH, FIXED 2026-07-27)
+
+**Symptom (desktop field report).** "All the terminals you see here are frozen.
+You can't write in them any more — the only one you can still type into is one
+you spawn fresh." The panes drew a screen that never changed again; typing into
+them appeared to do nothing.
+
+**What was actually true at that moment.** Measured on the reporting machine
+while the panes were frozen:
+
+- `GET /api/agentic-ide/state` reported all 16 panes `live`, four of them with
+ `idle_seconds` of 0.0-0.2 — agents printing *right now*.
+- `netstat` showed 17 established connections to the backend port: the panes'
+ WebSockets were open, not dropped.
+
+So neither the agents nor the wire were broken. The keystrokes even arrived —
+input is written straight to the PTY and never touches the viewer — but with
+nothing coming back, a pane that echoes nothing is indistinguishable from a pane
+that ignores you.
+
+**Root cause A — a departing viewer released a slot it no longer owned.** A
+pane's output goes to ONE viewer slot (`Terminal.viewer_output`), and viewers
+overlap by design: reloading the page, restarting a pane or coming back to the
+section closes one socket and opens another for the same pane in the same
+breath, while the agent keeps running. `attach()` handed the slot to the new
+viewer; the old socket's teardown then ran
+
+```python
+finally:
+ registry.detach(term.key, pane_workspace) # cleared the slot unconditionally
+```
+
+Whichever of the two the server finished first was a matter of milliseconds, and
+with a full grid reconnecting at once some panes always lost the race. The
+loser's screen was never fed again: socket open, agent alive, transcript
+filling, pane frozen for the rest of the session. Nothing recovered it, because
+nothing re-attached — the socket was still connected.
+
+**Root cause B — "not yet" was answered as "not here".** A pane that connects
+while the workspace is still being restored got `SessionError("No Agentic-IDE
+session is running.")`, which the socket closed with **4404**. The client reads
+4404 as "this terminal does not exist here" and stops for good — correctly, for
+what that code means. It is exactly the state every pane reconnects into after
+an app restart: the log shows eleven panes doing it within nine seconds of the
+10:00 boot, all of them permanently dead while their workspace came back twelve
+minutes later. On top of that, ANY pane that spent its eight attempts was dead
+for the session — a laptop waking up was enough.
+
+**Fix.**
+- `jarvis/agentic_ide/session.py` — `detach(key, workspace_id, viewer=...)`
+ releases the slot only if it still holds *that* viewer's callback (compared by
+ equality, since a bound method is a new object per attribute access). A caller
+ that means "nobody is watching this pane" — teardown, tests — passes nothing
+ and clears it outright. New `SessionNotReady(SessionError)` separates "the
+ workspace is not open yet" from "no such pane".
+- `jarvis/ui/web/agentic_ide_routes.py` — the PTY socket passes its own
+ `on_output` when detaching, and closes with **4503** on `SessionNotReady`
+ instead of 4404.
+- `paneSocket.ts` — 4503 is waited out on its own counter (fast while a restart
+ plays out, then every 30 s), and a spent attempt budget no longer ends the
+ pane: it reports itself unreachable and keeps knocking every 30 s, so a
+ backend that comes back finds its terminals waiting. Only 4404 is final.
+- `AgenticTerminal.tsx` — at most one line per KIND of trouble, so a pane that
+ knocks every half minute does not stamp a red line into the terminal forever.
+
+**Regression guard.** `tests/unit/agentic_ide/test_viewer_handover.py` — the
+reload race in the order that used to freeze the workspace, the ordinary release
+still working, an exit reaching the viewer that took over, and "not yet" vs.
+"not here". `paneSocket.test.ts` — 4503 waited out, and a pane that ran out of
+fast attempts still reconnecting half a minute later.
+
+**Class rule.** A shared slot may only be cleared by whoever still holds it —
+"I am leaving" is never the same statement as "nobody is here". And a client
+that gives up permanently needs a reason that is permanent: everything else is a
+delay, so the honest answer to it is a slower retry, not a dead pane in front of
+a live process.
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index fe463a59cd..74a82a2e36 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -639,6 +639,18 @@ class SessionError(RuntimeError):
"""A request the registry refuses, with a user-facing English message."""
+class SessionNotReady(SessionError):
+ """The addressed workspace is not open — not "not here", but "not yet".
+
+ Raised where the old code raised a plain ``SessionError`` with the same
+ message, and the distinction is the whole point: a pane that connects while
+ the backend is still coming up (a restart, a workspace not restored yet) is
+ asking about a workspace that WILL exist, and a viewer told "no such pane"
+ stops trying for good. Every caller that can wait must be able to tell the
+ two apart — see the PTY socket's close codes.
+ """
+
+
class Registry:
"""Process-wide holder of the open Agentic-IDE workspaces.
@@ -1379,7 +1391,8 @@ class Registry:
found = self._locate(key, workspace_id)
if found is None:
if self.get(workspace_id) is None:
- raise SessionError("No Agentic-IDE session is running.")
+ # Not a refusal — a "not yet". A viewer may wait for this.
+ raise SessionNotReady("No Agentic-IDE session is running.")
raise SessionError(f"Unknown terminal: {key}")
session, term = found
if appearance in THEME_COLOURS:
@@ -1387,9 +1400,11 @@ class Registry:
manager = self._manager()
if term.pty_id and manager.has(term.pty_id):
- # The agent never stopped. Take over the viewer slot — the previous
- # viewer, if any, is gone by definition (a socket that closed) or is
- # being replaced by this one, so there is still exactly one.
+ # The agent never stopped. Take over the viewer slot: the previous
+ # viewer is either gone (a socket that closed) or is being replaced
+ # 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
term.reattached = True
@@ -1657,7 +1672,7 @@ class Registry:
term.transcript.resize(cols, rows)
return self._manager().resize(term.pty_id, cols, rows)
- def detach(self, key: str, workspace_id: str | None = None) -> None:
+ def detach(self, key: str, workspace_id: str | None = None, viewer: Any = None) -> None:
"""Let go of a pane's viewer. The agent behind it keeps running.
Detaching used to kill the PTY, on the reasoning that an agent nobody
@@ -1670,11 +1685,35 @@ class Registry:
runs until its workspace is closed.** Nothing is invisible about it —
every open workspace is a tab with a live-pane count on it, and closing
one stops its agents immediately (see ``_close_locked``).
+
+ **``viewer`` is what stops a leaving viewer from blinding the one that
+ replaced it** (BUG-113). Viewers overlap: reloading the page, restarting
+ a pane or switching back to the section closes one socket and opens
+ another for the SAME pane in the same breath, and which of the two the
+ server finishes first is a matter of milliseconds. Clearing the slot
+ unconditionally therefore wiped a viewer that had just been installed —
+ the pane then sat there with an open socket, a live agent typing into a
+ transcript, and a screen that never moved again. Passing the callback
+ that was handed to ``attach`` makes this a no-op unless the slot is
+ still that viewer's; a caller that genuinely means "nobody is watching
+ this pane" (a test, a teardown) passes nothing and clears it outright.
"""
found = self._locate(key, workspace_id)
if found is None:
return
term = found[1]
+ 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.
+ logger.debug(
+ "Agentic IDE: a departing viewer left {} to the one that replaced it",
+ term.name,
+ )
+ return
term.viewer_output = None
term.viewer_exit = None
@@ -2181,6 +2220,7 @@ __all__ = [
"Registry",
"Session",
"SessionError",
+ "SessionNotReady",
"Terminal",
"agent_argv",
"get_registry",
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index c311ca01f9..2328ae061f 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -64,6 +64,7 @@ from jarvis.agentic_ide.session import (
MAX_TERMINALS,
MAX_WORKSPACES,
SessionError,
+ SessionNotReady,
account_home,
agent_argv,
get_registry,
@@ -1568,6 +1569,20 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
workspace_id=pane_workspace,
appearance=appearance,
)
+ except SessionNotReady as exc:
+ # "Not yet", not "not here": this pane connected while its workspace was
+ # still being restored — the ordinary state of affairs for a second or
+ # two after the app restarts, when every pane in a full grid reconnects
+ # at once. Told "no such pane" (4404) they all gave up permanently and
+ # the whole workspace came back frozen, so this says "try again" with a
+ # code of its own and the pane keeps waiting.
+ log.info(
+ "Agentic IDE: %r connected before its workspace was open — asked it to wait",
+ name,
+ )
+ await ws.send_json({"t": "error", "message": str(exc)})
+ await ws.close(code=4503, reason="not ready")
+ return
except SessionError as exc:
# The reason used to travel to the browser and nowhere else, where it
# ended up as a tooltip on a red badge. A spawn that fails for every
@@ -1641,7 +1656,14 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
# None of those mean "stop working", so the agent keeps running and
# only the viewer is released; the next viewer re-joins it. What stops
# an agent is closing its workspace (DELETE /workspaces/{id}).
- registry.detach(term.key, pane_workspace)
+ #
+ # ``on_output`` identifies WHICH viewer is leaving, and that is what
+ # keeps a reload from blinding itself: the replacement socket for this
+ # pane may already have taken the slot while this one was still closing,
+ # and releasing it then would leave a live agent painting into nothing
+ # (BUG-113).
+ registry.detach(term.key, pane_workspace, viewer=on_output)
+
def _safe_int(value: object, default: int) -> int:
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index ebb49c3ea3..edccec28fe 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -309,11 +309,13 @@ export function AgenticTerminal({
let socket: PaneSocket | null = null;
let disposed = false;
- // Only the first attempt of a run of trouble is printed into the pane, plus
- // the verdict if it ends badly. A reconnect that succeeds redraws the screen
- // from the server's replay buffer anyway, so narrating every retry would
- // scroll the agent's own output away for nothing.
- let troublePrinted = false;
+ // At most one line per KIND of trouble: one when the connection starts
+ // wobbling, one if it is declared unreachable. A reconnect that succeeds
+ // redraws the screen from the server's replay buffer anyway, so narrating
+ // every attempt would scroll the agent's own output away for nothing — and
+ // a pane that keeps knocking every half minute would otherwise stamp a red
+ // line into the terminal twice a minute forever.
+ let troubleShown: "retrying" | "unreachable" | null = null;
/*
* Is anyone actually looking at this pane?
@@ -392,7 +394,7 @@ export function AgenticTerminal({
},
onOutput: (text) => writeToPane(text),
onReady: ({ resumed, reattached }) => {
- troublePrinted = false;
+ troubleShown = null;
// Say which of THREE things happened. They look identical on screen and
// only differ when it matters: an agent that never stopped still holds
// everything, a resumed one re-read its history, and a fresh one will
@@ -419,8 +421,9 @@ export function AgenticTerminal({
// there is what left a whole grid painted red over a backend that was
// merely restarting.
report(retrying ? "connecting" : "error", message);
- if (retrying && troublePrinted) return;
- troublePrinted = true;
+ const kind = retrying ? "retrying" : "unreachable";
+ if (troubleShown === kind) return;
+ troubleShown = kind;
writeToPane(
`\r\n\x1b[${retrying ? "33" : "31"}m[${message}]\x1b[0m\r\n`,
);
diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.ts b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.ts
index 6c1d466bfa..396bb96374 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.ts
@@ -148,7 +148,7 @@ describe("openPaneSocket", () => {
socket.close();
});
- it("stops retrying once the attempt budget is spent", async () => {
+ it("slows down once the attempt budget is spent, and says so", async () => {
const cb = handlers();
const socket = openPaneSocket({ name: "Mika", cols: 80, rows: 24 }, cb);
@@ -157,16 +157,61 @@ describe("openPaneSocket", () => {
await vi.advanceTimersByTimeAsync(20_000);
}
- // Bounded: a backend that is genuinely gone must not be hammered forever,
- // and the pane must end up saying so rather than spinning silently.
+ // Bounded: a backend that is genuinely gone must not be hammered, and the
+ // pane must end up saying so rather than spinning silently.
expect(cb.onTrouble).toHaveBeenLastCalledWith(expect.any(String), false);
const attempts = MockWebSocket.opened.length;
- MockWebSocket.last!.dropped(1006);
await vi.advanceTimersByTimeAsync(20_000);
expect(MockWebSocket.opened).toHaveLength(attempts);
socket.close();
});
+ it("keeps knocking every half minute instead of dying for the session", async () => {
+ const cb = handlers();
+ const socket = openPaneSocket({ name: "Mika", cols: 80, rows: 24 }, cb);
+
+ for (let i = 0; i < 12; i += 1) {
+ MockWebSocket.last!.dropped(1006);
+ await vi.advanceTimersByTimeAsync(20_000);
+ }
+ expect(cb.onTrouble).toHaveBeenLastCalledWith(expect.any(String), false);
+ MockWebSocket.last!.dropped(1006);
+ const spent = MockWebSocket.opened.length;
+
+ // The reasons a pane cannot connect are nearly always temporary — an app
+ // restarting, a machine waking up. A pane that gave up for good left a live
+ // agent behind an unusable terminal until the whole workspace was rebuilt
+ // by hand (BUG-113), so it stays quiet but never stops trying.
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(MockWebSocket.opened).toHaveLength(spent);
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(MockWebSocket.opened.length).toBeGreaterThan(spent);
+
+ MockWebSocket.last!.fire("open");
+ MockWebSocket.last!.deliver({ t: "ready", resumed: false, reattached: true });
+ expect(cb.onReady).toHaveBeenCalledTimes(1);
+ socket.close();
+ });
+
+ it("waits out a backend that is up but has not restored the workspace yet", async () => {
+ const cb = handlers();
+ const socket = openPaneSocket({ name: "Mika", cols: 80, rows: 24 }, cb);
+
+ // 4503 is "not yet", the state every pane of a restored workspace connects
+ // into for a second or two after the app restarts. Read as "no such pane"
+ // it ended a whole grid at once; here it must cost nothing but patience.
+ for (let i = 0; i < 12; i += 1) {
+ MockWebSocket.last!.dropped(4503);
+ await vi.advanceTimersByTimeAsync(30_000);
+ }
+ expect(cb.onTrouble).toHaveBeenLastCalledWith(expect.any(String), true);
+
+ MockWebSocket.last!.fire("open");
+ MockWebSocket.last!.deliver({ t: "ready", resumed: true, reattached: false });
+ expect(cb.onReady).toHaveBeenCalledTimes(1);
+ socket.close();
+ });
+
it("treats an agent exit as final, not as a dropped connection", async () => {
const cb = handlers();
const socket = openPaneSocket({ name: "Mika", cols: 80, rows: 24 }, cb);
diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts
index f51d415c8f..7f4ba18c39 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts
@@ -21,9 +21,14 @@
* - **A dropped connection.** A backend restart, a reload, a moment of
* unreachability. One failed attempt used to be final, which is why a
* whole grid of panes could go red at once and stay that way.
+ * - **A backend that is up but not ready.** After a restart the panes of a
+ * restored workspace reconnect within milliseconds — reliably before the
+ * workspace itself is back. That answer (4503) is a "not yet" and is waited
+ * out; only "not here" (4404) ends a pane for good.
*
- * Both are bounded: a pane never hammers a backend that is genuinely gone, and
- * whatever it ends up believing, it says out loud.
+ * All three are bounded: a pane never hammers a backend that is genuinely
+ * gone — it falls back to knocking every half minute — and whatever it ends up
+ * believing, it says out loud.
*/
import { mintWsTicket } from "@/lib/ws";
@@ -32,17 +37,39 @@ import { mintWsTicket } from "@/lib/ws";
const CLOSE_UNAUTHORIZED = 4401;
/** Server close code: no such pane in the addressed workspace. */
const CLOSE_NO_SUCH_PANE = 4404;
+/**
+ * Server close code: the workspace this pane belongs to is not open YET.
+ *
+ * Its own code because it is the opposite verdict from 4404 with the same
+ * shape: the backend is up but still restoring, which is precisely the state
+ * every pane of a full grid reconnects into after the app restarts. Until the
+ * server distinguished them, that answer arrived as "no such pane" and a whole
+ * workspace of terminals gave up for good (BUG-113).
+ */
+const CLOSE_NOT_READY = 4503;
const MIN_BACKOFF = 500;
const MAX_BACKOFF = 8_000;
/**
- * Consecutive failed attempts before a pane declares itself unreachable.
- * Eight covers the ~20 s a backend restart takes to answer again, and stops
- * well short of retrying at a dead server for the rest of the session.
+ * Consecutive failed attempts before a pane stops retrying quickly.
+ * Eight covers the ~20 s a backend restart takes to answer again.
*/
const MAX_ATTEMPTS = 8;
+/**
+ * How often a pane that has run out of fast attempts still knocks.
+ *
+ * It does keep knocking, and that is the point: the reasons a terminal cannot
+ * be reached are overwhelmingly temporary — a backend restarting, a workspace
+ * not restored yet, a laptop that was asleep — and every one of them used to
+ * end with a pane that was dead for the rest of the session while the agent
+ * behind it was alive and working. Half a minute apart costs nothing and is the
+ * difference between a workspace that heals itself and one the user has to
+ * rebuild by hand.
+ */
+const IDLE_BACKOFF = 30_000;
+
/**
* Consecutive 4401s that still count as a transient authorization hiccup.
* Beyond this, fresh tickets are evidently not unlocking the socket and the
@@ -120,6 +147,8 @@ export function openPaneSocket(
/** The agent reported its own exit — a later close is not a lost wire. */
let agentExited = false;
let attempts = 0;
+ /** Consecutive "not yet" answers — waiting, which is not failing. */
+ let waits = 0;
let ticketRetries = 0;
let pendingTicket: string | null = null;
@@ -139,7 +168,12 @@ export function openPaneSocket(
const retryLater = (message: string) => {
attempts += 1;
if (attempts > MAX_ATTEMPTS) {
- giveUp(message);
+ // Out of fast attempts, not out of hope: the pane says so (``retrying``
+ // false paints it as unreachable and offers the restart button) and then
+ // keeps knocking every half minute, so a backend that comes back finds
+ // its terminals waiting rather than needing every one of them reopened.
+ handlers.onTrouble(message, false);
+ schedule(IDLE_BACKOFF);
return;
}
handlers.onTrouble(message, true);
@@ -170,6 +204,22 @@ export function openPaneSocket(
giveUp("This terminal is no longer part of the open workspace.");
return;
}
+ if (code === CLOSE_NOT_READY) {
+ // The workspace is still coming up. Waiting is the correct answer, and it
+ // is counted separately from failures: the backend is answering, doing
+ // exactly what it said it was doing, so this must not burn down the
+ // budget that decides whether the pane is UNREACHABLE. Fast while a
+ // restart plays out, patient afterwards — a workspace restored a quarter
+ // of an hour later still finds its panes waiting.
+ waits += 1;
+ handlers.onTrouble("Waiting for the workspace to come back…", true);
+ schedule(
+ waits > MAX_ATTEMPTS
+ ? IDLE_BACKOFF
+ : Math.min(MAX_BACKOFF, MIN_BACKOFF * 2 ** (waits - 1)),
+ );
+ return;
+ }
if (code === CLOSE_UNAUTHORIZED) {
void authRetry();
return;
@@ -215,6 +265,7 @@ export function openPaneSocket(
// this attempt used, it worked.
ticketRetries = 0;
attempts = 0;
+ waits = 0;
handlers.onReady({
resumed: Boolean(msg.resumed),
reattached: Boolean(msg.reattached),
diff --git a/tests/unit/agentic_ide/test_viewer_handover.py b/tests/unit/agentic_ide/test_viewer_handover.py
new file mode 100644
index 0000000000..3bbc01c373
--- /dev/null
+++ b/tests/unit/agentic_ide/test_viewer_handover.py
@@ -0,0 +1,167 @@
+"""Which viewer a pane's output goes to when two of them overlap (BUG-113).
+
+Viewers overlap constantly and by design: reloading the page, restarting a pane
+or coming back to the section closes one socket and opens another for the SAME
+pane in the same breath, and the agent behind it never stops. Which of the two
+the server finishes first is a matter of milliseconds — so the rule cannot be
+"the last one to speak wins", it has to be "only the viewer that still holds the
+slot may release it".
+
+Without that rule a departing viewer cleared a slot the arriving one had just
+filled, and the result was the reported symptom: a full workspace of terminals
+frozen on screen — sockets open, agents alive and typing into their transcripts,
+screens that never moved again — while a freshly opened pane worked perfectly.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import session as session_mod
+from jarvis.agentic_ide.session import Registry, SessionError, SessionNotReady
+from tests.fakes.fake_pty_manager import FakePtyManager
+
+
+def fake_pty() -> FakePtyManager:
+ return FakePtyManager()
+
+
+def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> Registry:
+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))
+ return Registry(pty_manager=fake_pty)
+
+
+class Viewer:
+ """One socket's end of a pane — what it was handed, in order."""
+
+ def __init__(self) -> None:
+ self.seen: list[str] = []
+ self.exits: list[int] = []
+
+ async def output(self, text: str) -> None:
+ self.seen.append(text)
+
+ async def exit(self, code: int) -> None:
+ self.exits.append(code)
+
+ @property
+ def screen(self) -> str:
+ return "".join(self.seen)
+
+
+async def _one_pane(registry: Registry, folder: Path):
+ session = await registry.start(str(folder), [{"agent": "claude"}])
+ return session, session.terminals[0]
+
+
+async def test_a_leaving_viewer_does_not_blind_the_one_that_replaced_it(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """The reload race, in the order that used to freeze the workspace."""
+ session, term = await _one_pane(registry, tmp_path)
+ old, new = Viewer(), Viewer()
+ await registry.attach(term.name, 80, 24, old.output, old.exit)
+
+ # The page reloads: the replacement socket attaches BEFORE the old one has
+ # finished closing, which is the common order and not an exotic one.
+ await registry.attach(term.name, 80, 24, new.output, new.exit)
+ registry.detach(term.key, session.id, viewer=old.output)
+
+ await fake_pty.emit(term.pty_id, "the agent is still working")
+
+ assert "the agent is still working" in new.screen, (
+ "the pane on screen went blind — a viewer that had already been "
+ "replaced released the slot the live one was using"
+ )
+ assert term.viewer_output == new.output
+
+
+async def test_the_viewer_that_still_holds_the_slot_releases_it(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """The ordinary case must keep working: nobody watching means nobody fed."""
+ session, term = await _one_pane(registry, tmp_path)
+ viewer = Viewer()
+ await registry.attach(term.name, 80, 24, viewer.output, viewer.exit)
+
+ registry.detach(term.key, session.id, viewer=viewer.output)
+ await fake_pty.emit(term.pty_id, "printed to nobody")
+
+ assert term.viewer_output is None
+ assert viewer.screen == "", "a pane nobody is watching must not be fed"
+ # And the agent is untouched by it — that is the whole lifetime rule.
+ assert term.pty_id not in fake_pty.closed
+
+
+async def test_a_caller_that_names_no_viewer_still_clears_the_slot(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """Teardown paths mean "nobody is watching this pane", full stop."""
+ session, term = await _one_pane(registry, tmp_path)
+ viewer = Viewer()
+ await registry.attach(term.name, 80, 24, viewer.output, viewer.exit)
+
+ registry.detach(term.key, session.id)
+
+ assert term.viewer_output is None
+
+
+async def test_the_new_viewer_is_handed_the_screen_the_pane_is_showing(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """A replacement viewer starts from the current screen, not from blank."""
+ session, term = await _one_pane(registry, tmp_path)
+ old = Viewer()
+ await registry.attach(term.name, 80, 24, old.output, old.exit)
+ await fake_pty.emit(term.pty_id, "\x1b[32mbuilding…\x1b[0m")
+
+ new = Viewer()
+ await registry.attach(term.name, 80, 24, new.output, new.exit)
+ registry.detach(term.key, session.id, viewer=old.output)
+
+ assert "building…" in new.screen
+
+
+async def test_an_exit_reaches_the_viewer_that_took_over(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """The other half of the slot: a dead agent must be reported on screen."""
+ session, term = await _one_pane(registry, tmp_path)
+ old, new = Viewer(), Viewer()
+ await registry.attach(term.name, 80, 24, old.output, old.exit)
+ await registry.attach(term.name, 80, 24, new.output, new.exit)
+ registry.detach(term.key, session.id, viewer=old.output)
+
+ await fake_pty.die(term.pty_id, 1)
+
+ assert new.exits == [1]
+ assert old.exits == [], "a replaced viewer must not be told anything"
+
+
+# ------------------------------------------------- not here vs. not yet
+async def test_a_pane_of_a_workspace_that_is_not_open_yet_is_told_to_wait(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """The state every pane reconnects into while the app is still starting.
+
+ Answered as a flat refusal it read as "this terminal no longer exists", and
+ a whole grid of panes stopped trying for the rest of the session.
+ """
+ with pytest.raises(SessionNotReady):
+ await registry.attach("Alex", 80, 24, Viewer().output, Viewer().exit)
+
+
+async def test_a_pane_the_open_workspace_does_not_have_is_refused(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """A pane that is genuinely not there stays refused — retrying cannot help."""
+ await _one_pane(registry, tmp_path)
+
+ with pytest.raises(SessionError) as refused:
+ await registry.attach("Nobody", 80, 24, Viewer().output, Viewer().exit)
+
+ assert not isinstance(refused.value, SessionNotReady)