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): clear a pane before redrawing the screen it re-joined

Ruben Lütke4b0c1de8975d
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 8d4ad0e30e..b8619e74d8 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -2156,6 +2156,7 @@ class Registry:
on_exit: Any,
workspace_id: str | None = None,
appearance: str | None = None,
+ on_replay: Any = None,
) -> Terminal:
"""Point a viewer at terminal ``key`` — one attach at a time per pane.
@@ -2172,6 +2173,12 @@ class Registry:
immediately, and they are exactly what a burst of reconnecting panes
asks for. ``_attach_locked`` resolves again under the lock, because the
workspace may have closed while this attempt waited its turn.
+
+ ``on_replay`` receives the re-joined screen (see :meth:`_attach_locked`)
+ and exists so a viewer can tell it apart from live output. Omitted, the
+ replay goes to ``on_output`` — correct for an internal caller that only
+ wants the bytes, and wrong for a viewer that draws them, which is why
+ the socket route passes one.
"""
found = self._locate(key, workspace_id)
if found is None:
@@ -2188,6 +2195,7 @@ class Registry:
on_exit,
workspace_id=workspace_id,
appearance=appearance,
+ on_replay=on_replay,
)
async def _attach_locked(
@@ -2199,6 +2207,7 @@ class Registry:
on_exit: Any,
workspace_id: str | None = None,
appearance: str | None = None,
+ on_replay: Any = None,
) -> Terminal:
"""Point a viewer at terminal ``key``, starting its agent if needed.
@@ -2225,6 +2234,20 @@ class Registry:
progress every time somebody looked away, which is precisely what having
several workspaces would otherwise cost.
+ **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
+ screen, a replay REBUILDS one. A viewer that appended it instead drew
+ the agent's interface a second time over the copy already there — and
+ because an Ink TUI skips unchanged cells with cursor moves rather than
+ overwriting them with spaces, the two copies did not stack tidily, they
+ interleaved character by character ("plus everything new" came back as
+ "plueverythingwnew"). Reported 2026-07-29 across three panes; every
+ reconnect made it worse and nothing ever repaired it, because the agent
+ only ever redraws its own visible rows and never the scrollback above
+ them. Omitting ``on_replay`` keeps the old single-channel behaviour, for
+ internal callers that consume bytes rather than paint them.
+
**This is also where a conversation is continued rather than restarted.**
A pane holding a resume handle launches its CLI with the arguments that
reopen that conversation; a pane without one starts fresh and keeps
@@ -2272,7 +2295,11 @@ class Registry:
# 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.
- await on_output(replay)
+ #
+ # 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
diff --git a/jarvis/agentic_ide/transcript.py b/jarvis/agentic_ide/transcript.py
index 62735c3f9d..cf4139f9a1 100644
--- a/jarvis/agentic_ide/transcript.py
+++ b/jarvis/agentic_ide/transcript.py
@@ -279,10 +279,20 @@ class ReplayBuffer:
return self._mode_prologue() + "\x1b[0m" + text
def clear(self) -> None:
+ """Forget everything — this buffer is being handed to a fresh process.
+
+ Including the remembered modes. They describe what the PREVIOUS agent
+ negotiated, and it is gone; the new one states its own within its first
+ few hundred bytes, straight into the empty buffer below. Keeping them
+ would put a dead process's screen mode at the front of the next
+ truncated replay, and a viewer that clears before drawing a replay has
+ nothing else to derive its state from.
+ """
self._chunks.clear()
self._size = 0
self.truncated = False
self._open_escape = False
+ self._modes.clear()
__all__ = [
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index eb55c8cc7d..99ce157d25 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -2640,6 +2640,26 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
except Exception: # noqa: BLE001, S110 - viewer gone; transcript keeps filling
pass
+ async def on_replay(text: str) -> None:
+ """The screen this pane is re-joining, as the bytes that drew it.
+
+ Its own frame type rather than a large ``o``, because the viewer has to
+ do something different with it: clear the terminal first. The same bytes
+ appended to a screen that already holds a copy of that interface do not
+ stack tidily — a TUI skips unchanged cells with cursor moves instead of
+ overwriting them, so the two copies interleave character by character.
+ See ``SessionRegistry._attach_locked``.
+
+ A viewer that does not know this frame simply ignores it and comes back
+ blank rather than scrambled, which is the better of the two failures and
+ only reachable by a client older than this server.
+ """
+ async with send_lock:
+ try:
+ await ws.send_json({"t": "replay", "d": text})
+ except Exception: # noqa: BLE001, S110 - viewer gone; transcript keeps filling
+ pass
+
async def on_exit(code: int) -> None:
async with send_lock:
try:
@@ -2715,6 +2735,7 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
on_exit,
workspace_id=pane_workspace,
appearance=appearance,
+ on_replay=on_replay,
)
except SessionNotReady as exc:
# "Not yet", not "not here": this pane connected while its workspace was
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.offscreen.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.offscreen.test.tsx
index aaa97898e6..a5e81b3b68 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.offscreen.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.offscreen.test.tsx
@@ -11,10 +11,19 @@ import { render } from "@testing-library/react";
import { act } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+/**
+ * Recorded in `writes` rather than counted separately, because the ORDER is the
+ * contract: a reset after the replay wipes the screen it was supposed to draw.
+ *
+ * Hoisted because `vi.mock` factories run before the module body.
+ */
+const RESET = vi.hoisted(() => "<reset>");
+
const harness = vi.hoisted(() => ({
writes: [] as string[],
handlers: null as null | {
onOutput: (text: string) => void;
+ onReplay: (text: string) => void;
onExit: (code: number) => void;
onReady: (info: { resumed: boolean; reattached: boolean }) => void;
onTrouble: (message: string, retrying: boolean) => void;
@@ -55,6 +64,9 @@ vi.mock("@xterm/xterm", () => ({
write(text: string) {
harness.writes.push(text);
}
+ reset() {
+ harness.writes.push(RESET);
+ }
resize() {}
dispose() {}
clearTextureAtlas() {}
@@ -182,6 +194,42 @@ describe("AgenticTerminal off-screen output", () => {
expect(replayed).toHaveLength(opening.length + 40 * flood.length);
});
+ it("clears the screen before drawing a re-joined one", () => {
+ // The pane has been running; then the socket drops and comes back, and the
+ // server hands over the bytes that drew the screen the agent is looking at.
+ // Written onto what is still there, they draw that interface a SECOND time
+ // over the copy already on screen — and because an Ink TUI skips unchanged
+ // cells with cursor moves rather than overwriting them, the two copies
+ // interleave character by character instead of stacking (2026-07-29).
+ mount();
+ act(() => harness.handlers?.onOutput("the screen as it was"));
+ harness.writes = [];
+
+ act(() => harness.handlers?.onReplay("the screen as it is"));
+
+ expect(harness.writes).toEqual([RESET, "the screen as it is"]);
+ });
+
+ it("drops output parked before a replay rather than painting it after", () => {
+ // Parked output was captured from the screen the replay REPLACES. Written
+ // afterwards it paints the older screen over the newer one; the replay is
+ // the whole truth by the time it arrives.
+ mount();
+ act(() => harness.fire?.(false));
+ act(() => harness.handlers?.onOutput("older than the replay"));
+ expect(harness.writes).toEqual([]);
+
+ act(() => harness.handlers?.onReplay("the current screen"));
+ act(() => harness.fire?.(true));
+
+ const drawn = harness.writes.join("");
+ expect(drawn).not.toContain("older than the replay");
+ expect(drawn).toContain("the current screen");
+ // Still reset first, even though the write itself waited for the pane to
+ // come back — a replay parked and un-parked is still a rebuild.
+ expect(harness.writes[0]).toBe(RESET);
+ });
+
it("keeps the exit banner BEHIND the output it follows", () => {
// Writing the banner straight to xterm while output is parked would put
// "[exited]" above the lines that explain why.
@@ -194,9 +242,14 @@ describe("AgenticTerminal off-screen output", () => {
act(() => harness.fire?.(true));
const replayed = harness.writes.join("");
+ // Anchored on the banner's SHAPE — "[<pane name> …" — rather than on the
+ // wording of the explanation inside it. This assertion is about ordering,
+ // and it spent a while red because it matched the word "exited" that
+ // `explainExit` has since reworded to "stopped".
expect(replayed.indexOf("the last thing it said")).toBeLessThan(
- replayed.indexOf("exited"),
+ replayed.indexOf("[Claude Code"),
);
+ expect(replayed).toContain("[Claude Code");
});
it("does not park while the whole document is hidden", () => {
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index b5e8fc2ec8..c5b8453d1a 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -599,6 +599,40 @@ export function AgenticTerminal({
if (offscreen.full) term.write(offscreen.drain());
};
+ /**
+ * Draw the screen this pane is re-joining — on a terminal cleared first.
+ *
+ * A replay is not a big chunk of output, it is a REBUILD: the server hands
+ * over the raw bytes that drew the screen the agent is looking at, so that
+ * a pane which was away — a reconnect, a backend restart, a workspace
+ * switch — comes back showing the interface rather than a blank rectangle.
+ *
+ * Writing it onto whatever is already here draws that interface a second
+ * time over the copy still on screen, and the two do not stack tidily. An
+ * Ink TUI (Claude Code, Codex) skips unchanged cells with cursor moves
+ * instead of overwriting them with spaces, so the first copy shows THROUGH
+ * the second, character by character: "plus everything new" came back as
+ * "plueverythingwnew" (reported 2026-07-29, three panes, unreadable). Nor does
+ * it heal — the agent repaints its own visible rows and never the
+ * scrollback above them, so every reconnect added another layer.
+ *
+ * `reset()` rather than `clear()`: the replay re-states the screen modes
+ * the agent negotiated (alternate screen, mouse tracking), and those have
+ * to start from a known state or the pane inherits half of the old one.
+ */
+ const replayToPane = (text: string) => {
+ if (!text) return;
+ // Parked output belongs to the screen this replay REPLACES, and it was
+ // captured before it. Written afterwards it would paint the older screen
+ // over the newer one; written before, it would be reset away regardless.
+ offscreen.drain();
+ term.reset();
+ // Through the ordinary path, so a replay arriving while nobody is looking
+ // is parked and un-parked by the same rules as anything else — and so it
+ // counts as the pane having painted.
+ writeToPane(text);
+ };
+
/*
* The size the terminal PROCESS has actually been told.
*
@@ -674,6 +708,7 @@ export function AgenticTerminal({
requestAnimationFrame(sendResize);
},
onOutput: (text) => writeToPane(text),
+ onReplay: (text) => replayToPane(text),
/**
* A prompt just landed in this pane — make that impossible to miss.
*
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 3d96d8bac7..0e17cbd443 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.ts
@@ -56,6 +56,7 @@ function handlers() {
return {
onOpen: vi.fn(),
onOutput: vi.fn(),
+ onReplay: vi.fn(),
onReady: vi.fn(),
onExit: vi.fn(),
onTrouble: vi.fn(),
@@ -124,6 +125,27 @@ describe("openPaneSocket", () => {
socket.close();
});
+ it("keeps a re-joined screen off the live-output channel", () => {
+ const cb = handlers();
+ const socket = openPaneSocket({ name: "Mika", cols: 80, rows: 24 }, cb);
+ MockWebSocket.last!.fire("open");
+
+ // The same bytes on the two channels mean opposite things: live output
+ // continues the screen, a replay rebuilds it — and only the second one may
+ // clear the terminal first. Routed to `onOutput` instead, the re-joined
+ // interface is drawn on top of the copy already there and the two
+ // interleave into unreadable text (2026-07-29).
+ MockWebSocket.last!.deliver({ t: "replay", d: "\x1b[?1049h# the screen" });
+
+ expect(cb.onReplay).toHaveBeenCalledWith("\x1b[?1049h# the screen");
+ expect(cb.onOutput).not.toHaveBeenCalled();
+
+ MockWebSocket.last!.deliver({ t: "o", d: "live" });
+ expect(cb.onOutput).toHaveBeenCalledWith("live");
+ expect(cb.onReplay).toHaveBeenCalledTimes(1);
+ socket.close();
+ });
+
it("gives up when the pane is no longer part of the open workspace", async () => {
const cb = handlers();
const socket = openPaneSocket({ name: "Ghost", 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 77f2eeefc7..f7fd6adc03 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts
@@ -170,6 +170,24 @@ export interface PaneSocketHandlers {
/** The socket is up; the pane may send its measured size. */
onOpen?: () => void;
onOutput: (text: string) => void;
+ /**
+ * The screen this pane is re-joining, as the raw bytes that drew it.
+ *
+ * Separate from `onOutput` because it is a different instruction, not a
+ * bigger one: live output CONTINUES a screen, a replay REBUILDS it, and a
+ * handler that appends it draws the agent's interface a second time on top
+ * of the copy already there. That does not stack tidily — an Ink TUI skips
+ * unchanged cells with cursor moves instead of overwriting them with spaces,
+ * so the old copy shows through the new one character by character ("plus
+ * everything new" came back as "plueverythingwnew", reported 2026-07-29).
+ * Nothing repairs it either: the agent redraws its own visible rows and
+ * never the scrollback above them, so the mess survives every later repaint.
+ *
+ * The implementation therefore has exactly one obligation — reset the
+ * terminal before writing this — and it is required rather than optional so
+ * that a new pane cannot quietly forget it.
+ */
+ onReplay: (text: string) => void;
/**
* The agent is attached — freshly started, resumed, or re-joined.
*
@@ -409,6 +427,8 @@ export function openPaneSocket(
}
if (msg.t === "o") {
handlers.onOutput(msg.d ?? "");
+ } else if (msg.t === "replay") {
+ handlers.onReplay(msg.d ?? "");
} else if (msg.t === "ready") {
// A live handshake also clears the auth streak: whatever credential
// this attempt used, it worked.
diff --git a/tests/unit/agentic_ide/test_replay_channel.py b/tests/unit/agentic_ide/test_replay_channel.py
new file mode 100644
index 0000000000..b6e8493665
--- /dev/null
+++ b/tests/unit/agentic_ide/test_replay_channel.py
@@ -0,0 +1,169 @@
+"""A re-joined screen travels on its own channel, so a viewer can clear first.
+
+The defect these pin down (reported 2026-07-29, three panes unreadable). A pane
+that reconnects — a backend restart, a workspace switch, a moment of
+unreachability, all routine — is handed the raw bytes that drew the screen its
+agent is looking at, so it comes back showing the interface instead of a blank
+rectangle. Those bytes used to arrive as ordinary output, and the viewer did the
+only thing it can do with output: append it.
+
+That draws the agent's interface a SECOND time on top of the copy already on
+screen, and the two do not stack tidily. An Ink-based TUI (Claude Code, Codex)
+skips unchanged cells with cursor moves instead of overwriting them with spaces,
+so the older copy shows THROUGH the newer one character by character — "plus
+everything new" came back as "plueverythingwnew". Nothing repaired it either: the agent
+redraws its own visible rows and never the scrollback above them, so every
+reconnect stacked one more layer.
+
+The fix is a distinction, not a filter: live output CONTINUES a screen, a replay
+REBUILDS one, and only the second may reset the terminal. These tests hold the
+two apart at the seam where they are produced.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import session as ide
+from jarvis.agentic_ide.transcript import ReplayBuffer
+from tests.fakes.fake_pty_manager import FakePtyManager
+
+
+def pool(monkeypatch: pytest.MonkeyPatch) -> FakePtyManager:
+ monkeypatch.setattr(ide, "agent_argv", lambda name: (f"/usr/bin/{name}",))
+ monkeypatch.setattr(ide, "COLD_START_SETTLE_S", 0.0)
+ return FakePtyManager()
+
+
+async def _gone(_code: int) -> None:
+ return None
+
+
+class Viewer:
+ """One socket's two channels, kept apart the way the route keeps them."""
+
+ def __init__(self) -> None:
+ self.output: list[str] = []
+ self.replay: list[str] = []
+
+ async def on_output(self, text: str) -> None:
+ self.output.append(text)
+
+ async def on_replay(self, text: str) -> None:
+ self.replay.append(text)
+
+
+async def _running_pane(pool: FakePtyManager, folder: Path): # noqa: ANN202 - internal fixture
+ """A pane whose agent has already painted something, ready to be re-joined."""
+ registry = ide.Registry(pty_manager=pool)
+ session = await registry.start(str(folder), [{"agent": "claude"}])
+ term = session.terminals[0]
+ first = Viewer()
+ await registry.attach(
+ term.key,
+ 80,
+ 24,
+ first.on_output,
+ _gone,
+ workspace_id=session.id,
+ on_replay=first.on_replay,
+ )
+ await pool.emit(term.pty_id, "\x1b[?1049h┌─ Claude Code ─┐\r\n")
+ return registry, session, term
+
+
+async def test_a_rejoined_screen_arrives_as_a_replay(
+ pool: FakePtyManager, tmp_path: Path
+) -> None:
+ """The whole bug in one assertion: the screen must not look like output."""
+ registry, session, term = await _running_pane(pool, tmp_path)
+ back = Viewer()
+
+ await registry.attach(
+ term.key,
+ 80,
+ 24,
+ back.on_output,
+ _gone,
+ workspace_id=session.id,
+ on_replay=back.on_replay,
+ )
+
+ assert "".join(back.replay).endswith("┌─ Claude Code ─┐\r\n"), (
+ "the re-joining viewer is handed the screen on the replay channel"
+ )
+ assert back.output == [], (
+ "and NOT as output — a viewer appends output, which draws the agent's "
+ "interface a second time over the copy already on its screen"
+ )
+
+
+async def test_live_output_after_a_rejoin_is_still_output(
+ pool: FakePtyManager, tmp_path: Path
+) -> None:
+ """The distinction must not swallow the stream it was carved out of.
+
+ A replay channel that kept receiving after the handover would make the
+ viewer reset its terminal on every frame the agent prints.
+ """
+ registry, session, term = await _running_pane(pool, tmp_path)
+ back = Viewer()
+ await registry.attach(
+ term.key,
+ 80,
+ 24,
+ back.on_output,
+ _gone,
+ workspace_id=session.id,
+ on_replay=back.on_replay,
+ )
+ replayed = len(back.replay)
+
+ await pool.emit(term.pty_id, "· Working…")
+
+ assert back.output == ["· Working…"], "live frames stay on the output channel"
+ assert len(back.replay) == replayed, "and nothing further arrives as a replay"
+
+
+async def test_a_caller_without_a_replay_channel_still_gets_the_screen(
+ pool: FakePtyManager, tmp_path: Path
+) -> None:
+ """Omitting ``on_replay`` means one channel, not a lost screen.
+
+ Internal callers consume the bytes rather than paint them, and a re-attach
+ that silently dropped the screen for them would be the same class of bug
+ this fix exists to remove, pointed the other way.
+ """
+ registry, session, term = await _running_pane(pool, tmp_path)
+ back = Viewer()
+
+ await registry.attach(term.key, 80, 24, back.on_output, _gone, workspace_id=session.id)
+
+ assert "".join(back.output).endswith("┌─ Claude Code ─┐\r\n")
+ assert back.replay == []
+
+
+def test_a_cleared_buffer_forgets_the_dead_process_modes() -> None:
+ """A fresh process negotiates its own screen modes — the old ones are gone.
+
+ ``clear()`` runs when a pane's agent is replaced, and the modes describe
+ what the PREVIOUS one asked for. Kept, they are re-stated at the front of
+ the next truncated replay, which now lands on a terminal the viewer has
+ just reset — so they would be the only thing telling it what screen it is
+ on, and they would be wrong.
+ """
+ buffer = ReplayBuffer(limit=64)
+ buffer.feed("\x1b[?1049h")
+ buffer.feed("x" * 128)
+ assert buffer.truncated, "the fixture has to actually overflow to matter"
+ assert "1049h" in buffer.text(), "a truncated replay re-states the live modes"
+
+ buffer.clear()
+ buffer.feed("y" * 128)
+
+ assert "1049" not in buffer.text(), (
+ "the replaced process's screen mode must not lead the next replay"
+ )