A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
keep agents view in fullscreen mode (#351)
kte51466e7208a
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex 07cc8339c1..e94cc40293 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -14,6 +14,7 @@- Fixed session-targeted heartbeat jobs staying scheduled after sessions are killed or saved sessions are deleted ([#332](https://github.com/PrimeIntellect-ai/prime-agent/pull/332)).- Fixed self-updates interrupting and automatically resuming daemon sessions instead of waiting for long-running work to finish.- Fixed provider errors being surfaced instead of retried within the retry budget ([ENG-4503](https://linear.app/primeintellect/issue/ENG-4503/restarting-old-session-returns-empty-model-response)).+- Fixed Agents View returning from fullscreen sessions without flashing primary scrollback ([ENG-4508](https://linear.app/primeintellect/issue/ENG-4508/fullscreen-mode-agents-view-scroll)).## [0.2.6] - 2026-07-06diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.tsindex 89981d529f..2f600234ef 100644--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts@@ -5,6 +5,7 @@ import type { AutocompleteItem, OverlayHandle, SlashCommand } from "@earendil-woimport {CombinedAutocompleteProvider,type Component,+ clippedFullscreenDockHeight,type Focusable,fuzzyFilter,ProcessTerminal,@@ -334,6 +335,7 @@ export async function runAgentsViewMode(options: AgentsViewModeOptions): PromisestartupNotice: opened.cwdFallbackNotice,verbose: options.verbose,returnToAgentsView: true,+ forceFullscreen: true,// The agents view renders the global notices itself, so suppress them in-session.agentsViewOwnsStartupNotices: true,// Matches the node id scheme used by snapshot child seeding@@ -352,7 +354,7 @@ export async function runAgentsViewMode(options: AgentsViewModeOptions): Promise// Tear down the session TUI exactly as a normal back-navigation would// (drain input, stop renderer + theme watcher) so it doesn't fight the// agents-view UI for the terminal, then drop the daemon connection.- await interactiveMode.teardownSessionUi();+ await interactiveMode.teardownSessionUi({ preserveAltScreen: true });await opened.connection.dispose().catch(() => undefined);}} catch (error) {@@ -369,6 +371,7 @@ class AgentsViewMode implements Component, Focusable {private readonly ui: TUI;private readonly editor: CustomEditor;private readonly splash: BrandSplashHeader;+ private readonly fullscreenDock: Component;private readonly keybindings: KeybindingsManager;private client: DaemonClient | undefined;private resolveRun: ((result: AgentsViewRunResult) => void) | undefined;@@ -445,6 +448,12 @@ class AgentsViewMode implements Component, Focusable {this.setReplyTarget(undefined);return true;};+ this.fullscreenDock = {+ render: (width) => this.renderDock(width),+ invalidate: () => {+ this.editor.invalidate();+ },+ };this.splash = new BrandSplashHeader(VERSION,() => this.getSplashModelId(),@@ -463,6 +472,12 @@ class AgentsViewMode implements Component, Focusable {this.ui.addChild(this);this.ui.setFocus(this);this.ui.start();+ this.ui.enterFullscreen({+ scroll: [this],+ dock: this.fullscreenDock,+ mouse: false,+ viewportControls: false,+ });const startupStatusMessage = this.persistentState.statusMessage;this.persistentState.statusMessage = undefined;if (startupStatusMessage) {@@ -549,14 +564,8 @@ class AgentsViewMode implements Component, Focusable {render(width: number): string[] {const safeWidth = Math.max(1, width);- const height = Math.max(1, this.ui.terminal.rows);- const promptLines = [...this.renderPrompt(safeWidth), this.renderHints(safeWidth)];- const contentHeight = Math.max(0, height - promptLines.length);- const lines = this.renderContent(safeWidth, contentHeight).slice(0, contentHeight);- while (lines.length < contentHeight) {- lines.push("");- }- lines.push(...promptLines.slice(0, Math.max(0, height - lines.length)));+ const height = this.contentHeight(safeWidth);+ const lines = this.renderContent(safeWidth, height).slice(0, height);while (lines.length < height) {lines.push("");}@@ -1794,10 +1803,10 @@ class AgentsViewMode implements Component, Focusable {this.clearCtrlCExitHint({ render: false });this.clearDeleteConfirmation({ render: false });this.setStatusMessage(undefined, { render: false });- this.ui.stop();- if (result.type === "open") {- this.ui.terminal.clearScreen();- }+ this.ui.stop({+ preserveAltScreen: result.type === "open",+ flushFullscreen: false,+ });stopThemeWatcher();this.client?.close();this.client = undefined;@@ -1966,6 +1975,13 @@ class AgentsViewMode implements Component, Focusable {return this.editor.render(width);}+ private renderDock(width: number): string[] {+ const safeWidth = Math.max(1, width);+ return [...this.renderPrompt(safeWidth), this.renderHints(safeWidth)].map((line) =>+ this.finalizeRenderedLine(line, safeWidth),+ );+ }+private renderHints(width: number): string {if (this.isCtrlCExitHintVisible()) {const clearKey = keyText("app.clear");@@ -2004,6 +2020,12 @@ class AgentsViewMode implements Component, Focusable {return Math.max(4, this.ui.terminal.rows - 9);}+ private contentHeight(width: number): number {+ const rows = this.ui.terminal.rows;+ const dockHeight = clippedFullscreenDockHeight(this.renderDock(width).length, rows);+ return Math.max(0, rows - dockHeight);+ }+private getSplashModelId(): string | undefined {return this.rows[this.selectedIndex]?.summary.model?.id ?? this.options.startupModelId;}diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 63adab678b..6c41160a64 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -554,6 +554,8 @@ export interface InteractiveModeOptions {onShutdown?: () => void | Promise<void>;/** Allow returning from a full session to the agents view without stopping the daemon-owned agent. */returnToAgentsView?: boolean;+ /** Enter fullscreen regardless of the persisted fullscreen preference. */+ forceFullscreen?: boolean;/*** The agents view already surfaced global startup notices (app/extension updates, tmux setup),* so this session must not repeat them in its chat stream. Distinct from `returnToAgentsView`,@@ -1081,7 +1083,9 @@ export class InteractiveMode {// Start the UI before initializing extensions so session_start handlers can use interactive dialogsthis.ui.start();- this.fullscreenEnabled = this.settingsManager.getFullscreen() && process.stdout.isTTY === true;+ this.fullscreenEnabled =+ (this.options.forceFullscreen === true || this.settingsManager.getFullscreen()) &&+ process.stdout.isTTY === true;if (this.fullscreenEnabled) {this.applyFullscreen(true);}@@ -5606,9 +5610,9 @@ export class InteractiveMode {* leak into the parent UI, then stops the renderer and theme watcher. Safe to* call from a crash path too; idempotent via stop().*/- async teardownSessionUi(): Promise<void> {+ async teardownSessionUi(options: { preserveAltScreen?: boolean } = {}): Promise<void> {await this.ui.terminal.drainInput(1000).catch(() => undefined);- this.stop();+ this.stop({ preserveAltScreen: options.preserveAltScreen });stopThemeWatcher();}@@ -5618,12 +5622,21 @@ export class InteractiveMode {this.isShuttingDown = true;this.unregisterSignalHandlers();- await this.teardownSessionUi();+ await this.teardownSessionUi({ preserveAltScreen: true });+ let handoffComplete = false;try {- await this.agentConnection.dispose();+ try {+ await this.agentConnection.dispose();+ } finally {+ await this.options.onShutdown?.();+ this.onInputCallback?.(undefined);+ handoffComplete = true;+ }} finally {- await this.options.onShutdown?.();- this.onInputCallback?.(undefined);+ if (!handoffComplete) {+ this.ui.terminal.leaveAltScreen();+ this.ui.terminal.showCursor();+ }}}@@ -8256,7 +8269,7 @@ ${interrupt ? `| \`${interrupt}\` | Interrupt current operation |\n` : ""}| \`${}}- stop(): void {+ stop(options: { preserveAltScreen?: boolean } = {}): void {this.unregisterSignalHandlers();this.clearCtrlCExitHint({ render: false });if (this.settingsManager.getShowTerminalProgress()) {@@ -8272,7 +8285,10 @@ ${interrupt ? `| \`${interrupt}\` | Interrupt current operation |\n` : ""}| \`${this.unsubscribe();}if (this.isInitialized) {- this.ui.stop();+ this.ui.stop({+ preserveAltScreen: options.preserveAltScreen,+ flushFullscreen: options.preserveAltScreen ? false : undefined,+ });this.isInitialized = false;}}diff --git a/packages/tui/CHANGELOG.md b/packages/tui/CHANGELOG.mdindex 1418ed9b3f..9a2b97f7a6 100644--- a/packages/tui/CHANGELOG.md+++ b/packages/tui/CHANGELOG.md@@ -6,6 +6,7 @@- Fixed full TUI redraws to preserve terminal scrollback on resize and shrink redraws ([#331](https://github.com/PrimeIntellect-ai/prime-agent/pull/331) by [@sethkarten](https://github.com/sethkarten)).- Fixed fullscreen overlays that request native mouse behavior suspending mouse tracking while visible.+- Added fullscreen handoff support so callers can switch alternate-screen views without replaying content into primary scrollback.## [0.2.6] - 2026-07-06diff --git a/packages/tui/src/fullscreen.ts b/packages/tui/src/fullscreen.tsindex 352866baa8..3b370dfa43 100644--- a/packages/tui/src/fullscreen.ts+++ b/packages/tui/src/fullscreen.ts@@ -8,7 +8,12 @@import { isImageLine } from "./terminal-image.js";import { sliceByColumn, stripAnsi, visibleWidth } from "./utils.js";-const MIN_TRANSCRIPT_ROWS = 3;+export const FULLSCREEN_MIN_TRANSCRIPT_ROWS = 3;++export function clippedFullscreenDockHeight(dockLength: number, height: number): number {+ const maxDock = Math.max(0, height - FULLSCREEN_MIN_TRANSCRIPT_ROWS);+ return Math.min(dockLength, maxDock);+}// Kitty images span multiple physical rows and cannot be clipped to a window.const IMAGE_PLACEHOLDER = "\x1b[2m[image — view in inline mode]\x1b[0m";@@ -71,10 +76,10 @@ export class FullscreenViewport {*/composeFrame(transcript: string[], dock: string[], height: number): string[] {let dockLines = dock;- const maxDock = Math.max(0, height - MIN_TRANSCRIPT_ROWS);- if (dockLines.length > maxDock) {+ const dockHeight = clippedFullscreenDockHeight(dockLines.length, height);+ if (dockLines.length > dockHeight) {// bottom of the dock (editor + footer) wins over widgets above it- dockLines = dockLines.slice(dockLines.length - maxDock);+ dockLines = dockLines.slice(dockLines.length - dockHeight);}const windowHeight = height - dockLines.length;const maxScroll = Math.max(0, transcript.length - windowHeight);diff --git a/packages/tui/src/index.ts b/packages/tui/src/index.tsindex 641df72e00..c9b34c5e12 100644--- a/packages/tui/src/index.ts+++ b/packages/tui/src/index.ts@@ -30,7 +30,12 @@ export { TruncatedText } from "./components/truncated-text.js";// Editor component interface (for custom editors)export type { EditorComponent, EditorPasteSnapshot } from "./editor-component.js";// Fullscreen (alternate-screen) viewport-export { FullscreenViewport, type ScrollInfo } from "./fullscreen.js";+export {+ clippedFullscreenDockHeight,+ FULLSCREEN_MIN_TRANSCRIPT_ROWS,+ FullscreenViewport,+ type ScrollInfo,+} from "./fullscreen.js";// Fuzzy matchingexport { type FuzzyMatch, fuzzyFilter, fuzzyFilterScored, fuzzyMatch, type ScoredItem } from "./fuzzy.js";// Keybindings@@ -76,7 +81,7 @@ export { VersionedRenderCache } from "./render-cache.js";// Input buffering for batch splittingexport { StdinBuffer, type StdinBufferEventMap, type StdinBufferOptions } from "./stdin-buffer.js";// Terminal interface and implementations-export { ProcessTerminal, type Terminal } from "./terminal.js";+export { ProcessTerminal, type Terminal, type TerminalStopOptions } from "./terminal.js";export {bestAnsiColor,blendColor,@@ -132,6 +137,7 @@ export {Container,CURSOR_MARKER,type Focusable,+ type FullscreenOptions,isFocusable,type OverlayAnchor,type OverlayHandle,@@ -139,6 +145,7 @@ export {type OverlayOptions,type SizeValue,TUI,+ type TuiStopOptions,} from "./tui.js";// Utilitiesexport { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "./utils.js";diff --git a/packages/tui/src/terminal.ts b/packages/tui/src/terminal.tsindex e6f16b436d..71702e1785 100644--- a/packages/tui/src/terminal.ts+++ b/packages/tui/src/terminal.ts@@ -17,6 +17,17 @@ const TERMINAL_PROGRESS_KEEPALIVE_MS = 1000;const TERMINAL_PROGRESS_ACTIVE_SEQUENCE = "\x1b]9;4;3\x07";const TERMINAL_PROGRESS_CLEAR_SEQUENCE = "\x1b]9;4;0;\x07";+// A preserved alternate screen is adopted by the next ProcessTerminal during in-process handoff.+let pendingAltScreenHandoff: symbol | undefined;++function consumeAltScreenHandoff(): boolean {+ if (!pendingAltScreenHandoff) {+ return false;+ }+ pendingAltScreenHandoff = undefined;+ return true;+}+/*** Minimal terminal interface for TUI*/@@ -25,7 +36,7 @@ export interface Terminal {start(onInput: (data: string) => void, onResize: () => void): void;// Stop the terminal and restore state- stop(): void;+ stop(options?: TerminalStopOptions): void;/*** Drain stdin before exiting to prevent Kitty key release events from@@ -76,6 +87,10 @@ export interface Terminal {setProgress(active: boolean): void;}+export interface TerminalStopOptions {+ preserveAltScreen?: boolean;+}+/*** Real terminal using process.stdin/stdout*/@@ -85,7 +100,8 @@ export class ProcessTerminal implements Terminal {private resizeHandler?: () => void;private _kittyProtocolActive = false;private _modifyOtherKeysActive = false;- private _altScreenActive = false;+ private readonly altScreenHandoffToken = Symbol("altScreenHandoff");+ private _altScreenActive = consumeAltScreenHandoff();private _mouseTrackingActive = false;private stdinBuffer?: StdinBuffer;private stdinDataHandler?: (data: string) => void;@@ -341,21 +357,26 @@ export class ProcessTerminal implements Terminal {}}- stop(): void {+ stop(options: TerminalStopOptions = {}): void {this.finishDefaultColorProbe();if (this.clearProgressInterval()) {process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);}- // never strand the user on the alt screen or with mouse tracking onif (this._mouseTrackingActive) {process.stdout.write("\x1b[?1006l\x1b[?1002l");this._mouseTrackingActive = false;}if (this._altScreenActive) {- process.stdout.write("\x1b[?1049l");- this._altScreenActive = false;+ if (options.preserveAltScreen) {+ pendingAltScreenHandoff = this.altScreenHandoffToken;+ this._altScreenActive = false;+ } else {+ this.releaseAltScreen();+ }+ } else if (!options.preserveAltScreen) {+ this.releaseAltScreen();}// Disable bracketed paste mode@@ -452,13 +473,26 @@ export class ProcessTerminal implements Terminal {enterAltScreen(): void {if (this._altScreenActive) return;+ if (this.ownsPendingAltScreenHandoff()) {+ pendingAltScreenHandoff = undefined;+ this._altScreenActive = true;+ return;+ }this._altScreenActive = true;this.write("\x1b[?1049h");}leaveAltScreen(): void {- if (!this._altScreenActive) return;+ this.releaseAltScreen();+ }++ private releaseAltScreen(): void {+ const ownsPendingHandoff = this.ownsPendingAltScreenHandoff();+ if (!this._altScreenActive && !ownsPendingHandoff) return;this._altScreenActive = false;+ if (ownsPendingHandoff) {+ pendingAltScreenHandoff = undefined;+ }this.write("\x1b[?1049l");}@@ -466,6 +500,10 @@ export class ProcessTerminal implements Terminal {return this._altScreenActive;}+ private ownsPendingAltScreenHandoff(): boolean {+ return pendingAltScreenHandoff === this.altScreenHandoffToken;+ }+setMouseTracking(enabled: boolean): void {if (enabled === this._mouseTrackingActive) return;this._mouseTrackingActive = enabled;diff --git a/packages/tui/src/tui.ts b/packages/tui/src/tui.tsindex 89d240fdc7..99e4863b59 100644--- a/packages/tui/src/tui.ts+++ b/packages/tui/src/tui.ts@@ -72,6 +72,23 @@ export interface Component {invalidate(): void;}+export interface TuiStopOptions {+ preserveAltScreen?: boolean;+ flushFullscreen?: boolean;+}++export interface FullscreenOptions {+ scroll: Component[];+ dock: Component;+ mouse?: boolean;+ viewportControls?: boolean;+}++interface ExitFullscreenOptions {+ flush?: boolean;+ leaveAltScreen?: boolean;+}+type InputListenerResult = { consume?: boolean; data?: string } | undefined;type InputListener = (data: string) => InputListenerResult;@@ -291,6 +308,7 @@ export class TUI extends Container {scroll: Component[];dock: Component;mouse: boolean;+ viewportControls: boolean;inlineState: {previousLines: string[];previousKittyImageIds: Set<number>;@@ -531,16 +549,17 @@ export class TUI extends Container {this.terminal.write("\x1b[16t");}- stop(): void {- // before the exit bookkeeping below, which assumes the primary screen- this.exitFullscreen();+ stop(options: TuiStopOptions = {}): void {+ const preserveAltScreen = options.preserveAltScreen === true && this.terminal.altScreenActive;+ const flushFullscreen = options.flushFullscreen ?? !preserveAltScreen;+ this.exitFullscreen({ flush: flushFullscreen, leaveAltScreen: !preserveAltScreen });this.stopped = true;if (this.renderTimer) {clearTimeout(this.renderTimer);this.renderTimer = undefined;}// Move cursor to the end of the content to prevent overwriting/artifacts on exit- if (this.previousLines.length > 0) {+ if (!preserveAltScreen && this.previousLines.length > 0) {const targetRow = this.previousLines.length; // Line after the last contentconst lineDiff = targetRow - this.hardwareCursorRow;if (lineDiff > 0) {@@ -551,8 +570,12 @@ export class TUI extends Container {this.terminal.write("\r\n");}- this.terminal.showCursor();- this.terminal.stop();+ if (preserveAltScreen) {+ this.terminal.hideCursor();+ } else {+ this.terminal.showCursor();+ }+ this.terminal.stop({ preserveAltScreen });}requestRender(force = false): void {@@ -604,13 +627,14 @@ export class TUI extends Container {* Wheel tracking is enabled blind — probing is not viable (tmux never* answers DECRQM) and unsupporting terminals ignore the mode-sets.*/- enterFullscreen(options: { scroll: Component[]; dock: Component; mouse?: boolean }): void {+ enterFullscreen(options: FullscreenOptions): void {if (this.fullscreen) return;this.fullscreen = {viewport: new FullscreenViewport(),scroll: options.scroll,dock: options.dock,mouse: options.mouse !== false,+ viewportControls: options.viewportControls !== false,inlineState: {previousLines: this.previousLines,previousKittyImageIds: this.previousKittyImageIds,@@ -632,12 +656,14 @@ export class TUI extends Container {* Leave fullscreen. The inline differ resumes against the entry snapshot,* so content produced while fullscreen flows into native scrollback.*/- exitFullscreen(): void {+ exitFullscreen(options: ExitFullscreenOptions = {}): void {if (!this.fullscreen) return;const { inlineState } = this.fullscreen;this.fullscreen = null;this.syncFullscreenMouseTracking();- this.terminal.leaveAltScreen();+ if (options.leaveAltScreen !== false) {+ this.terminal.leaveAltScreen();+ }this.previousLines = inlineState.previousLines;this.previousKittyImageIds = inlineState.previousKittyImageIds;this.previousWidth = inlineState.previousWidth;@@ -647,7 +673,7 @@ export class TUI extends Container {this.maxLinesRendered = inlineState.maxLinesRendered;this.previousViewportTop = inlineState.previousViewportTop;// synchronous so the flush also happens on shutdown, where a scheduled render never fires- if (!this.stopped) {+ if (options.flush !== false && !this.stopped) {this.doRender();}}@@ -821,7 +847,7 @@ export class TUI extends Container {return true;}- if (overlayFocused) return false;+ if (overlayFocused || !fullscreen.viewportControls) return false;const keybindings = getKeybindings();if (keybindings.matches(data, "tui.viewport.pageUp")) {@@ -1268,7 +1294,7 @@ export class TUI extends Container {let frame = fullscreen.viewport.composeFrame(transcript, dock, height);const scrollInfo = fullscreen.viewport.scrollInfo();- if (!scrollInfo.following) {+ if (fullscreen.viewportControls && !scrollInfo.following) {// Follow hint composited over the bottom of the transcript window,// just above the dock. Overlays still paint on top of it.const followKey = getKeybindings().getKeys("tui.viewport.follow")[0] ?? "alt+down";diff --git a/packages/tui/test/fullscreen.test.ts b/packages/tui/test/fullscreen.test.tsindex 7f1b7728f3..d51e6a635b 100644--- a/packages/tui/test/fullscreen.test.ts+++ b/packages/tui/test/fullscreen.test.ts@@ -1,5 +1,6 @@import assert from "node:assert";import { describe, it } from "node:test";+import type { TerminalStopOptions } from "../src/terminal.js";import { type Component, TUI } from "../src/tui.js";import { VirtualTerminal } from "./virtual-terminal.js";@@ -20,12 +21,18 @@ class InputComponent extends TestComponent {class LoggingVirtualTerminal extends VirtualTerminal {private writes: string[] = [];+ lastStopOptions: TerminalStopOptions | undefined;override write(data: string): void {this.writes.push(data);super.write(data);}+ override stop(options?: TerminalStopOptions): void {+ this.lastStopOptions = options;+ super.stop(options);+ }+getWrites(): string {return this.writes.join("");}@@ -625,4 +632,64 @@ describe("TUI fullscreen mode", () => {tui.stop();});++ it("can stop without leaving alt screen or flushing fullscreen content", async () => {+ const { terminal, tui, chat, dock } = setup(lines(30));+ tui.enterFullscreen({ scroll: [chat], dock });+ await terminal.waitForRender();++ terminal.clearWrites();+ tui.stop({ preserveAltScreen: true, flushFullscreen: false });+ await terminal.flush();++ assert.strictEqual(tui.isFullscreen(), false);+ assert.strictEqual(terminal.getActiveBufferType(), "alternate");+ assert.strictEqual(terminal.mouseTrackingActive, false);+ assert.ok(!terminal.getWrites().includes("\x1b[?1049l"));+ assert.ok(!terminal.getWrites().includes("Line 29"));++ const next = new TUI(terminal);+ const nextContent = new TestComponent();+ nextContent.lines = ["Agents View"];+ const nextDock = new TestComponent();+ nextDock.lines = ["> prompt"];+ next.start();+ next.enterFullscreen({ scroll: [nextContent], dock: nextDock, mouse: false });+ await terminal.waitForRender();++ const viewport = terminal.getViewport();+ assert.strictEqual(viewport[0], "Agents View");+ assert.strictEqual(viewport.at(-1), "> prompt");++ next.stop({ flushFullscreen: false });+ await terminal.flush();+ assert.strictEqual(terminal.getActiveBufferType(), "normal");+ });++ it("ignores preserve requests when no alternate screen is active", async () => {+ const { terminal, tui } = setup(lines(3));+ await terminal.waitForRender();++ terminal.clearWrites();+ tui.stop({ preserveAltScreen: true });+ await terminal.flush();++ assert.strictEqual(terminal.getActiveBufferType(), "normal");+ assert.strictEqual(terminal.lastStopOptions?.preserveAltScreen, false);+ });++ it("can pass viewport keys to the focused component", async () => {+ const { terminal, tui, chat, dock } = setup(lines(20));+ const input = new InputComponent();+ tui.setFocus(input);+ tui.enterFullscreen({ scroll: [chat], dock, viewportControls: false });+ await terminal.waitForRender();++ terminal.sendInput(PAGE_UP);+ await terminal.waitForRender();++ assert.deepStrictEqual(input.inputs, [PAGE_UP]);++ tui.stop();+ });});diff --git a/packages/tui/test/terminal.test.ts b/packages/tui/test/terminal.test.tsindex 7099b3dfa1..7af3dbb7e6 100644--- a/packages/tui/test/terminal.test.ts+++ b/packages/tui/test/terminal.test.ts@@ -43,3 +43,137 @@ describe("ProcessTerminal dimensions", () => {}});});++describe("ProcessTerminal alternate screen handoff", () => {+ it("does not inherit an active alternate screen before it is preserved", () => {+ const originalWrite = process.stdout.write;+ const writes: string[] = [];+ const patchedWrite = ((...args: Parameters<typeof process.stdout.write>): boolean => {+ const chunk = args[0];+ writes.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8"));+ const callback = args.find((arg): arg is (error?: Error | null) => void => typeof arg === "function");+ callback?.();+ return true;+ }) as typeof process.stdout.write;++ process.stdout.write = patchedWrite;+ try {+ const first = new ProcessTerminal();+ first.enterAltScreen();++ const second = new ProcessTerminal();+ assert.equal(second.altScreenActive, false);+ second.stop();++ assert.equal(writes.filter((write) => write === "\x1b[?1049l").length, 0);+ first.leaveAltScreen();+ assert.equal(writes.filter((write) => write === "\x1b[?1049l").length, 1);+ } finally {+ const cleanup = new ProcessTerminal();+ if (cleanup.altScreenActive) {+ cleanup.stop();+ }+ process.stdout.write = originalWrite;+ }+ });++ it("inherits a preserved alternate screen into the next terminal instance", () => {+ const originalWrite = process.stdout.write;+ const writes: string[] = [];+ const patchedWrite = ((...args: Parameters<typeof process.stdout.write>): boolean => {+ const chunk = args[0];+ writes.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8"));+ const callback = args.find((arg): arg is (error?: Error | null) => void => typeof arg === "function");+ callback?.();+ return true;+ }) as typeof process.stdout.write;++ process.stdout.write = patchedWrite;+ try {+ const first = new ProcessTerminal();+ first.enterAltScreen();+ first.stop({ preserveAltScreen: true });++ const second = new ProcessTerminal();+ assert.equal(second.altScreenActive, true);+ second.stop();+ assert.equal(second.altScreenActive, false);++ const third = new ProcessTerminal();+ assert.equal(third.altScreenActive, false);+ assert.ok(writes.includes("\x1b[?1049h"));+ assert.ok(writes.includes("\x1b[?1049l"));+ } finally {+ const cleanup = new ProcessTerminal();+ if (cleanup.altScreenActive) {+ cleanup.stop();+ }+ process.stdout.write = originalWrite;+ }+ });++ it("lets the preserving terminal cancel a handoff before it is consumed", () => {+ const originalWrite = process.stdout.write;+ const writes: string[] = [];+ const patchedWrite = ((...args: Parameters<typeof process.stdout.write>): boolean => {+ const chunk = args[0];+ writes.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8"));+ const callback = args.find((arg): arg is (error?: Error | null) => void => typeof arg === "function");+ callback?.();+ return true;+ }) as typeof process.stdout.write;++ process.stdout.write = patchedWrite;+ try {+ const first = new ProcessTerminal();+ first.enterAltScreen();+ first.stop({ preserveAltScreen: true });+ assert.equal(first.altScreenActive, false);++ first.leaveAltScreen();+ assert.equal(writes.filter((write) => write === "\x1b[?1049l").length, 1);++ const second = new ProcessTerminal();+ assert.equal(second.altScreenActive, false);+ } finally {+ const cleanup = new ProcessTerminal();+ if (cleanup.altScreenActive) {+ cleanup.stop();+ }+ process.stdout.write = originalWrite;+ }+ });++ it("only hands a preserved alternate screen to one terminal instance", () => {+ const originalWrite = process.stdout.write;+ const writes: string[] = [];+ const patchedWrite = ((...args: Parameters<typeof process.stdout.write>): boolean => {+ const chunk = args[0];+ writes.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8"));+ const callback = args.find((arg): arg is (error?: Error | null) => void => typeof arg === "function");+ callback?.();+ return true;+ }) as typeof process.stdout.write;++ process.stdout.write = patchedWrite;+ try {+ const first = new ProcessTerminal();+ first.enterAltScreen();+ first.stop({ preserveAltScreen: true });++ const second = new ProcessTerminal();+ const third = new ProcessTerminal();+ assert.equal(second.altScreenActive, true);+ assert.equal(third.altScreenActive, false);++ second.stop();+ assert.equal(writes.filter((write) => write === "\x1b[?1049l").length, 1);+ } finally {+ const cleanup = new ProcessTerminal();+ if (cleanup.altScreenActive) {+ cleanup.stop();+ }+ process.stdout.write = originalWrite;+ }+ });+});diff --git a/packages/tui/test/virtual-terminal.ts b/packages/tui/test/virtual-terminal.tsindex 400f6fe9c3..410b7a8e2f 100644--- a/packages/tui/test/virtual-terminal.ts+++ b/packages/tui/test/virtual-terminal.ts@@ -1,6 +1,6 @@import type { Terminal as XtermTerminalType } from "@xterm/headless";import xterm from "@xterm/headless";-import type { Terminal } from "../src/terminal.js";+import type { Terminal, TerminalStopOptions } from "../src/terminal.js";// Extract Terminal class from the moduleconst XtermTerminal = xterm.Terminal;@@ -42,7 +42,7 @@ export class VirtualTerminal implements Terminal {// No-op for virtual terminal - no stdin to drain}- stop(): void {+ stop(_options?: TerminalStopOptions): void {// Disable bracketed paste modethis.xterm.write("\x1b[?2004l");this.inputHandler = undefined;