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): keep terminal replays clean across resize

Ruben Lütkec6863896dd4d
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 94ffa80b60..c75f426c94 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -2278,6 +2278,11 @@ class Registry:
progress every time somebody looked away, which is precisely what having
several workspaces would otherwise cost.
+ A replay is valid only at the geometry that produced its cursor moves.
+ When the viewer comes back at another size, the old drawing is replaced
+ by its terminal-mode prologue and a live repaint. This is still the same
+ process and conversation; only the stale pixels are discarded.
+
**That replay goes out on ``on_replay``, not on ``on_output``, because a
viewer has to CLEAR its screen before drawing it.** The two are the same
bytes and completely different instructions: live output continues a
@@ -2331,25 +2336,40 @@ class Registry:
_watch(term, on_output, on_exit)
term.reattached = True
term.stopping = False
- term.transcript.resize(cols, rows)
- manager.resize(term.pty_id, cols, rows)
- replay = term.replay.text()
+ geometry_changed = (term.transcript.cols, term.transcript.rows) != (
+ cols,
+ rows,
+ )
+ if geometry_changed:
+ geometry_changed = manager.resize(term.pty_id, cols, rows)
+ if geometry_changed:
+ term.transcript.resize(cols, rows)
+ needs_repaint = term.replay.truncated
+ if geometry_changed and is_coding_agent(term.agent):
+ # A cursor-addressed TUI stream is meaningful only at the size
+ # that produced it. Replaying the old geometry after a grid
+ # re-layout leaves status rows and command fragments behind
+ # the new paint. Keep the terminal modes, drop those drawing
+ # bytes, and let the live agent rebuild one clean screen below.
+ replay = term.replay.rebase_for_resize()
+ needs_repaint = True
+ else:
+ replay = term.replay.text()
if replay:
- # Hand over the raw stream that drew the current screen. A
- # coding agent's TUI is a painted surface, not a log: without
- # this the pane comes back blank until the agent happens to
- # repaint, which looks exactly like a dead terminal.
+ # Hand over either the stream that drew the current screen, or
+ # (after a geometry change) the terminal-mode prologue that a
+ # clean repaint must draw on. A coding agent's TUI is a painted
+ # surface, not a log: the viewer needs one of those two rebuild
+ # paths rather than an append to whatever it held before.
#
# On the replay channel when the viewer offered one — see the
# docstring for what appending it to a screen that already had
# a copy of it looked like.
await (on_replay or on_output)(replay)
- if term.replay.truncated:
- # The tail is all this pane has, and it no longer starts where
- # the agent started drawing. Replaying it alone brings back the
- # one row the agent rewrote last and empty space where its
- # prompt box should be — see ReplayBuffer's docstring. Ask for
- # a fresh paint instead of hoping one arrives.
+ if needs_repaint:
+ # Either the tail lost its opening frame, or its cursor moves
+ # belong to another geometry. Neither can rebuild this viewer.
+ # Ask for a fresh paint instead of hoping one arrives.
await self._nudge_repaint(term, cols, rows)
logger.debug("Agentic IDE: {} re-joined a running agent", term.name)
return term
@@ -2861,8 +2881,17 @@ class Registry:
return False
# The replayed screen has to follow the real one; otherwise the
# transcript keeps wrapping at the old width.
+ if (term.transcript.cols, term.transcript.rows) == (cols, rows):
+ return True
+ if not self._manager().resize(term.pty_id, cols, rows):
+ return False
+ if is_coding_agent(term.agent):
+ # Future viewers must not replay cursor moves produced for the old
+ # grid into the new one. The live viewer already has its screen;
+ # this only starts a clean replay epoch for the next reconnect.
+ term.replay.rebase_for_resize()
term.transcript.resize(cols, rows)
- return self._manager().resize(term.pty_id, cols, rows)
+ return True
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.
diff --git a/jarvis/agentic_ide/transcript.py b/jarvis/agentic_ide/transcript.py
index cf4139f9a1..964c8c58ed 100644
--- a/jarvis/agentic_ide/transcript.py
+++ b/jarvis/agentic_ide/transcript.py
@@ -278,6 +278,29 @@ class ReplayBuffer:
text = text[remnant.end() :]
return self._mode_prologue() + "\x1b[0m" + text
+ def rebase_for_resize(self) -> str:
+ """Forget drawing bytes tied to the old geometry, preserving modes.
+
+ Cursor-addressed TUI output only has meaning at the terminal size that
+ produced it. Replaying that stream into a differently sized viewer
+ leaves old status rows and fragments between the newly painted ones.
+ A resize therefore starts a new replay epoch: the caller sends this
+ returned prologue to a reset viewer, then asks the live TUI to repaint.
+
+ Private modes survive because most coding CLIs negotiate alternate
+ screen and mouse tracking only once, at process startup. Dropping
+ those together with the stale drawing would repair the text while
+ silently breaking the pane's mouse and scrollbar.
+ """
+ prologue = self._mode_prologue() + "\x1b[0m"
+ self._chunks.clear()
+ self._size = 0
+ self.truncated = False
+ self._open_escape = False
+ self._chunks.append(prologue)
+ self._size = len(prologue)
+ return prologue
+
def clear(self) -> None:
"""Forget everything — this buffer is being handed to a fresh process.
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
index f626a757d5..bd51f0434b 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
@@ -1690,6 +1690,7 @@ export function AgenticGrid({
promptCount={term.prompts_sent}
appearance={appearance}
fontSize={fontSize}
+ geometryReady={gridWidth > 0 && gridHeight > 0}
focused={target === term.name}
maximized={isMaximized}
layoutBusy={layoutBusy}
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 6793dc2897..ad1b2034b6 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
@@ -141,6 +141,32 @@ describe("AgenticTerminal layout", () => {
expect(terminalHarness.open).toHaveBeenCalledWith(host);
expect(terminalHarness.observe).toHaveBeenCalledWith(host);
});
+
+ it("waits for the area-aware grid measurement before opening the PTY", () => {
+ const view = render(
+ <AgenticTerminal
+ name="Dana"
+ displayName="Claude Code"
+ appearance="dark"
+ fontSize={13}
+ geometryReady={false}
+ />,
+ );
+
+ expect(terminalHarness.open).not.toHaveBeenCalled();
+
+ view.rerender(
+ <AgenticTerminal
+ name="Dana"
+ displayName="Claude Code"
+ appearance="dark"
+ fontSize={13}
+ geometryReady
+ />,
+ );
+
+ expect(terminalHarness.open).toHaveBeenCalled();
+ });
});
describe("pane keyboard", () => {
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index 789aa6d4c6..f8704ceffa 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -9,8 +9,9 @@
* 2. Appearance and font size are applied to the LIVE instance in their own
* effects. Rebuilding the terminal when the user flips to dark mode would
* tear down the WebSocket, which kills the agent running behind it and
- * loses the whole session. So the connect effect depends on the pane key
- * alone.
+ * loses the whole session. So the connect effect depends on pane identity,
+ * restart intent and one-way initial geometry readiness — never live
+ * appearance state.
*
* ## Why this pane is configured the way it is
*
@@ -220,6 +221,15 @@ interface AgenticTerminalProps {
promptCount?: number;
appearance: TerminalAppearance;
fontSize: number;
+ /**
+ * Has the grid measured the pane's final opening geometry?
+ *
+ * Area-aware layouts cannot know their band count until the container has a
+ * height. Opening the PTY during the width-only first pass attaches it at one
+ * size and immediately moves it to another, while its replay is still being
+ * parsed. Omitted for standalone uses, which already render at a fixed size.
+ */
+ geometryReady?: boolean;
/** Highlight this pane as the prompt target. */
focused?: boolean;
onFocus?: () => void;
@@ -304,6 +314,7 @@ export function AgenticTerminal({
promptCount = 0,
appearance,
fontSize,
+ geometryReady = true,
focused = false,
onFocus,
onStatus,
@@ -389,6 +400,7 @@ export function AgenticTerminal({
layoutBusyRef.current = layoutBusy;
useEffect(() => {
+ if (!geometryReady) return;
const container = containerRef.current;
if (!container) return;
@@ -954,7 +966,7 @@ export function AgenticTerminal({
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- see file header:
// appearance/fontSize must NOT rebuild the pane (it would kill the agent).
- }, [name, restartToken]);
+ }, [name, restartToken, geometryReady]);
// Live restyle — no reconnect, so the running agent is untouched. The canvas
// renderer caches rendered glyphs per colour in a texture atlas, so a theme
diff --git a/tests/unit/agentic_ide/test_session.py b/tests/unit/agentic_ide/test_session.py
index 8050649266..a6ebc8ac87 100644
--- a/tests/unit/agentic_ide/test_session.py
+++ b/tests/unit/agentic_ide/test_session.py
@@ -281,12 +281,14 @@ async def test_coming_back_rejoins_the_running_agent_and_replays_its_screen(
async def _capture(text: str) -> None:
seen.append(text)
- back = await registry.attach(term.name, 100, 30, _capture, _noop_exit)
+ fake_pty.resizes.clear()
+ back = await registry.attach(term.name, 80, 24, _capture, _noop_exit)
assert back.pty_id == original_pty, "the same agent process must be re-joined"
assert len(fake_pty.spawns) == spawns_before, "nothing may be respawned"
assert back.reattached is True
assert "building…" in "".join(seen), "the screen must come back with the pane"
+ assert fake_pty.resizes == [], "re-joining at the current size must not redraw it"
async def test_a_pane_whose_replay_lost_its_start_asks_the_agent_to_repaint(
@@ -319,27 +321,37 @@ async def test_a_pane_whose_replay_lost_its_start_asks_the_agent_to_repaint(
assert sizes[-1] == (100, 30), "the pane must be left at the size it really is"
-async def test_an_intact_replay_leaves_the_agent_alone(
+async def test_a_geometry_change_rebases_an_intact_replay_and_repaints(
registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
) -> None:
- """No nudge when the tail is whole — it already rebuilds the screen.
-
- The redraw is cheap but not free, and it is the common case that must stay
- untouched: a pane that printed less than its replay budget comes back from
- its own bytes.
- """
+ """Cursor moves recorded at one size must never be replayed at another."""
session = await _open(registry, tmp_path, [{"agent": "claude"}])
term = session.terminals[0]
await registry.attach(term.name, 80, 24, _noop_output, _noop_exit)
pty = term.pty_id
- await fake_pty.emit(pty, "\x1b[32mbuilding…\x1b[0m")
+ await fake_pty.emit(pty, "\x1b[?1049h\x1b[32mOLD STATUS ROW\x1b[0m")
registry.detach(term.key, session.id)
+ replayed: list[str] = []
+
+ async def _capture_replay(text: str) -> None:
+ replayed.append(text)
+
fake_pty.resizes.clear()
- await registry.attach(term.name, 100, 30, _noop_output, _noop_exit)
+ await registry.attach(
+ term.name,
+ 100,
+ 30,
+ _noop_output,
+ _noop_exit,
+ on_replay=_capture_replay,
+ )
sizes = [(cols, rows) for tid, cols, rows in fake_pty.resizes if tid == pty]
- assert sizes == [(100, 30)], "an intact replay must not cost a repaint"
+ restored = "".join(replayed)
+ assert "OLD STATUS ROW" not in restored
+ assert "\x1b[?1049h" in restored, "alternate-screen ownership must survive"
+ assert sizes == [(100, 30), (100, 29), (100, 30)]
async def test_closing_a_workspace_stops_only_its_own_agents(
@@ -536,8 +548,8 @@ async def test_a_displaced_viewer_cannot_resize_the_pane_it_lost(
assert fake_pty.resizes == [], "a displaced viewer must not move the agent's screen"
# The viewer that actually holds the pane still can.
- assert registry.resize(term.key, 200, 50, viewer=second_viewer) is True
- assert fake_pty.resizes == [(term.pty_id, 200, 50)]
+ assert registry.resize(term.key, 201, 50, viewer=second_viewer) is True
+ assert fake_pty.resizes == [(term.pty_id, 201, 50)]
async def test_an_internal_resize_needs_no_viewer(
@@ -554,3 +566,16 @@ async def test_an_internal_resize_needs_no_viewer(
assert registry.resize(term.key, 120, 40) is True
assert fake_pty.resizes == [(term.pty_id, 120, 40)]
+
+
+async def test_a_duplicate_resize_does_not_make_the_tui_repaint(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """The socket handshake already applied this size; its echo is a no-op."""
+ await _open(registry, tmp_path, [{"agent": "claude"}])
+ await registry.attach("T1", 80, 24, _noop_output, _noop_exit)
+ term = registry.session.terminals[0]
+ fake_pty.resizes.clear()
+
+ assert registry.resize(term.key, 80, 24) is True
+ assert fake_pty.resizes == []
diff --git a/tests/unit/agentic_ide/test_transcript.py b/tests/unit/agentic_ide/test_transcript.py
index f050c1f2a9..cf81252585 100644
--- a/tests/unit/agentic_ide/test_transcript.py
+++ b/tests/unit/agentic_ide/test_transcript.py
@@ -264,6 +264,24 @@ def test_an_untruncated_replay_is_still_verbatim() -> None:
assert buffer.text() == stream
+def test_rebasing_for_a_resize_drops_old_drawing_but_preserves_modes() -> None:
+ """A TUI stream is geometry-bound; its negotiated terminal state is not."""
+ buffer = ReplayBuffer()
+ buffer.feed("\x1b[?1049h\x1b[?1006hOLD STATUS ROW")
+
+ prologue = buffer.rebase_for_resize()
+
+ assert "OLD STATUS ROW" not in prologue
+ assert "OLD STATUS ROW" not in buffer.text()
+ assert "\x1b[?1049h" in prologue
+ assert "\x1b[?1006h" in prologue
+ assert prologue.endswith("\x1b[0m")
+ assert buffer.truncated is False
+
+ buffer.feed("NEW SCREEN")
+ assert buffer.text() == prologue + "NEW SCREEN"
+
+
def test_a_replay_forgets_the_modes_when_it_is_cleared() -> None:
buffer = ReplayBuffer(limit=32)
buffer.feed("\x1b[?1049h" + "z" * 100)