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(ide): stop repeated Codex terminal height nudges (#275)

Ruben Lütke743c09effe6c
diff --git a/jarvis/agentic_ide/transcript.py b/jarvis/agentic_ide/transcript.py
index 143c246444..e14b9107d2 100644
--- a/jarvis/agentic_ide/transcript.py
+++ b/jarvis/agentic_ide/transcript.py
@@ -56,8 +56,16 @@ _PRIVATE_MODE_RE = re.compile(r"\x1b\[\?([0-9;]+)([hl])")
# after any byte, including between ``ESC[?10`` and ``00h``.
_PRIVATE_MODE_PARTIAL_RE = re.compile(r"\x1b(?:\[(?:\?(?:[0-9;]*))?)?$")
_PRIVATE_MODE_PARTIAL_MAX = 128
-#: ``ESC [ 2 J`` — erase the whole screen, the first thing a full repaint sends.
-_FULL_CLEAR = "\x1b[2J"
+# A full erase is either ED 2, or ED 0 after moving to the top-left cell.
+# Codex uses the latter. Missing it made successful redraws trigger all five
+# height nudges, visibly moving the terminal down and up every half second.
+# Only intervening controls that cannot move the cursor are accepted.
+# Kept in step with frontend/terminalRepaint.ts by shared protocol fixtures.
+_FULL_CLEAR_RE = re.compile(
+ r"\x1b\[2J|\x1b\[(?:0*1?)(?:;0*1?)?[Hf]"
+ r"(?:\x1b\[[0-9;:]*m|\x1b\[\?(?:25|2026)[hl])*\x1b\[0*J"
+)
+_FULL_CLEAR_SCAN_TAIL = 128
_DECORATION_CHARS = set("─│┌┐└┘├┤┬┴┼━┃╭╮╯╰═║╔╗╚╝╠╣╦╩╬▀▄█▌▐░▒▓▔▁·.-_=*#~ ")
_SPINNER_CHARS = set("|/\\-◐◓◑◒✻✽✢·✳✶⣿")
@@ -246,11 +254,14 @@ class ReplayBuffer:
if not chunk:
return
self._note_modes(chunk)
+ previous = len(self._clear_scan_tail)
scanned = self._clear_scan_tail + chunk
- # The tail is shorter than the sequence, so no erase is counted twice.
- self.clears += scanned.count(_FULL_CLEAR)
- self._clear_scan_tail = scanned[-(len(_FULL_CLEAR) - 1) :]
- erase = chunk.rfind(_FULL_CLEAR) if self.holds_screen else -1
+ # The longer scan tail can contain an already counted erase. Count
+ # only matches completed by this read, including split home/ED pairs.
+ erases = [match for match in _FULL_CLEAR_RE.finditer(scanned) if match.end() > previous]
+ self.clears += len(erases)
+ self._clear_scan_tail = scanned[-_FULL_CLEAR_SCAN_TAIL:]
+ erase = erases[-1].start() if erases and self.holds_screen else -1
if erase >= 0:
# A full-screen agent just emptied its screen, so everything it
# drew before this is gone from it — and what follows is a frame
@@ -262,7 +273,7 @@ class ReplayBuffer:
# answered — which a busy Claude Code does only half the time
# (2026-09-29). The modes the dropped bytes negotiated are kept
# the same way ``rebase_for_resize`` keeps them.
- self._rebase(chunk[erase:])
+ self._rebase(scanned[erase:])
return
self._chunks.append(chunk)
self._size += len(chunk)
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 20014e66b1..69c4fec198 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
@@ -6,6 +6,8 @@ const terminalHarness = vi.hoisted(() => ({
host: { current: null as HTMLElement | null },
observe: vi.fn(),
fit: vi.fn(),
+ clearTextureAtlas: vi.fn(),
+ spacingAtOpen: [] as unknown[],
/** What the terminal reports after a fit — a test moves it to grow the pane. */
size: { cols: 80, rows: 24 },
/** Every frame the pane hands its socket. Returns whether it went out. */
@@ -107,6 +109,7 @@ vi.mock("@xterm/xterm", () => ({
loadAddon() {}
open(host: HTMLElement) {
terminalHarness.open(host);
+ terminalHarness.spacingAtOpen.push(this.options.letterSpacing);
terminalHarness.host.current = host;
}
focus() {
@@ -153,7 +156,7 @@ vi.mock("@xterm/xterm", () => ({
terminalHarness.resize(cols, rows);
}
dispose() {}
- clearTextureAtlas() {}
+ clearTextureAtlas() { terminalHarness.clearTextureAtlas(this); }
},
}));
@@ -720,7 +723,7 @@ describe("AgenticTerminal layout", () => {
expect(region?.className).not.toContain("invisible");
});
- it("waits for a promised repaint rather than showing the broken tail", () => {
+ it.each(["\x1b[2", "\x1b[1;1H\x1b["])("waits for a promised repaint and recognizes split erases: %j", (eraseStart) => {
// A replay the server marks as needing a repaint cannot rebuild the screen
// by itself. A busy agent may answer the repaint request late (the server
// repeats it after half a second), and revealing on quiet in between showed
@@ -752,7 +755,7 @@ describe("AgenticTerminal layout", () => {
// The erase arrives split across two chunks; the quiet window follows it.
act(() => {
- terminalHarness.handlers.current?.onOutput?.("\x1b[2" as never);
+ terminalHarness.handlers.current?.onOutput?.(eraseStart as never);
terminalHarness.handlers.current?.onOutput?.("Jthe repainted screen" as never);
});
expect(region?.className).toContain("invisible");
@@ -2641,6 +2644,8 @@ describe("renaming a pane", () => {
describe("terminal text size across a rebuild", () => {
beforeEach(() => {
terminalHarness.instances.length = 0;
+ terminalHarness.clearTextureAtlas.mockClear();
+ terminalHarness.spacingAtOpen.length = 0;
globalThis.ResizeObserver = ResizeObserverHarness;
});
@@ -2650,6 +2655,51 @@ describe("terminal text size across a rebuild", () => {
const newest = () => terminalHarness.instances[terminalHarness.instances.length - 1];
+ it.each(["light", "dark"] as const)("keeps the glyph cache warm when opening and restarting %s panes", (appearance) => {
+ const pane = (name: string, restartToken = 0) => (
+ <AgenticTerminal key={name} name={name} displayName="Codex" appearance={appearance} fontSize={13} restartToken={restartToken} />
+ );
+ const view = render(<>{pane("First")}</>);
+ expect(terminalHarness.clearTextureAtlas).not.toHaveBeenCalled();
+ const first = newest();
+
+ view.rerender(<>{pane("First")}{pane("Second")}</>);
+ expect(terminalHarness.instances).toHaveLength(2);
+ expect(terminalHarness.instances[0]).toBe(first);
+ expect(terminalHarness.clearTextureAtlas).not.toHaveBeenCalled();
+
+ view.rerender(<>{pane("First")}{pane("Second", 1)}</>);
+ expect(terminalHarness.instances).toHaveLength(3);
+ expect(terminalHarness.clearTextureAtlas).not.toHaveBeenCalled();
+ });
+
+ it("still refreshes glyphs on real theme and font changes without reconnecting", () => {
+ const view = render(<AgenticTerminal name="Dana" displayName="Codex" appearance="dark" fontSize={13} />);
+ const terminal = newest();
+ terminalHarness.clearTextureAtlas.mockClear();
+
+ view.rerender(<AgenticTerminal name="Dana" displayName="Codex" appearance="light" fontSize={13} />);
+ expect(terminalHarness.clearTextureAtlas).toHaveBeenCalledTimes(1);
+ expect(newest().options.theme).not.toBeUndefined();
+
+ view.rerender(<AgenticTerminal name="Dana" displayName="Codex" appearance="light" fontSize={18} />);
+ expect(terminalHarness.clearTextureAtlas).toHaveBeenCalledTimes(2);
+ expect(newest().options.fontSize).toBe(18);
+ expect(newest()).toBe(terminal);
+ expect(terminalHarness.instances).toHaveLength(1);
+ });
+
+ it("aligns fractional font cells before opening the renderer and measuring the first grid", () => {
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({
+ font: "",
+ measureText: () => ({ width: 249.6 }),
+ } as unknown as CanvasRenderingContext2D);
+
+ render(<AgenticTerminal name="Dana" displayName="Codex" appearance="dark" fontSize={13} />);
+ expect(terminalHarness.spacingAtOpen).toEqual([1]);
+ expect(terminalHarness.clearTextureAtlas).not.toHaveBeenCalled();
+ });
+
it("keeps the xterm canvas clear over the shared translucent pane shell", () => {
render(
<AgenticTerminal
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index a7a3524ecf..c521073822 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -137,6 +137,8 @@ import {
PARKED_RECHECK_MS,
} from "./offscreenBuffer";
import { installQuerySuppression } from "./terminalQueries";
+import { installSynchronizedOutput } from "./terminalSynchronizedOutput";
+import { FULL_SCREEN_ERASE_SCAN_TAIL, hasFullScreenErase } from "./terminalRepaint";
import {
bindTerminalScrollRegion,
captureWheelForTerminalHistory,
@@ -245,9 +247,6 @@ export const REBUILD_SETTLE_MAX_MS = 450;
*/
export const REPAINT_WAIT_MAX_MS = 1_400;
-/** The whole-screen erase a full-screen agent's repaint starts with. */
-const FULL_SCREEN_ERASE = "\x1b[2J";
-
/**
* The longest an active pane's surface may stay behind a curtain, full stop.
*
@@ -1035,6 +1034,10 @@ export function AgenticTerminal({
} catch {
/* proposed API unavailable in this build — widths stay at Unicode 6 */
}
+ // Align before the renderer joins the shared glyph atlas and before the
+ // first fit/handshake. Correcting spacing afterwards changes the grid and
+ // invalidates every existing pane's cache just to open an empty terminal.
+ alignTerminalCells(term);
term.open(container);
// The wheel always moves xterm's own history, even while a normal-buffer
// CLI has negotiated mouse tracking — otherwise scrolling only "works"
@@ -1052,6 +1055,7 @@ export function AgenticTerminal({
// The fallback renderer starts on an empty surface.
term.refresh(0, term.rows - 1);
});
+ const synchronizedOutput = installSynchronizedOutput(term);
termRef.current = term;
fitRef.current = fit;
setTerminalEpoch((current) => current + 1);
@@ -1368,12 +1372,12 @@ export function AgenticTerminal({
const noteRepaintOutput = (text: string) => {
if (!repaintPending) return;
const scanned = eraseScanTail + text;
- if (scanned.includes(FULL_SCREEN_ERASE)) {
+ if (hasFullScreenErase(scanned)) {
repaintPending = false;
eraseScanTail = "";
return;
}
- eraseScanTail = scanned.slice(-(FULL_SCREEN_ERASE.length - 1));
+ eraseScanTail = scanned.slice(-FULL_SCREEN_ERASE_SCAN_TAIL);
};
const clearSettleTimers = () => {
@@ -1523,6 +1527,7 @@ export function AgenticTerminal({
setTailReady(false);
armCurtainWatchdog();
}
+ synchronizedOutput.reset();
term.reset();
// A normal-buffer CLI's replay is its whole scrollback — up to the
// server's 128 KB (see `ReplayBuffer`) — and xterm parses it in time
@@ -2289,6 +2294,7 @@ export function AgenticTerminal({
disposePasteBridge();
disposeNewlineBridge();
disposeQuerySuppression();
+ synchronizedOutput.dispose();
try {
socket?.close();
} catch {
@@ -2415,24 +2421,25 @@ export function AgenticTerminal({
* change has to invalidate it or the old palette keeps being painted.
*
* `terminalEpoch` is in here, and in the size effect below, for a reason the
- * appearance prop alone cannot cover: these effects fire on CHANGES, and the
- * terminal underneath them can be replaced without one. Every rebuild bumps
- * the epoch, so the pane restates the current theme and size to the new
- * terminal instead of trusting that it was born with them.
+ * appearance prop alone cannot cover: the terminal can be replaced without
+ * either prop changing. Check the replacement's actual options, but leave a
+ * correctly initialized terminal alone. Clearing its shared atlas on mount
+ * makes every existing WebGL pane rebuild its glyphs too.
*/
useEffect(() => {
const term = termRef.current;
if (!term) return;
- term.options.theme = themeFor(appearance);
+ const theme = themeFor(appearance);
+ if (term.options.theme === theme) return;
+ term.options.theme = theme;
clearTerminalTextureAtlas(term);
}, [appearance, terminalEpoch]);
useEffect(() => {
const term = termRef.current;
- if (!term) return;
- // A no-op on a terminal already built at this size (xterm's setter drops a
- // write of the identical value), which is what makes restating it on every
- // rebuild free.
+ if (!term || term.options.fontSize === fontSize) return;
+ // The setter itself skips unchanged values; the alignment, atlas clear and
+ // resize below must also run only for an actual size change.
term.options.fontSize = fontSize;
// A new size is a new glyph advance, and so a new fraction of a pixel for
// the canvas renderer to floor away. Re-align before the fit below, or the
diff --git a/jarvis/ui/web/frontend/src/components/agentic/RetainedWorkspaceGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/RetainedWorkspaceGrid.test.tsx
new file mode 100644
index 0000000000..b2c497d1c2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/RetainedWorkspaceGrid.test.tsx
@@ -0,0 +1,93 @@
+import { useEffect } from "react";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { SessionState } from "@/lib/agenticIdeApi";
+
+const lifecycle = vi.hoisted(() => ({ mount: vi.fn(), unmount: vi.fn() }));
+vi.mock("./WorkspaceTerminalGrid", () => ({
+ WorkspaceTerminalGrid: ({ session, active, disabled }: { session: SessionState; active: boolean; disabled: boolean }) => {
+ useEffect(() => {
+ lifecycle.mount(session.id);
+ return () => lifecycle.unmount(session.id);
+ }, []);
+ return <input aria-label={session.id} data-active={String(active)} disabled={disabled} defaultValue={session.name} />;
+ },
+}));
+import { RetainedWorkspaceGrid } from "./RetainedWorkspaceGrid";
+
+const session = (id: string, count = 1) => ({
+ id, name: id,
+ terminals: Array.from({ length: count }, (_, index) => ({ key: `${id}-${index}`, history_id: `${id}-${index}` })),
+}) as SessionState;
+const props = {
+ onScreen: true, selected: "", fontSize: 13, appearance: null,
+ onChanged: vi.fn(), onAdd: vi.fn(), onClose: vi.fn(), onSelect: vi.fn(),
+};
+beforeEach(() => { vi.clearAllMocks(); });
+afterEach(cleanup);
+
+describe("retained workspace terminals", () => {
+ it("keeps the same terminal view and input when switching away and back", () => {
+ const first = session("first");
+ const second = session("second");
+ const view = render(<RetainedWorkspaceGrid {...props} session={first} />);
+ const input = screen.getByLabelText("first");
+ fireEvent.change(input, { target: { value: "unfinished input" } });
+ view.rerender(<RetainedWorkspaceGrid {...props} session={second} />);
+ expect(input.closest("[hidden]")).not.toBeNull();
+ expect(input.getAttribute("data-active")).toBe("false");
+ expect(input.hasAttribute("disabled")).toBe(true);
+ view.rerender(<RetainedWorkspaceGrid {...props} session={{ ...first }} />);
+ expect(screen.getByLabelText("first")).toBe(input);
+ expect((input as HTMLInputElement).value).toBe("unfinished input");
+ expect(input.closest("[hidden]")).toBeNull();
+ expect(input.getAttribute("data-active")).toBe("true");
+ expect(lifecycle.mount).toHaveBeenCalledTimes(2);
+ expect(lifecycle.unmount).not.toHaveBeenCalled();
+ });
+
+ it("parks every retained view when the IDE is offscreen", () => {
+ const view = render(<RetainedWorkspaceGrid {...props} session={session("first")} />);
+ view.rerender(<RetainedWorkspaceGrid {...props} session={session("second")} />);
+ view.rerender(<RetainedWorkspaceGrid {...props} session={session("second")} onScreen={false} />);
+ expect(document.querySelectorAll("[data-active=true]")).toHaveLength(0);
+ expect(lifecycle.unmount).not.toHaveBeenCalled();
+ });
+
+ it("evicts the least recently visited workspace after three views", () => {
+ const view = render(<RetainedWorkspaceGrid {...props} session={session("first")} />);
+ for (const id of ["second", "third", "first", "fourth"]) {
+ view.rerender(<RetainedWorkspaceGrid {...props} session={session(id)} />);
+ }
+ expect(lifecycle.unmount).toHaveBeenCalledExactlyOnceWith("second");
+ expect(screen.queryByLabelText("second")).toBeNull();
+ expect(document.querySelectorAll("input")).toHaveLength(3);
+ });
+
+ it("bounds retained panes while always allowing the active workspace", () => {
+ const view = render(<RetainedWorkspaceGrid {...props} session={session("first", 6)} />);
+ view.rerender(<RetainedWorkspaceGrid {...props} session={session("second", 6)} />);
+ expect(lifecycle.unmount).not.toHaveBeenCalled();
+ view.rerender(<RetainedWorkspaceGrid {...props} session={session("large", 16)} />);
+ expect(screen.queryByLabelText("first")).toBeNull();
+ expect(screen.queryByLabelText("second")).toBeNull();
+ expect(screen.getByLabelText("large")).toBeTruthy();
+ });
+
+ it("releases closed workspaces and views made stale by a transferred pane", () => {
+ const first = session("first");
+ const view = render(<RetainedWorkspaceGrid {...props} session={first} workspaceIds={["first", "second"]} />);
+ view.rerender(<RetainedWorkspaceGrid {...props} session={session("second")} workspaceIds={["second"]} />);
+ expect(screen.queryByLabelText("first")).toBeNull();
+ view.rerender(<RetainedWorkspaceGrid {...props} session={{ ...session("third"), terminals: session("second").terminals }} />);
+ expect(screen.queryByLabelText("second")).toBeNull();
+ expect(screen.getByLabelText("third")).toBeTruthy();
+ });
+
+ it("releases all retained views on unmount", () => {
+ const view = render(<RetainedWorkspaceGrid {...props} session={session("first")} />);
+ view.rerender(<RetainedWorkspaceGrid {...props} session={session("second")} />);
+ view.unmount();
+ expect(lifecycle.unmount.mock.calls).toEqual([["second"], ["first"]]);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/RetainedWorkspaceGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/RetainedWorkspaceGrid.tsx
new file mode 100644
index 0000000000..1705fa6269
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/RetainedWorkspaceGrid.tsx
@@ -0,0 +1,41 @@
+import { useLayoutEffect, useRef, type ComponentProps } from "react";
+import { WorkspaceTerminalGrid } from "./WorkspaceTerminalGrid";
+
+type GridProps = ComponentProps<typeof WorkspaceTerminalGrid>;
+
+// Bound retained renderers and scrollback. A larger active workspace is always
+// allowed, but then keeps no background workspace alive.
+const MAX_WARM_PANES = 12;
+const MAX_WARM_WORKSPACES = 3;
+
+type Props = GridProps & {
+ onScreen: boolean;
+ workspaceIds?: readonly string[];
+};
+
+/** Keep recent terminal views alive instead of replaying their history on every switch. */
+export function RetainedWorkspaceGrid({ onScreen, workspaceIds, ...current }: Props) {
+ const retained = useRef<GridProps[]>([]);
+ const activePaneIds = new Set(current.session.terminals.flatMap((pane) => pane.history_id ? [pane.history_id] : []));
+ const entries = [current];
+ let panes = current.session.terminals.length;
+ for (const previous of retained.current) {
+ if (previous.session.id === current.session.id) continue;
+ if (workspaceIds && !workspaceIds.includes(previous.session.id)) continue;
+ // A transferred pane belongs to its new workspace. Do not retain another
+ // viewer from the source workspace's stale snapshot.
+ if (previous.session.terminals.some((pane) => pane.history_id && activePaneIds.has(pane.history_id))) continue;
+ if (entries.length >= MAX_WARM_WORKSPACES || panes + previous.session.terminals.length > MAX_WARM_PANES) continue;
+ entries.push(previous);
+ panes += previous.session.terminals.length;
+ }
+ useLayoutEffect(() => { retained.current = entries; });
+
+ return <>{entries.map((entry) => {
+ const visible = entry.session.id === current.session.id;
+ const active = onScreen && visible;
+ return <div key={entry.session.id} hidden={!visible} className="h-full min-h-0" data-workspace-terminal-view={entry.session.id}>
+ <WorkspaceTerminalGrid {...entry} active={active} disabled={!active || entry.disabled} />
+ </div>;
+ })}</>;
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsx
index bdcf78404e..b9508a7337 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsx
@@ -8,9 +8,10 @@ vi.mock("@/store/events", () => ({ useEventStore: (select: (state: unknown) => u
vi.mock("./AgenticTerminal", () => ({ AgenticTerminal: (props: {
name: string; onToggleMaximize: () => void; onRestart: () => void; restartToken: number;
onFocus: () => void;
+ active?: boolean; focused?: boolean;
onArrangeStart?: (event: React.PointerEvent) => void;
headerMode?: string; markFocus?: boolean;
-}) => <div onMouseDown={props.onFocus} data-testid={`pane-${props.name}`} data-header-mode={props.headerMode} data-mark-focus={String(props.markFocus)}>
+}) => <div onMouseDown={props.onFocus} data-testid={`pane-${props.name}`} data-header-mode={props.headerMode} data-mark-focus={String(props.markFocus)} data-active={String(props.active)} data-focused={String(props.focused)}>
<button onClick={props.onToggleMaximize}>Maximize {props.name}</button>
<button type="button" data-ide-drag-handle="true" onPointerDown={props.onArrangeStart}>Move {props.name}</button>
<button onClick={props.onRestart}>Restart {props.name}</button>
@@ -52,6 +53,18 @@ function Controlled() {
beforeEach(() => { vi.clearAllMocks(); });
afterEach(cleanup);
+it("parks retained terminals and releases keyboard focus while their workspace is inactive", () => {
+ const session = makeSession(["T1"]);
+ const view = render(<WorkspaceTerminalGrid {...props} session={session} selected="T1" />);
+ const pane = screen.getByTestId("pane-T1");
+ expect(pane.getAttribute("data-active")).toBe("true");
+ expect(pane.getAttribute("data-focused")).toBe("true");
+ view.rerender(<WorkspaceTerminalGrid {...props} session={session} selected="T1" active={false} />);
+ expect(screen.getByTestId("pane-T1")).toBe(pane);
+ expect(pane.getAttribute("data-active")).toBe("false");
+ expect(pane.getAttribute("data-focused")).toBe("false");
+});
+
it("swaps immediately, persists once and preserves mounted terminal nodes", async () => {
let finish!: (state: SessionState) => void;
api.move.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
@@ -222,6 +235,16 @@ it("drags the seam between two panes to resize them and saves the new sizes", as
} finally { vi.useRealTimers(); }
});
+it("leaves a maximize request pending until its retained workspace is active", () => {
+ act(() => useIdeChatStore.setState({ paneRequest: { workspaceId: "w1", pane: "T1", nonce: 6, maximize: true } }));
+ const session = makeSession();
+ const view = render(<WorkspaceTerminalGrid {...props} session={session} active={false} />);
+ expect(useIdeChatStore.getState().paneRequest?.maximize).toBe(true);
+ view.rerender(<WorkspaceTerminalGrid {...props} session={session} active />);
+ expect(useIdeChatStore.getState().paneRequest?.maximize).toBe(false);
+ act(() => useIdeChatStore.setState({ paneRequest: null }));
+});
+
it("maximizes the pane the office asked for, once, and only in its own workspace", () => {
act(() => useIdeChatStore.setState({ paneRequest: { workspaceId: "w2", pane: "T3", nonce: 7, maximize: true } }));
const { unmount } = render(<WorkspaceTerminalGrid {...props} session={makeSession()} />);
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx
index 801f6422db..304a77dbf4 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx
@@ -39,6 +39,8 @@ function writeStyle(node: HTMLElement, style: React.CSSProperties) {
}
interface Props {
+ /** Hidden retained workspaces keep their sockets but park output and focus. */
+ active?: boolean;
session: SessionState;
onChanged: (session: SessionState) => void;
/** Open the agent picker; with an anchor, the new pane splits off that pane. */
@@ -63,7 +65,7 @@ interface Props {
interface DropTarget { id: string; position: PaneMovePosition; allowed: boolean }
interface DragFeedback { id: string; target: DropTarget | null; x: number; y: number }
-export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSelect, selected, maxPanes = MAX_WORKSPACE_PANES, fontSize, appearance, disabled = false, onMutationStart, onMutationEnd, paneStyle: look = "classic" }: Props) {
+export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSelect, selected, maxPanes = MAX_WORKSPACE_PANES, fontSize, appearance, disabled = false, onMutationStart, onMutationEnd, paneStyle: look = "classic", active = true }: Props) {
const theme = useThemeValue();
const pushToast = useEventStore((state) => state.pushToast);
// The pane an agent card in the side panel pointed at, framed in blue.
@@ -139,12 +141,12 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSe
const paneRequest = useIdeChatStore((state) => state.paneRequest);
const settlePaneMaximize = useIdeChatStore((state) => state.settlePaneMaximize);
useEffect(() => {
- if (!paneRequest?.maximize || paneRequest.workspaceId !== session.id) return;
+ if (!active || !paneRequest?.maximize || paneRequest.workspaceId !== session.id) return;
const terminal = session.terminals.find((entry) => entry.name === paneRequest.pane);
if (!terminal) return;
settlePaneMaximize(paneRequest.nonce);
setMaximized(idOf(terminal));
- }, [paneRequest, session.id, session.terminals, settlePaneMaximize]);
+ }, [active, paneRequest, session.id, session.terminals, settlePaneMaximize]);
useEffect(() => { if (disabled) dragCleanup.current?.(); }, [disabled]);
useEffect(() => {
const node = frame.current;
@@ -408,10 +410,10 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSe
drag?.id === id && "opacity-50",
spotlitPane === terminal.name && "ring-2 ring-accent ring-offset-2 ring-offset-background",
visibleMaximized && visibleMaximized !== id && "hidden")}>
- <AgenticTerminal headerMode={minimal ? "minimal" : "compact"} agent={terminal.agent}
+ <AgenticTerminal active={active} headerMode={minimal ? "minimal" : "compact"} agent={terminal.agent}
name={terminal.name} workspaceId={session.id} displayName={terminal.display_name}
recap={terminal.recap} promptCount={terminal.prompts_sent} appearance={appearance ?? theme} fontSize={fontSize}
- focused={selected === terminal.name} markFocus={!panelInUse}
+ focused={active && selected === terminal.name} markFocus={!panelInUse}
onFocus={() => { if (spotlitPane && spotlitPane !== terminal.name) setSpotlight(null); setPanelInUse(false); onSelect(terminal.name); }}
layoutBusy={resizing}
maximized={visibleMaximized === id} onToggleMaximize={() => setMaximized((current) => current === id ? null : id)}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/terminalRepaint.test.ts b/jarvis/ui/web/frontend/src/components/agentic/terminalRepaint.test.ts
new file mode 100644
index 0000000000..9020104109
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalRepaint.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+import cases from "../../../../../../../tests/fakes/terminal_repaint_cases.json";
+import { FULL_SCREEN_ERASE_SCAN_TAIL, hasFullScreenErase } from "./terminalRepaint";
+
+describe("full terminal repaint acknowledgement", () => {
+ it.each(cases.full)("accepts a full redraw across any chunk boundary: %j", (erase) => {
+ for (let split = 1; split < erase.length; split++) {
+ expect(hasFullScreenErase(erase.slice(0, split))).toBe(false);
+ const tail = erase.slice(0, split).slice(-FULL_SCREEN_ERASE_SCAN_TAIL);
+ expect(hasFullScreenErase(tail + erase.slice(split))).toBe(true);
+ }
+ });
+
+ it.each(cases.partial)("does not release the curtain for a partial erase: %j", (erase) => {
+ expect(hasFullScreenErase(erase)).toBe(false);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/terminalRepaint.ts b/jarvis/ui/web/frontend/src/components/agentic/terminalRepaint.ts
new file mode 100644
index 0000000000..a3254a446f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalRepaint.ts
@@ -0,0 +1,10 @@
+/** Shared protocol cases also test ReplayBuffer's backend acknowledgement. */
+const FULL_SCREEN_ERASE = /\x1b\[2J|\x1b\[(?:0*1?)(?:;0*1?)?[Hf](?:\x1b\[[0-9;:]*m|\x1b\[\?(?:25|2026)[hl])*\x1b\[0*J/;
+
+/** Retain enough of a split cursor-home/erase pair and its color controls. */
+export const FULL_SCREEN_ERASE_SCAN_TAIL = 128;
+
+/** ED 0 clears the whole screen only immediately after a cursor-home. */
+export function hasFullScreenErase(text: string): boolean {
+ return FULL_SCREEN_ERASE.test(text);
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/terminalSynchronizedOutput.test.ts b/jarvis/ui/web/frontend/src/components/agentic/terminalSynchronizedOutput.test.ts
new file mode 100644
index 0000000000..e6c892d5ee
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalSynchronizedOutput.test.ts
@@ -0,0 +1,148 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { Terminal } from "@xterm/xterm";
+import { installSynchronizedOutput, SYNCHRONIZED_OUTPUT_TIMEOUT_MS } from "./terminalSynchronizedOutput";
+
+function harness() {
+ const csi = new Map<string, (params: number[]) => boolean>();
+ let reset = () => false;
+ const render = vi.fn();
+ const refresh = vi.fn();
+ const service = { _renderRows: render };
+ const term = {
+ rows: 24, refresh, _core: { _renderService: service },
+ parser: {
+ registerCsiHandler(id: { final: string }, callback: (params: number[]) => boolean) {
+ csi.set(id.final, callback);
+ return { dispose: () => csi.delete(id.final) };
+ },
+ registerEscHandler(_id: unknown, callback: () => boolean) {
+ reset = callback;
+ return { dispose: () => { reset = () => false; } };
+ },
+ },
+ } as unknown as Terminal;
+ const bridge = installSynchronizedOutput(term);
+ return { bridge, render, refresh, service, csi, reset: () => reset() };
+}
+
+afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); });
+
+describe("synchronized terminal output", () => {
+ it("keeps the last frame while several output chunks build the next one", () => {
+ const h = harness();
+ h.service._renderRows(0, 23);
+ h.render.mockClear();
+ expect(h.csi.get("h")!([2026, 25])).toBe(false);
+ h.service._renderRows(0, 12);
+ h.service._renderRows(13, 23);
+ expect(h.render).not.toHaveBeenCalled();
+ expect(h.csi.get("l")!([2026, 25])).toBe(false);
+ expect(h.refresh).toHaveBeenCalledExactlyOnceWith(0, 23);
+ h.service._renderRows(0, 23);
+ expect(h.render).toHaveBeenCalledExactlyOnceWith(0, 23);
+ h.bridge.dispose();
+ });
+
+ it("leaves ordinary output and unrelated private modes unchanged", () => {
+ const h = harness();
+ h.csi.get("h")!([25]);
+ h.service._renderRows(3, 7);
+ h.csi.get("l")!([2026]);
+ expect(h.render).toHaveBeenCalledExactlyOnceWith(3, 7);
+ expect(h.refresh).not.toHaveBeenCalled();
+ h.bridge.dispose();
+ });
+
+ it("bounds a missing end marker even when begin is repeated", () => {
+ vi.useFakeTimers();
+ const h = harness();
+ h.csi.get("h")!([2026]);
+ vi.advanceTimersByTime(SYNCHRONIZED_OUTPUT_TIMEOUT_MS - 1);
+ h.csi.get("h")!([2026]);
+ h.service._renderRows(0, 23);
+ expect(h.render).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ h.service._renderRows(0, 23);
+ expect(h.render).toHaveBeenCalledOnce();
+ expect(h.refresh).toHaveBeenCalledOnce();
+ h.bridge.dispose();
+ });
+
+ it("starts a fresh deadline for the next frame and releases on reset", () => {
+ vi.useFakeTimers();
+ const h = harness();
+ h.csi.get("h")!([2026]);
+ vi.advanceTimersByTime(900);
+ h.csi.get("l")!([2026]);
+ h.csi.get("h")!([2026]);
+ vi.advanceTimersByTime(101);
+ h.service._renderRows(0, 23);
+ expect(h.render).not.toHaveBeenCalled();
+ h.bridge.reset();
+ h.service._renderRows(0, 23);
+ expect(h.render).toHaveBeenCalledOnce();
+ h.csi.get("h")!([2026]);
+ expect(h.reset()).toBe(false);
+ h.service._renderRows(0, 23);
+ expect(h.render).toHaveBeenCalledTimes(2);
+ h.bridge.dispose();
+ });
+
+ it("restores rendering and removes timers and parser handlers on disposal", () => {
+ vi.useFakeTimers();
+ const h = harness();
+ h.csi.get("h")!([2026]);
+ h.bridge.dispose();
+ h.bridge.dispose();
+ expect(h.service._renderRows).toBe(h.render);
+ expect(h.csi.size).toBe(0);
+ expect(vi.getTimerCount()).toBe(0);
+ expect(h.refresh).not.toHaveBeenCalled();
+ });
+
+ it("degrades to ordinary rendering when xterm's private seam is unavailable", () => {
+ const bridge = installSynchronizedOutput({} as Terminal);
+ expect(() => { bridge.reset(); bridge.dispose(); }).not.toThrow();
+ });
+
+ it("honors Codex frame markers split across writes through the real xterm parser", async () => {
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
+ vi.stubGlobal("matchMedia", () => ({ matches: false, addListener() {}, removeListener() {} }));
+ const host = document.createElement("div");
+ document.body.append(host);
+ const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true });
+ term.open(host);
+ const service = (term as unknown as { _core: { _renderService: { _renderRows(start: number, end: number): void } } })._core._renderService;
+ const render = vi.spyOn(service, "_renderRows");
+ let bridge: ReturnType<typeof installSynchronizedOutput> | undefined;
+ const write = (text: string) => new Promise<void>((resolve) => term.write(text, resolve));
+ try {
+ // The installed xterm ignores the frame marker without the bridge:
+ // the same split repaint can present its incomplete first half.
+ await write("\x1b[?2026h\x1b[1;1H\x1b[Jbaseline partial");
+ service._renderRows(0, 23);
+ expect(render).toHaveBeenCalled();
+ await write("\x1b[?2026l");
+ render.mockClear();
+ bridge = installSynchronizedOutput(term);
+ await write("\x1b[?2026h\x1b[?25l\x1b[1;1H\x1b[Jpartial");
+ // Discard a baseline repaint that ran before the async parser consumed
+ // the new begin marker; every presentation from this point must wait.
+ render.mockClear();
+ service._renderRows(0, 23);
+ expect(render).not.toHaveBeenCalled();
+ await write(" frame\x1b[?20");
+ service._renderRows(0, 23);
+ expect(render).not.toHaveBeenCalled();
+ await write("26l\x1b[?25h");
+ service._renderRows(0, 23);
+ expect(render).toHaveBeenCalled();
+ expect(term.buffer.active.getLine(0)?.translateToString(true)).toBe("partial frame");
+ } finally {
+ bridge?.dispose();
+ term.dispose();
+ host.remove();
+ vi.unstubAllGlobals();
+ }
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/terminalSynchronizedOutput.ts b/jarvis/ui/web/frontend/src/components/agentic/terminalSynchronizedOutput.ts
new file mode 100644
index 0000000000..2624c887e6
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalSynchronizedOutput.ts
@@ -0,0 +1,85 @@
+import type { Terminal } from "@xterm/xterm";
+
+/** A missing end marker must not leave a terminal frozen. */
+export const SYNCHRONIZED_OUTPUT_TIMEOUT_MS = 1_000;
+
+interface RenderService {
+ _renderRows(start: number, end: number): void;
+}
+
+export interface SynchronizedOutput {
+ reset(): void;
+ dispose(): void;
+}
+
+/**
+ * Honor DEC synchronized output (CSI ? 2026 h/l) on xterm 5.5.
+ *
+ * Codex splits one repaint across several PTY/WebSocket chunks. Without this
+ * mode, xterm paints the intermediate erase and cursor moves before the rest
+ * of the frame arrives. Parsing must continue; only presentation waits.
+ *
+ * RenderService is shared by the DOM, canvas and WebGL renderers, including
+ * renderer replacements after context loss. Its debouncer calls _renderRows
+ * through the service, so this also holds refreshes queued before the marker.
+ * Keep the previous frame visible instead of hiding or clearing the canvas.
+ */
+export function installSynchronizedOutput(term: Terminal): SynchronizedOutput {
+ const service = (term as unknown as {
+ _core?: { _renderService?: RenderService };
+ })._core?._renderService;
+ if (typeof service?._renderRows !== "function") {
+ // Unknown xterm internals: ordinary rendering remains available.
+ return { reset() {}, dispose() {} };
+ }
+
+ const original = service._renderRows;
+ let holding = false;
+ let disposed = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const release = () => {
+ if (timer !== undefined) clearTimeout(timer);
+ timer = undefined;
+ if (!holding) return;
+ holding = false;
+ if (!disposed) term.refresh(0, Math.max(0, term.rows - 1));
+ };
+ const begin = () => {
+ if (disposed || holding) return;
+ holding = true;
+ // Repeated set-mode commands are not nested frames and must not extend
+ // the deadline indefinitely when a program forgets to send its end marker.
+ timer = setTimeout(release, SYNCHRONIZED_OUTPUT_TIMEOUT_MS);
+ };
+ const renderRows = function (this: RenderService, start: number, end: number) {
+ if (!holding) original.call(this, start, end);
+ };
+ service._renderRows = renderRows;
+
+ const handlers = [
+ term.parser.registerCsiHandler({ prefix: "?", final: "h" }, (params) => {
+ if (params.includes(2026)) begin();
+ // Let xterm apply other modes combined with this one, e.g. cursor mode.
+ return false;
+ }),
+ term.parser.registerCsiHandler({ prefix: "?", final: "l" }, (params) => {
+ if (params.includes(2026)) release();
+ return false;
+ }),
+ term.parser.registerEscHandler({ final: "c" }, () => {
+ release();
+ return false;
+ }),
+ ];
+
+ return {
+ reset: release,
+ dispose() {
+ if (disposed) return;
+ disposed = true;
+ release();
+ for (const handler of handlers) handler.dispose();
+ if (service._renderRows === renderRows) service._renderRows = original;
+ },
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
index 2cc0b623be..5995083b09 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { FolderPlus, Loader2, X } from "lucide-react";
import { FolderPicker } from "@/components/agentic/FolderPicker";
import { VoiceBubble, storedVoiceBubbleOpen, storeVoiceBubbleOpen } from "@/components/agentic/VoiceBubble";
-import { WorkspaceTerminalGrid } from "@/components/agentic/WorkspaceTerminalGrid";
+import { RetainedWorkspaceGrid } from "@/components/agentic/RetainedWorkspaceGrid";
import { WorkspaceAgentSetup } from "@/components/agentic/WorkspaceAgentSetup";
import { RunOnPicker, storeRunOn, storedRunOn } from "@/components/agentic/RunOnPicker";
import { WorkspaceOptionsDialog } from "@/components/agentic/WorkspaceOptionsDialog";
@@ -561,7 +561,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
<main className="min-h-0 flex-1">
<IdeSidePanelFrame markInUse={paneStyle === "minimal"}>
- {session ? <WorkspaceTerminalGrid key={session.id} session={session} onChanged={(next) => setState((current) => current?.session?.id === next.id ? { ...current, session: next } : current)}
+ {session ? <RetainedWorkspaceGrid session={session} onScreen={onScreen} workspaceIds={state.workspaces?.map((workspace) => workspace.id)} onChanged={(next) => setState((current) => current?.session?.id === next.id ? { ...current, session: next } : current)}
onAdd={openAgentPicker} onClose={closeAgent} onSelect={setSelected} selected={selected} maxPanes={maxPanes} fontSize={fontSize} appearance={appearance} disabled={busy}
onMutationStart={beginGridMutation} onMutationEnd={endGridMutation} paneStyle={paneStyle} />
: <div className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center">
diff --git a/tests/fakes/terminal_repaint_cases.json b/tests/fakes/terminal_repaint_cases.json
new file mode 100644
index 0000000000..4e278b2cd6
--- /dev/null
+++ b/tests/fakes/terminal_repaint_cases.json
@@ -0,0 +1,19 @@
+{
+ "full": [
+ "\u001b[2J",
+ "\u001b[1;1H\u001b[J",
+ "\u001b[H\u001b[J",
+ "\u001b[0;0H\u001b[0J",
+ "\u001b[1H\u001b[0m\u001b[J",
+ "\u001b[H\u001b[?25l\u001b[J"
+ ],
+ "partial": [
+ "\u001b[J",
+ "\u001b[2;1H\u001b[J",
+ "\u001b[1;2H\u001b[J",
+ "\u001b[Htext\u001b[J",
+ "\u001b[H\u001b[1B\u001b[J",
+ "\u001b[H\u001b[?1049l\u001b[J",
+ "\u001b[H\u001b[3J"
+ ]
+}
diff --git a/tests/unit/agentic_ide/test_session.py b/tests/unit/agentic_ide/test_session.py
index 65dcf42cf3..c1c1dd7d5a 100644
--- a/tests/unit/agentic_ide/test_session.py
+++ b/tests/unit/agentic_ide/test_session.py
@@ -360,10 +360,10 @@ async def test_a_geometry_change_rebases_an_intact_replay_and_repaints(
async def _rejoin_cut_fullscreen_pane(
- registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path, agent: str = "claude"
) -> tuple[object, str]:
"""A full-screen agent whose replay lost its start, re-joined at 80x24."""
- session = await _open(registry, tmp_path, [{"agent": "claude"}])
+ session = await _open(registry, tmp_path, [{"agent": agent}])
term = session.terminals[0]
await registry.attach(term.name, 80, 24, _noop_output, _noop_exit)
pty = term.pty_id
@@ -377,6 +377,32 @@ async def _rejoin_cut_fullscreen_pane(
return term, pty
+async def test_codex_home_then_erase_stops_repeated_height_nudges(
+ registry: Registry,
+ fake_pty: FakePtyManager,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A real Codex redraw must not cause five down/up size changes."""
+ monkeypatch.setattr(session_mod, "REPAINT_CONFIRM_S", 0.02)
+ monkeypatch.setattr(session_mod, "REPAINT_POLL_S", 0.005)
+ plain_resize = FakePtyManager.resize
+
+ def answer_first_nudge(self: FakePtyManager, tid: str, cols: int, rows: int) -> bool:
+ done = plain_resize(self, tid, cols, rows)
+ if len(self.resizes) == 1:
+ asyncio.get_running_loop().create_task(
+ self.emit(tid, "\x1b[?2026h\x1b[1;1H\x1b[Jnew Codex frame\x1b[?2026l")
+ )
+ return done
+
+ monkeypatch.setattr(FakePtyManager, "resize", answer_first_nudge)
+ _term, pty = await _rejoin_cut_fullscreen_pane(registry, fake_pty, tmp_path, agent="codex")
+ await asyncio.gather(*registry._repaint_checks)
+ sizes = [(cols, rows) for tid, cols, rows in fake_pty.resizes if tid == pty]
+ assert sizes == [(80, 23), (80, 24)]
+
+
async def test_an_ignored_repaint_nudge_is_sent_again(
registry: Registry,
fake_pty: FakePtyManager,
diff --git a/tests/unit/agentic_ide/test_transcript.py b/tests/unit/agentic_ide/test_transcript.py
index 13ac21d387..57da5ee58d 100644
--- a/tests/unit/agentic_ide/test_transcript.py
+++ b/tests/unit/agentic_ide/test_transcript.py
@@ -6,9 +6,46 @@ is Alex doing?" gets answered from control codes and repainted frames.
"""
from __future__ import annotations
+import json
+from pathlib import Path
+
+import pytest
+
from jarvis.agentic_ide.screen import ScreenBuffer
from jarvis.agentic_ide.transcript import ReplayBuffer, Transcript, is_noise, strip_ansi
+REPAINT_CASES = json.loads(
+ (Path(__file__).parents[2] / "fakes" / "terminal_repaint_cases.json").read_text(
+ encoding="utf-8"
+ )
+)
+
+
[email protected]("erase", REPAINT_CASES["full"])
+def test_equivalent_full_redraws_acknowledge_a_repaint_across_every_read_boundary(
+ erase: str,
+) -> None:
+ for split in range(1, len(erase)):
+ buffer = ReplayBuffer()
+ buffer.feed("\x1b[?1049hOLD FRAME")
+ buffer.feed(erase[:split])
+ buffer.feed(erase[split:] + "new frame")
+ assert buffer.clears == 1, (erase, split)
+ assert "OLD FRAME" not in buffer.text()
+ assert buffer.text().endswith(erase + "new frame")
+ buffer.feed("more output")
+ assert buffer.clears == 1, "the retained scan tail must not count an erase twice"
+
+
[email protected]("erase", REPAINT_CASES["partial"])
+def test_a_partial_erase_does_not_acknowledge_a_full_redraw(erase: str) -> None:
+ buffer = ReplayBuffer()
+ buffer.feed("\x1b[?1049hOLD FRAME")
+ for character in erase:
+ buffer.feed(character)
+ assert buffer.clears == 0
+ assert "OLD FRAME" in buffer.text()
+
def test_strip_ansi_removes_colour_and_cursor_sequences() -> None:
coloured = "\x1b[32mgreen\x1b[0m and \x1b[1;31mred\x1b[0m"