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: reclaim foreground terminal geometry

Ruben Lütkef486a75ec808
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 8fbb72ed38..9da2bf9277 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -1376,18 +1376,27 @@ def _watch(
on_exit: Any,
cols: int,
rows: int,
-) -> None:
- """Attach a viewer to ``term`` and make it the owner.
+ *,
+ claim_owner: bool = True,
+) -> bool:
+ """Attach a viewer to ``term`` and optionally 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.
+ A background viewer may watch without taking the one shared PTY geometry
+ away from the window that is actually in front of the user.
"""
term.watchers = [w for w in term.watchers if not _same_viewer(w.output, on_output)]
term.watchers.append(PaneViewer(on_output, on_exit, cols, rows))
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
+ owner_is_attached = any(
+ _same_viewer(watched.output, term.viewer_output) for watched in term.watchers
+ )
+ if claim_owner or term.viewer_output is None or not owner_is_attached:
+ term.viewer_output = on_output
+ term.viewer_exit = on_exit
+ return _same_viewer(term.viewer_output, on_output)
def _viewers(term: Terminal) -> list[Any]:
@@ -2363,6 +2372,7 @@ class Registry:
workspace_id: str | None = None,
appearance: str | None = None,
on_replay: Any = None,
+ claim_owner: bool = True,
) -> Terminal:
"""Point a viewer at terminal ``key`` — one attach at a time per pane.
@@ -2402,6 +2412,7 @@ class Registry:
workspace_id=workspace_id,
appearance=appearance,
on_replay=on_replay,
+ claim_owner=claim_owner,
)
async def _attach_locked(
@@ -2414,6 +2425,7 @@ class Registry:
workspace_id: str | None = None,
appearance: str | None = None,
on_replay: Any = None,
+ claim_owner: bool = True,
) -> Terminal:
"""Point a viewer at terminal ``key``, starting its agent if needed.
@@ -2486,21 +2498,26 @@ 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 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.
+ # The agent never stopped. A foreground viewer takes over the owner
+ # slot; a background viewer only joins the output fanout. A viewer
+ # that is being replaced may still be TIDYING UP — see ``detach``,
+ # which is what stops that tidy-up from clearing the live owner.
#
# 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, cols, rows)
- term.reattached = True
- term.stopping = False
- geometry_changed = (term.transcript.cols, term.transcript.rows) != (
+ owns_viewer = _watch(
+ term,
+ on_output,
+ on_exit,
cols,
rows,
+ claim_owner=claim_owner,
+ )
+ term.reattached = True
+ term.stopping = False
+ geometry_changed = owns_viewer and (
+ (term.transcript.cols, term.transcript.rows) != (cols, rows)
)
if geometry_changed:
geometry_changed = manager.resize(term.pty_id, cols, rows)
@@ -3114,6 +3131,49 @@ class Registry:
except Exception as exc: # noqa: BLE001 - a stale screen beats a failed reconnect
logger.debug("Agentic IDE: could not nudge {} into a repaint: {}", term.name, exc)
+ def claim_viewer(
+ self,
+ key: str,
+ cols: int,
+ rows: int,
+ workspace_id: str | None = None,
+ viewer: Any = None,
+ ) -> bool:
+ """Give a foreground viewer ownership and restore its PTY geometry."""
+ if viewer is None:
+ return False
+ found = self._locate(key, workspace_id)
+ if found is None:
+ return False
+ term = found[1]
+ if not term.pty_id:
+ return False
+ claimed = next(
+ (watched for watched in term.watchers if _same_viewer(watched.output, viewer)),
+ None,
+ )
+ if claimed is None:
+ return False
+ claimed.cols = cols
+ claimed.rows = rows
+ # Most recently foregrounded last: if this owner closes, ``detach`` can
+ # promote the viewer the user interacted with most recently before it.
+ term.watchers = [
+ watched
+ for watched in term.watchers
+ if not _same_viewer(watched.output, viewer)
+ ]
+ term.watchers.append(claimed)
+ term.viewer_output = claimed.output
+ term.viewer_exit = claimed.exit
+ return self.resize(
+ term.key,
+ cols,
+ rows,
+ workspace_id,
+ viewer=claimed.output,
+ )
+
def resize(
self,
key: str,
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index 10a0ad70e3..62bc41c7c0 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -2984,7 +2984,8 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
"""Bidirectional bridge between one xterm pane and its agent's PTY.
Wire protocol (JSON both ways) — client: ``{t:"i",d}`` input,
- ``{t:"r",cols,rows}`` resize; server: ``{t:"o",d}`` output, ``{t:"ready"}``,
+ ``{t:"r",cols,rows}`` resize, ``{t:"claim",cols,rows}`` foreground
+ ownership; server: ``{t:"o",d}`` output, ``{t:"ready"}``,
``{t:"exit",code}``, ``{t:"error",message}``.
The optional ``workspace`` query parameter names the workspace this pane
@@ -3018,6 +3019,11 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
rows = _safe_int(qp.get("rows"), 24)
workspace_id = (qp.get("workspace") or "").strip() or None
appearance = (qp.get("appearance") or "").strip().lower() or None
+ claim_owner = (qp.get("claim") or "1").strip().lower() not in {
+ "0",
+ "false",
+ "no",
+ }
registry = get_registry()
send_lock = asyncio.Lock()
@@ -3125,6 +3131,7 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
workspace_id=pane_workspace,
appearance=appearance,
on_replay=on_replay,
+ claim_owner=claim_owner,
)
except SessionNotReady as exc:
# "Not yet", not "not here": this pane connected while its workspace was
@@ -3229,6 +3236,14 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
pane_workspace,
viewer=on_output,
)
+ elif kind == "claim":
+ registry.claim_viewer(
+ term.key,
+ _safe_int(msg.get("cols"), cols),
+ _safe_int(msg.get("rows"), rows),
+ pane_workspace,
+ viewer=on_output,
+ )
finally:
# The viewer went away — switched tab, reloaded, closed the browser.
# None of those mean "stop working", so the agent keeps running and
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
index 73ae5dba02..36dbb9982a 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
@@ -584,13 +584,14 @@ describe("pane refit", () => {
});
};
- const pane = (maximized: boolean) => (
+ const pane = (maximized: boolean, active = true) => (
<AgenticTerminal
name="Dana"
displayName="Claude Code"
appearance="dark"
fontSize={13}
maximized={maximized}
+ active={active}
/>
);
@@ -603,10 +604,12 @@ describe("pane refit", () => {
terminalHarness.send.mockImplementation(() => true);
terminalHarness.handlers.current = null;
terminalHarness.size = { cols: 80, rows: 24 };
+ vi.spyOn(document, "hasFocus").mockReturnValue(true);
});
afterEach(() => {
vi.useRealTimers();
+ vi.restoreAllMocks();
Reflect.deleteProperty(HTMLElement.prototype, "clientWidth");
Reflect.deleteProperty(HTMLElement.prototype, "clientHeight");
});
@@ -650,6 +653,21 @@ describe("pane refit", () => {
expect(terminalHarness.send).not.toHaveBeenCalled();
});
+ it("reclaims the shared PTY geometry when the pane becomes active", () => {
+ const view = render(pane(false, false));
+ settle();
+ terminalHarness.send.mockClear();
+
+ view.rerender(pane(false, true));
+ settle();
+
+ expect(terminalHarness.send).toHaveBeenCalledWith({
+ t: "claim",
+ cols: 80,
+ rows: 24,
+ });
+ });
+
it("keeps offering a size the socket could not carry", () => {
// A pane measured while its backend was restarting must not treat the
// frame as delivered. Nothing measures a pane again on its own, so a size
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index e269714cfe..1ccc96d7be 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -816,7 +816,7 @@ export function AgenticTerminal({
// was connecting were dropped — without this the agent's full-screen
// TUI keeps drawing at the wrong width and looks clipped.
sendResize();
- requestAnimationFrame(sendResize);
+ requestAnimationFrame(() => sendResize());
},
onOutput: (text) => writeToPane(text),
onReplay: (text) => replayToPane(text),
@@ -1070,6 +1070,7 @@ export function AgenticTerminal({
}
const reveal = () => {
visibilityRef.current?.show();
+ resizeRef.current?.();
claimResizeRef.current?.();
termRef.current?.scrollToBottom?.();
};
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 0e17cbd443..9faa825598 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.ts
@@ -95,11 +95,21 @@ describe("openPaneSocket", () => {
// this socket is alive, and the server resolves a pane without one against
// whichever is showing — which is a different folder's pane.
expect(MockWebSocket.last!.url).toBe(
- "ws://localhost:5173/api/agentic-ide/pty/Mika?cols=120&rows=40&workspace=ide_abc",
+ "ws://localhost:5173/api/agentic-ide/pty/Mika?cols=120&rows=40&claim=1&workspace=ide_abc",
);
socket.close();
});
+ it("marks a background viewer so it cannot steal the shared PTY size", () => {
+ const socket = openPaneSocket(
+ { name: "Mika", cols: 60, rows: 20, claimOwner: false },
+ handlers(),
+ );
+
+ expect(MockWebSocket.last!.url).toContain("claim=0");
+ socket.close();
+ });
+
it("mints a one-time ticket and retries a rejected handshake (BUG-065)", async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts
index f7fd6adc03..b67eb9ede3 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts
@@ -126,6 +126,8 @@ export interface PaneSocketOptions {
name: string;
cols: number;
rows: number;
+ /** Whether this viewer is foregrounded and may own the shared PTY size. */
+ claimOwner?: boolean;
/**
* The workspace this pane belongs to. Several can be open and the front one
* changes while sockets are alive: without it the server resolves the pane
@@ -230,6 +232,7 @@ function paneUrl(opts: PaneSocketOptions, ticket: string | null): string {
const query = new URLSearchParams({
cols: String(opts.cols),
rows: String(opts.rows),
+ claim: opts.claimOwner === false ? "0" : "1",
});
if (opts.workspaceId) query.set("workspace", opts.workspaceId);
if (opts.appearance) query.set("appearance", opts.appearance);
diff --git a/tests/unit/agentic_ide/test_viewer_handover.py b/tests/unit/agentic_ide/test_viewer_handover.py
index d5f8cd809d..9c5f8d0f3b 100644
--- a/tests/unit/agentic_ide/test_viewer_handover.py
+++ b/tests/unit/agentic_ide/test_viewer_handover.py
@@ -243,3 +243,66 @@ async def test_one_socket_reattaching_is_not_two_viewers(
await fake_pty.emit(term.pty_id, "once")
assert viewer.seen.count("once") == 1, "the pane wrote the same bytes twice"
+
+
+async def test_background_viewer_watches_without_stealing_geometry(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """A background browser tab must not narrow the foreground desktop pane."""
+ _session, term = await _one_pane(registry, tmp_path)
+ app, tab = Viewer(), Viewer()
+ await registry.attach(term.name, 180, 50, app.output, app.exit)
+ fake_pty.resizes.clear()
+
+ await registry.attach(
+ term.name,
+ 60,
+ 20,
+ tab.output,
+ tab.exit,
+ claim_owner=False,
+ )
+ await fake_pty.emit(term.pty_id, "visible in both places")
+
+ assert term.viewer_output == app.output
+ assert fake_pty.resizes == []
+ assert "visible in both places" in app.screen
+ assert "visible in both places" in tab.screen
+
+
+async def test_foreground_viewer_can_reclaim_its_geometry(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """Returning to a window restores the PTY to that window's measured size."""
+ session, term = await _one_pane(registry, tmp_path)
+ app, tab = Viewer(), Viewer()
+ await registry.attach(term.name, 180, 50, app.output, app.exit)
+ await registry.attach(
+ term.name,
+ 60,
+ 20,
+ tab.output,
+ tab.exit,
+ claim_owner=False,
+ )
+ fake_pty.resizes.clear()
+
+ assert registry.claim_viewer(
+ term.key,
+ 60,
+ 20,
+ session.id,
+ viewer=tab.output,
+ )
+ assert term.viewer_output == tab.output
+ assert fake_pty.resizes == [(term.pty_id, 60, 20)]
+
+ assert registry.claim_viewer(
+ term.key,
+ 180,
+ 50,
+ session.id,
+ viewer=app.output,
+ )
+ assert term.viewer_output == app.output
+ assert fake_pty.resizes[-1] == (term.pty_id, 180, 50)