Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): restore terminal scrollback reach after a resize (PRD-8287) (#3893)
Andrew Mikofalvy4524d0ce9f74
diff --git a/.changeset/terminal-scroll-reach-after-resize.md b/.changeset/terminal-scroll-reach-after-resize.mdnew file mode 100644index 000000000..887dfa42f--- /dev/null+++ b/.changeset/terminal-scroll-reach-after-resize.md@@ -0,0 +1,9 @@+---+"@inkeep/open-knowledge": patch+---++Scrolling back through terminal history no longer dead-ends after the panel changes size. Moving the terminal between its bottom dock and the right column while scrolled up left the view unable to go any further up, by wheel or by keyboard, and it stayed that way, because the resize left the scrollbar and the rows pointing at different lines. The lines above were never lost, but the only way back to them was scrolling all the way down and starting again. The panel now puts the two back in agreement whenever the grid resizes under a scrolled-back view.++Resizing the terminal still moves your place in the history: it keeps the most recent visible line on screen, so a tall panel becoming a short one leaves you further down the buffer than you were. That part is unchanged.++One thing is new, and it is the trade this makes: if the terminal resizes while a scroll of yours is still gliding to a stop, that glide now stops where it is instead of finishing. Reaching the history again is worth more than the last few lines of momentum, but it is a change you can notice.diff --git a/packages/app/src/components/TerminalPanel.dom.test.tsx b/packages/app/src/components/TerminalPanel.dom.test.tsxindex 69978ffe8..9106f95f6 100644--- a/packages/app/src/components/TerminalPanel.dom.test.tsx+++ b/packages/app/src/components/TerminalPanel.dom.test.tsx@@ -18,6 +18,11 @@ import type {OkPtyData,OkPtyExit,} from '@/lib/desktop-bridge-types';+import {+ applyModelledScroll,+ createScrollModelState,+ instrumentSmoothScrollOption,+} from './terminal-scroll-model.test-helper';// --- xterm mocks (3rd-party system boundary) ---class MockFitAddon {@@ -77,9 +82,45 @@ class MockTerminal {// Optional wrapped-line fixture: each entry is one buffer row; rows after the// first carry `isWrapped` so the provider stitches them into one logical line.lineRows: string[] | null = null;+ // Where the viewport sits in the scrollback. `viewportY === baseY` is the+ // bottom; anything lower is scrolled back, which is what the panel's+ // post-resize scroll-reach restore keys off.+ //+ // The public scrolls model the pinned `CoreBrowserTerminal`: under+ // `smoothScrollDuration` they hand a target to an animated viewport and+ // return with `viewportY` unmoved, and `scrollToLine` does nothing at all+ // when `line - viewportY` is zero. A mock that simply recorded the calls+ // would accept a restore the real terminal swallows.+ // The scroll rules live in `terminal-scroll-model.test-helper`, shared with+ // the unit fake beside `restoreScrollReach` so the two cannot drift.+ scrollState = createScrollModelState(0);+ baseY = 0;+ get viewportY() {+ return this.scrollState.viewportY;+ }+ set viewportY(line: number) {+ this.scrollState.viewportY = line;+ }+ get scrollbarLine() {+ return this.scrollState.scrollbarLine;+ }+ set scrollbarLine(line: number) {+ this.scrollState.scrollbarLine = line;+ }+ get pendingScrollTarget() {+ return this.scrollState.pendingTarget;+ }+ scrollToBottom = vi.fn(() => {+ applyModelledScroll(this.scrollState, this.baseY, this.options.smoothScrollDuration as number);+ });+ scrollToLine = vi.fn((line: number) => {+ applyModelledScroll(this.scrollState, line, this.options.smoothScrollDuration as number);+ });get buffer() {return {active: {+ viewportY: this.viewportY,+ baseY: this.baseY,getLine: (index: number) => {if (this.lineRows) {const t = this.lineRows[index];@@ -150,7 +191,12 @@ class MockTerminal {attachCustomWheelEventHandler = vi.fn((h: (e: WheelEvent) => boolean) => {this.wheelHandler = h;});+ /** Writes to `smoothScrollDuration`; the scrolled-back guard's only trace. */+ smoothScrollWrites: () => number;constructor(options: Record<string, unknown>) {+ this.smoothScrollWrites = instrumentSmoothScrollOption(+ options as { smoothScrollDuration?: number },+ );this.options = options;lastTerm = this;}@@ -695,6 +741,70 @@ describe('TerminalPanel', () => {expect(lastTerm?.renderFlush).toHaveBeenCalledTimes(1);});+ test('a grid-changing fit keeps a scrolled-back viewport on the line it was reading', async () => {+ const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });+ render(<TerminalPanel bridge={bridge} />);+ await waitFor(() => expect(roCallback).toBeTruthy());++ // At the bottom there is no reach to lose, so the common resize must leave+ // even a disagreeing scrollbar alone.+ if (lastTerm) {+ lastTerm.viewportY = 120;+ lastTerm.baseY = 120;+ lastTerm.scrollbarLine = 7;+ }+ lastFit?.fit.mockImplementation(() => {+ if (lastTerm) lastTerm.cols += 1;+ });+ act(() => roCallback?.());+ expect(lastTerm?.viewportY).toBe(120);+ expect(lastTerm?.scrollbarLine).toBe(7);+ expect(lastTerm?.pendingScrollTarget).toBeNull();+ // The ordinary resize decides it has nothing to do without touching the+ // terminal's options; at the bottom both halves of the bounce would be+ // no-ops anyway, so this is the guard's only observable trace.+ expect(lastTerm?.smoothScrollWrites()).toBe(0);++ // Scrolled back, the same fit re-asserts the position outright: the reader+ // is left where they were, the scrollbar agrees again, and there is no+ // animation still to run.+ if (lastTerm) {+ lastTerm.viewportY = 34;+ lastTerm.scrollbarLine = 0;+ // Scoped to this act, so the ordering assertion below compares the two+ // calls from the SAME resize rather than an earlier flush.+ lastTerm.renderFlush.mockClear();+ lastTerm.scrollToBottom.mockClear();+ }+ act(() => roCallback?.());+ // Pins the CALL ORDER: the repaint must precede the restore, because+ // flushing the render debouncer runs the refresh callbacks the viewport+ // queued its scroll-area sync onto. What this cannot pin is the+ // consequence — the mock always supplies the debouncer internal, so it+ // never enters the degraded path where the flush defers to the next frame+ // and the restore lands ahead of the sync regardless of call order.+ expect(lastTerm?.renderFlush.mock.invocationCallOrder[0]).toBeLessThan(+ lastTerm?.scrollToBottom.mock.invocationCallOrder[0] ?? 0,+ );+ expect(lastTerm?.viewportY).toBe(34);+ expect(lastTerm?.scrollbarLine).toBe(34);+ expect(lastTerm?.pendingScrollTarget).toBeNull();+ // Suppressed across the pair, then put back.+ expect(lastTerm?.smoothScrollWrites()).toBe(2);+ expect(lastTerm?.options.smoothScrollDuration).toBe(125);++ // A resize that leaves the grid alone is not a resize that can cost reach.+ if (lastTerm) {+ lastTerm.viewportY = 12;+ lastTerm.scrollbarLine = 3;+ }+ lastFit?.fit.mockImplementation(() => {});+ act(() => roCallback?.());+ expect(lastTerm?.viewportY).toBe(12);+ expect(lastTerm?.scrollbarLine).toBe(3);+ expect(lastTerm?.pendingScrollTarget).toBeNull();+ });+test("the WebGL canvas's device-pixel re-clear also repaints in the same frame", async () => {const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });render(<TerminalPanel bridge={bridge} />);diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsxindex a42de439d..42de52b47 100644--- a/packages/app/src/components/TerminalPanel.tsx+++ b/packages/app/src/components/TerminalPanel.tsx@@ -32,6 +32,7 @@ import { createTerminalFileLinkProvider } from './terminal-link-provider';import { createRecentOpenGuard, type TerminalLinkTarget } from './terminal-links';import { createSameFrameRepaint } from './terminal-render-flush';import { createResizeThrottle } from './terminal-resize-throttle';+import { restoreScrollReach } from './terminal-scroll-reach';import { nextWheelReports, sgrWheelReport, wheelReportPosition } from './terminal-wheel';import { useLiveXtermTheme } from './use-live-xterm-theme';@@ -702,7 +703,26 @@ function TerminalSession({const colsBefore = term.cols;const rowsBefore = term.rows;fit.fit();- if (term.cols !== colsBefore || term.rows !== rowsBefore) repaintSameFrame();+ if (term.cols !== colsBefore || term.rows !== rowsBefore) {+ // Repaint first, then restore — for as long as the flush is+ // synchronous. `repaintSameFrame` flushes xterm's render debouncer,+ // and `_innerRefresh` ends by running the refresh callbacks, which is+ // where the viewport has queued the scroll-area sync that sets the+ // scrollbar's dimensions. So the flush is what re-derives those+ // dimensions against the new grid, and a restore running ahead of it+ // would re-assert a position against dimensions still describing the+ // old one.+ //+ // That last part is CONDITIONAL, so do not read it as an invariant.+ // The debouncer is a guarded internal: when a bump moves it,+ // `createSameFrameRepaint` warns and defers the refresh — and the+ // dimension sync riding on it — to the next frame, which puts the+ // restore back ahead of the sync. Nothing here detects that; the+ // warning is the signal, and in that state the panel has already lost+ // its same-frame repaint too.+ repaintSameFrame();+ restoreScrollReach(term);+ }ptyResizeThrottle?.request();});observer.observe(container);diff --git a/packages/app/src/components/terminal-scroll-model.test-helper.ts b/packages/app/src/components/terminal-scroll-model.test-helper.tsnew file mode 100644index 000000000..83590844b--- /dev/null+++ b/packages/app/src/components/terminal-scroll-model.test-helper.ts@@ -0,0 +1,103 @@+/**+ * One model of the xterm scroll behaviour that `restoreScrollReach` turns on,+ * shared by every fake that needs it.+ *+ * Two fakes model this terminal: the unit fake beside `restoreScrollReach`, and+ * the `MockTerminal` the panel's DOM tests render against. They were written+ * independently and could disagree silently — and a fake that is kinder than+ * the real terminal accepts a restore the real terminal swallows, which is the+ * failure this whole seam exists to make impossible. Keeping the rules here+ * means TypeScript, rather than a comment, is what stops them drifting.+ *+ * Three rules, all read off the pinned `CoreBrowserTerminal`:+ *+ * 1. A scroll to the line already showing does nothing at all — `scrollToLine`+ * computes `line - buffer.ydisp` and returns early on zero. This is what+ * swallows the second half of a bounce whose first half has not landed yet.+ * 2. While `smoothScrollDuration` is set, a scroll hands a target to an+ * animated viewport and returns with `ydisp` unmoved; at zero it lands+ * immediately. This is why two scrolls in one tick cannot see each other's+ * work unless the duration is suppressed across the pair.+ * 3. A scroll that lands immediately CANCELS one still animating —+ * `setScrollPositionNow` disposes the pending smooth scroll before it sets+ * state. That is the production path rather than a hypothetical: it is how+ * suppressing the duration cuts a live momentum scroll short.+ *+ * The scrollbar's position is tracked apart from the buffer's because their+ * disagreement IS the defect under repair: landing on the parked line is not+ * observable in `viewportY` alone, which is where the viewport already reads.+ */++export interface ScrollModelState {+ /** First line the viewport is showing, as `buffer.active.viewportY` reads it. */+ viewportY: number;+ /** Where the scrollbar points. Agreement with `viewportY` is the fix. */+ scrollbarLine: number;+ /** Non-null while an animated scroll is still only scheduled. */+ pendingTarget: number | null;+}++export function createScrollModelState(+ viewportY: number,+ scrollbarLine = viewportY,+): ScrollModelState {+ return { viewportY, scrollbarLine, pendingTarget: null };+}++/** `scrollToLine` / `scrollToBottom`; the latter is the former aimed at `baseY`. */+export function applyModelledScroll(+ state: ScrollModelState,+ target: number,+ smoothScrollDuration: number | undefined,+): void {+ if (target - state.viewportY === 0) return;+ if (smoothScrollDuration) {+ state.pendingTarget = target;+ return;+ }+ state.viewportY = target;+ state.scrollbarLine = target;+ // Rule 3. Keeping a superseded target here would let `settle` teleport the+ // view past the scroll that replaced it; `terminal-scroll-reach.ts` discloses+ // the live-momentum case as the one thing the fix adds.+ state.pendingTarget = null;+}++/** Run whatever an animated scroll only scheduled. */+export function settleModelledScroll(state: ScrollModelState): void {+ if (state.pendingTarget === null) return;+ state.viewportY = state.pendingTarget;+ state.scrollbarLine = state.pendingTarget;+ state.pendingTarget = null;+}++/**+ * Instrument an options bag so writes to `smoothScrollDuration` are counted.+ *+ * Takes the bag rather than manufacturing one, so the DOM mock can instrument+ * the options the component hands it and the unit fake can instrument a literal+ * — one counter, both fakes, no second hand-rolled accessor pair.+ *+ * The scrolled-back guard has no effect on the scroll STATE — at the bottom,+ * both halves of the bounce target the line already showing, and rule 1 makes+ * each a no-op on its own. What the guard actually buys is that an ordinary+ * resize, which is most of them and every step of a drag, does not touch the+ * terminal's options at all. Counting the writes is how a test can see that,+ * and is why dropping the guard fails rather than passing silently.+ */+export function instrumentSmoothScrollOption(options: {+ smoothScrollDuration?: number;+}): () => number {+ let current = options.smoothScrollDuration;+ let writes = 0;+ Object.defineProperty(options, 'smoothScrollDuration', {+ configurable: true,+ enumerable: true,+ get: () => current,+ set: (next: number | undefined) => {+ current = next;+ writes += 1;+ },+ });+ return () => writes;+}diff --git a/packages/app/src/components/terminal-scroll-reach.test.ts b/packages/app/src/components/terminal-scroll-reach.test.tsnew file mode 100644index 000000000..d811a1663--- /dev/null+++ b/packages/app/src/components/terminal-scroll-reach.test.ts@@ -0,0 +1,114 @@+import { describe, expect, test } from 'vitest';+import {+ applyModelledScroll,+ createScrollModelState,+ instrumentSmoothScrollOption,+ settleModelledScroll,+} from './terminal-scroll-model.test-helper';+import { restoreScrollReach, type ScrollReachTarget } from './terminal-scroll-reach';++/**+ * A stand-in for xterm's `Terminal`. The scroll rules it obeys live in+ * `terminal-scroll-model.test-helper`, shared with the panel's DOM mock so the+ * two cannot drift; everything here is the shape those rules hang off.+ */+function makeTerminal({+ viewportY,+ baseY,+ smoothScrollDuration = 125,+ desyncedScrollbarLine,+}: {+ viewportY: number;+ baseY: number;+ smoothScrollDuration?: number;+ /** Where the resize left the scrollbar pointing. */+ desyncedScrollbarLine?: number;+}) {+ const state = createScrollModelState(viewportY, desyncedScrollbarLine ?? viewportY);+ const options = { smoothScrollDuration };+ const smoothScrollWrites = instrumentSmoothScrollOption(options);++ const term: ScrollReachTarget = {+ buffer: {+ active: {+ get viewportY() {+ return state.viewportY;+ },+ baseY,+ },+ },+ options,+ scrollToBottom() {+ applyModelledScroll(state, baseY, term.options.smoothScrollDuration);+ },+ scrollToLine(line: number) {+ applyModelledScroll(state, line, term.options.smoothScrollDuration);+ },+ };++ return {+ term,+ settle: () => settleModelledScroll(state),+ get viewportY() {+ return state.viewportY;+ },+ get scrollbarLine() {+ return state.scrollbarLine;+ },+ get pending() {+ return state.pendingTarget;+ },+ /** How many times the smooth-scroll duration was written. */+ optionWrites: smoothScrollWrites,+ };+}++describe('restoreScrollReach', () => {+ test('a viewport sitting at the bottom is left alone', () => {+ // Even a disagreeing scrollbar is left alone here: at the bottom there is+ // no reach to lose, and re-asserting would be work for nothing.+ const t = makeTerminal({ viewportY: 400, baseY: 400, desyncedScrollbarLine: 12 });+ restoreScrollReach(t.term);+ t.settle();+ expect(t.viewportY).toBe(400);+ expect(t.scrollbarLine).toBe(12);+ // The ordinary resize, and every step of a drag, must not touch the+ // terminal's options to decide it has nothing to do.+ expect(t.optionWrites()).toBe(0);+ });++ test('a buffer with no scrollback yet is left alone', () => {+ const t = makeTerminal({ viewportY: 0, baseY: 0 });+ restoreScrollReach(t.term);+ t.settle();+ expect(t.viewportY).toBe(0);+ });++ test('a scrolled-back viewport keeps its line and gets its scrollbar back', () => {+ // The resize left the scrollbar pinned at the top while the rows still+ // render from line 34. That disagreement is what refuses every scroll-up.+ const t = makeTerminal({ viewportY: 34, baseY: 108, desyncedScrollbarLine: 0 });+ restoreScrollReach(t.term);+ expect(t.viewportY).toBe(34);+ expect(t.scrollbarLine).toBe(34);+ // Nothing scheduled means nothing slides, and nothing paints at the bottom.+ expect(t.pending).toBeNull();+ // Suppressed across the pair, then put back: exactly two writes.+ expect(t.optionWrites()).toBe(2);+ t.settle();+ expect(t.viewportY).toBe(34);+ });++ test('the smooth-scroll duration is put back afterwards', () => {+ const t = makeTerminal({ viewportY: 34, baseY: 108, smoothScrollDuration: 125 });+ restoreScrollReach(t.term);+ expect(t.term.options.smoothScrollDuration).toBe(125);+ });++ test('a terminal that never had smooth scrolling is left exactly as it was', () => {+ const t = makeTerminal({ viewportY: 34, baseY: 108, smoothScrollDuration: 0 });+ restoreScrollReach(t.term);+ expect(t.term.options.smoothScrollDuration).toBe(0);+ expect(t.viewportY).toBe(34);+ });+});diff --git a/packages/app/src/components/terminal-scroll-reach.ts b/packages/app/src/components/terminal-scroll-reach.tsnew file mode 100644index 000000000..92fcebcc7--- /dev/null+++ b/packages/app/src/components/terminal-scroll-reach.ts@@ -0,0 +1,93 @@+/**+ * Put a scrolled-back terminal viewport back in agreement with its scrollbar+ * after the grid resizes, without moving what the reader is looking at.+ *+ * A resize taken while the user is scrolled up leaves the viewport refusing to+ * go any further up. The lines above are still there — scrolling all the way+ * DOWN and back up reaches them — but every scroll-up from the parked position+ * is ignored, by wheel and by keyboard alike, and no later resize clears it.+ *+ * The cause is that xterm keeps two positions: `buffer.ydisp`, which the rows+ * are rendered from, and the scrollbar's own `scrollTop`. A resize re-derives+ * the scrollbar's DIMENSIONS on the next refresh callback but never its+ * POSITION, so `scrollTop` can end up pinned at zero while `ydisp` still says a+ * line well into the buffer. A scroll-up then resolves to the `scrollTop` it+ * already has, decides nothing changed, and the rows never move. Touching the+ * bottom is what re-establishes agreement, because a scroll that really moves+ * drives `scrollTop` and `ydisp` back through the same path together.+ *+ * Hence a bounce — but it only works with the animation off. The panel sets+ * `smoothScrollDuration`, under which every public scroll hands a target to an+ * animated viewport and returns before `ydisp` has moved. Two of them therefore+ * do not compose: `scrollToLine` computes its delta as `line - buffer.ydisp`,+ * so after an animated `scrollToBottom` it reads a `ydisp` that has not moved,+ * computes zero, and does nothing at all — leaving the reader at the bottom+ * instead of where they were. Suppressing the duration across the pair makes+ * both hops land in this tick, which is what lets the second one see the first,+ * and is why nothing is painted at the bottom on the way through.+ *+ * Two gates, and they are not the same gate. The caller only reaches here when+ * the fit CHANGED THE GRID, because a resize crossing no cell boundary cannot+ * cost anyone their reach. This checks that the viewport is SCROLLED BACK — and+ * not because the bounce would otherwise move something: at the bottom both+ * hops target the line already showing, and a scroll to the line you are on+ * returns early on its zero delta, so it moves nothing at all. What the gate+ * buys is that an ordinary resize never writes the terminal's OPTIONS, and the+ * fit half of the caller's observer is deliberately unthrottled, so that is+ * every grid-changing step of a drag. Both tests assert the position too, but+ * the option writes are what DISCRIMINATE: at the bottom a correct guard and+ * one with the guard REMOVED leave the position identical, since both hops+ * would target the line already showing, so the two writes the unguarded+ * version makes are the only thing telling them apart. Neither gate implies the other, so the+ * caller's is not re-checked here and this one is not hoisted into the caller.+ *+ * Retiring this: it can go when a resize leaves the scrollbar and `ydisp` in+ * agreement on its own. Nothing in xterm's public API reports that, so the test+ * is the behaviour rather than a version number — park a viewport back in the+ * scrollback, resize the grid, and see whether `Shift+PageUp` moves the rows+ * without this having run first. If it does, delete this and its tests.+ *+ * What this does NOT do is hold the line the reader had before the resize.+ * xterm anchors the most recent visible line through a reflow, so a tall panel+ * becoming a short one moves them down the buffer whatever happens here; this+ * adds no movement of its own on top of that.+ *+ * Nor does it preserve a scroll that is still ANIMATING. Suppressing the+ * duration makes both hops land immediately, and an immediate scroll disposes+ * any pending smooth scroll before it sets position — so a resize arriving+ * while the reader's momentum is still running cancels the rest of it, and+ * `parked` is read from wherever the animation had got to rather than where it+ * was heading. Each wheel event restarts the animation, so that window lasts as+ * long as the momentum stream does, and the unthrottled fit means a menu-driven+ * move or a window resize can land inside it. Strictly better than the dead end+ * it replaces, but it is the one thing the reader may notice.+ */++/** The slice of xterm's `Terminal` this needs, so a caller can be a stub. */+export interface ScrollReachTarget {+ readonly buffer: {+ readonly active: {+ /** First line the viewport is showing. */+ readonly viewportY: number;+ /** The viewport line that means "at the bottom". */+ readonly baseY: number;+ };+ };+ options: { smoothScrollDuration?: number };+ scrollToBottom(): void;+ scrollToLine(line: number): void;+}++export function restoreScrollReach(term: ScrollReachTarget): void {+ const parked = term.buffer.active.viewportY;+ if (parked >= term.buffer.active.baseY) return;++ const smoothScrollDuration = term.options.smoothScrollDuration;+ term.options.smoothScrollDuration = 0;+ try {+ term.scrollToBottom();+ term.scrollToLine(parked);+ } finally {+ term.options.smoothScrollDuration = smoothScrollDuration;+ }+}diff --git a/packages/desktop/tests/smoke/terminal-movement.e2e.ts b/packages/desktop/tests/smoke/terminal-movement.e2e.tsindex 45e1803ae..75858e3ef 100644--- a/packages/desktop/tests/smoke/terminal-movement.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-movement.e2e.ts@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import type { ElectronApplication, Page } from '@playwright/test';+import type { ElectronApplication, ElementHandle, Page } from '@playwright/test';import { _electron as electron } from '@playwright/test';import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';import { PTY_PLATFORM_SKIP_REASON, PTY_PLATFORM_SUPPORTED } from './_helpers/platform-gate';@@ -96,13 +96,12 @@ async function findEditorWindow(app: ElectronApplication, timeoutMs = 25_000): P/*** `editorPage` lets a caller that already holds the editor window skip the- * rediscovery poll. That poll is not free: it re-evaluates- * `window.okDesktop.config.mode` in the renderer, so it costs whatever the- * renderer's main thread is busy with, measured at ~400ms on a loaded CI- * runner. Any caller TIMING this dispatch must pass the page, or it charges the- * app for the harness's own round trip. On darwin the menu click happens inside- * main and never pays it at all, so leaving it in makes the same assertion mean- * two different things per platform.+ * rediscovery poll. That poll re-evaluates `window.okDesktop.config.mode` in+ * the renderer, so it waits on whatever the renderer's main thread is busy+ * with. Any caller that has armed a settlement observer should pass the page:+ * the poll otherwise sits between arming and dispatch, widening the window the+ * observer has to survive for no reason the app is responsible for. On darwin+ * the menu click happens inside main and never pays it at all.*/async function dispatchRendererMenuAction(app: ElectronApplication,@@ -173,8 +172,8 @@ async function clickTerminalPlacementItemRapidly(if (process.platform !== 'darwin') {for (let index = 0; index < count; index += 1) {// The page matters most here: without it each of these iterations pays- // its own rediscovery poll, and the settlement being timed spans all of- // them.+ // its own rediscovery poll, and the settlement being awaited spans all+ // of them.await dispatchRendererMenuAction(app, 'move-terminal', editorPage);}return;@@ -286,6 +285,26 @@ async function typeInActiveTerminal(page: Page, text: string): Promise<void> {await page.keyboard.type(text);}+/**+ * The rendered rows of the active terminal, and NOTHING else.+ *+ * Use this wherever being wrong about what is on screen would be wrong in the+ * ASSERTION's direction: anything checking a marker is ABSENT, and anything+ * PARSING what it reads. `readActiveTerminal`'s union with the announcement+ * buffer can only make those two fail — it holds lines the rows no longer show,+ * and it truncates mid-token under a burst.+ *+ * WAITING is the case that TOLERATES the union, which is why the waits+ * elsewhere in this file still use it — both the marker polls and the+ * shell-readiness wait. Extra content can only ever delay a wait, never satisfy+ * one wrongly: a stale line cannot contain a token that has not been printed.+ */+function readTerminalRows(page: Page): Promise<string> {+ return visibleTerminal(page).evaluate(+ (section) => section.querySelector('.xterm-rows')?.textContent ?? '',+ );+}+async function readActiveTerminal(page: Page): Promise<string> {return visibleTerminal(page).evaluate((section) => {const accessibility = section.querySelector('.xterm-accessibility')?.textContent ?? '';@@ -307,35 +326,73 @@ async function readActiveTerminal(page: Page): Promise<string> {* announcement buffer, and the line printed right after it had been cut in* half there and was not yet scrolled into the rows.*- * Steps are deliberately shorter than one wheel-page for the same reason:- * markers on adjacent lines must not be able to straddle a step boundary and- * so never appear together.+ * Pages with the keyboard, NOT the wheel. The panel sets+ * `smoothScrollDuration`, so a wheel notch does not move the rows — it+ * retargets an animation the renderer interpolates over the following frames,+ * and each further notch restarts that animation from wherever it had got to.+ * Reading straight after the last notch therefore reads a view still in flight,+ * and how far along it is depends on how many frames the runner could spare:+ * a made-up dependency on the machine for an assertion about retained lines.+ *+ * `Shift+PageUp` is animated too — `scrollPages` reaches the same viewport the+ * wheel does — so this does not escape the animation, it stops racing it. Each+ * press asks for one page rather than the wheel's several, the loop re-reads+ * between presses, and paging past the top is inert, so the presses converge on+ * the top instead of overshooting a target still being interpolated toward. The+ * ceiling is several times the pages either home needs to cross this fixture's+ * scrollback, so it bounds a stuck loop rather than the travel.*/async function expectScrollbackRetains(page: Page, ...markers: string[]): Promise<void> {- const terminal = visibleTerminal(page).locator('.xterm');- await terminal.hover();- const readRows = () =>- visibleTerminal(page).evaluate(- (section) => section.querySelector('.xterm-rows')?.textContent ?? '',- );-- let text = await readRows();+ // Focus the node xterm actually reads keys from. Clicking the row grid would+ // do it too, but a click lands on whatever the session last printed, and the+ // panel activates file links on a plain click — so the first path-shaped+ // token in this output would navigate the editor and take the focus that+ // every press below depends on.+ await visibleTerminal(page).locator('.xterm-helper-textarea').focus();+ let text = await readTerminalRows(page);for (let step = 0; step < 40 && !markers.every((marker) => text.includes(marker)); step += 1) {- await page.mouse.wheel(0, -500);- await page.evaluate(- () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())),- );- text = await readRows();+ await page.keyboard.press('Shift+PageUp');+ text = await readTerminalRows(page);}for (const marker of markers) {expect(text, `terminal scrollback is missing ${marker}`).toContain(marker);}+ await settleScrollPosition(page);+}++/**+ * Wait until the rows stop moving.+ *+ * The paging above is animated, so the position after the last press is a+ * target rather than a fact — and this is the only thing in the file that+ * leaves the view mid-flight, which is why the settle lives here rather than at+ * whichever caller happens to resize next. A resize refits the grid against+ * whatever line the buffer shows AT THAT INSTANT, so a move taken mid-animation+ * shrinks from a position that varies run to run, and every assertion about+ * what the shrink did to the scrollback inherits that variance.+ *+ * Each sample sits behind an animation frame, so consecutive reads cannot all+ * land inside one paint and report a stillness that is really just a fast round+ * trip. Best-effort by design: if the rows never settle inside the bound, the+ * assertions that follow are what fail, and they say something about the+ * product rather than about the sampling.+ */+async function settleScrollPosition(page: Page): Promise<void> {+ let previous = '';+ let stable = 0;+ for (let step = 0; step < 60 && stable < 2; step += 1) {+ await page.evaluate(+ () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())),+ );+ const current = await readTerminalRows(page);+ stable = current === previous ? stable + 1 : 0;+ previous = current;+ }}-function waitForTerminalHome(page: Page, home: TerminalHome): Promise<number> {+function waitForTerminalHome(page: Page, home: TerminalHome): Promise<void> {return page.evaluate((targetHome) => {- return new Promise<number>((resolve, reject) => {- const startedAt = performance.now();+ return new Promise<void>((resolve, reject) => {const activeSelector =targetHome === 'right'? '#terminal-column section[aria-label="Terminal"]'@@ -360,7 +417,7 @@ function waitForTerminalHome(page: Page, home: TerminalHome): Promise<number> {const rect = active?.getBoundingClientRect();if (active && !inactive && rect && rect.width > 0 && rect.height > 0 && text.length > 0) {window.clearTimeout(timeout);- resolve(performance.now() - startedAt);+ resolve();return;}frame = window.requestAnimationFrame(inspect);@@ -375,24 +432,74 @@ async function moveTerminal(app: ElectronApplication,page: Page,home: TerminalHome,-): Promise<number> {+): Promise<void> {const settlement = waitForTerminalHome(page, home);- // The stopwatch is already running inside the renderer, so the dispatch must- // not re-discover the window on the clock.+ // The observer is already armed inside the renderer, so the dispatch must not+ // re-discover the window before sending.await clickTerminalPlacementItem(app, page);- return settlement;+ await settlement;+}++/**+ * The live terminal surface, held so a later assertion can prove the SAME node+ * is what ended up at the other home. Follows `.xterm` rather than the section+ * wrapping it, so the node being tracked is the terminal itself.+ */+async function captureLiveTerminal(page: Page): Promise<ElementHandle<Element>> {+ const handle = await visibleTerminal(page).locator('.xterm').elementHandle();+ if (!handle) throw new Error('no visible Terminal surface to follow across the move');+ return handle;+}++/**+ * Moving the terminal must RE-PARENT the live surface, never tear it down and+ * build a fresh one at the other home. That is the property this file exists to+ * defend — a rebuilt surface is a dead PTY, a lost scrollback and a visible+ * stall — and following one node across the move states it outright.+ *+ * It stands where a wall-clock budget on the settlement used to, which could+ * only claim the property by proxy. That budget measured the harness as much as+ * the app: the observer arms in the renderer BEFORE the dispatch is sent, so+ * its number spanned a Playwright round trip and, on darwin, a main-process+ * menu click and its IPC too. Node identity does not move with how busy the+ * machine is.+ *+ * Nothing here bounds how LONG the move takes, deliberately: the only clock+ * this harness can read spans its own round trip to the renderer, so any number+ * it produces is partly a measurement of the runner. What remains is+ * `waitForTerminalHome`'s 5s rejection, which catches a move that never lands+ * rather than one that is merely slow — a move that became four seconds slower+ * would pass here. A budget worth having would have to be taken inside the app,+ * against a clock the harness does not sit on.+ */+async function expectTerminalMovedNotRebuilt(+ surface: ElementHandle<Element>,+ home: TerminalHome,+): Promise<void> {+ const containerId = home === 'right' ? 'terminal-column' : 'terminal-dock-panel';+ const placement = await surface.evaluate(+ (element, id) => ({+ connected: element.isConnected,+ atHome: element.closest(`#${id}`) !== null,+ }),+ containerId,+ );+ expect(placement, `the live terminal surface did not survive the move to ${home}`).toEqual({+ connected: true,+ atHome: true,+ });}/*** The live shell's pid, read from the terminal ROWS alone.*- * Every other reader here substring-matches a whole marker, so xterm's- * `.xterm-accessibility` announcement buffer can only ever delay them — a- * truncated prefix never satisfies a `toContain`. This one PARSES, which makes- * truncation dangerous rather than merely slow: a `MARKER=67818` cut short in- * the announcement buffer yields `67`, which clears the `toBeGreaterThan(0)`- * gate and then gets compared against the real pid as proof the session- * survived a move. Rows carry no such truncation.+ * This one PARSES rather than substring-matching a whole marker, which makes+ * the announcement buffer's truncation dangerous rather than merely slow: a+ * `MARKER=67818` cut short there yields `67`, which clears the+ * `toBeGreaterThan(0)` gate and is then compared against the real pid as proof+ * the session survived a move. Rows carry no such truncation.+ *+ * Which reader any given site wants is set out on `readTerminalRows`.*/async function readShellPid(page: Page, marker: string): Promise<number> {await typeInActiveTerminal(page, `printf '${marker}=%s\\n' "$$"\r`);@@ -400,9 +507,7 @@ async function readShellPid(page: Page, marker: string): Promise<number> {await expect.poll(async () => {- const rows = await visibleTerminal(page).evaluate(- (section) => section.querySelector('.xterm-rows')?.textContent ?? '',- );+ const rows = await readTerminalRows(page);const matches = [...rows.matchAll(new RegExp(`${marker}=(\\d+)`, 'g'))];processId = Number(matches.at(-1)?.[1] ?? 0);return processId;@@ -439,15 +544,39 @@ async function expectCollapsedRailColumn(page: Page, selector: string): Promise<.toBe(0);}+/**+ * A move must not leave a scrolled-back reader at the bottom.+ *+ * Both callers reach this straight after `expectScrollbackRetains`, so the view+ * is parked back in the scrollback and the newest line is off screen. Any+ * restore that ends up at the bottom — the shape a scroll pair takes when its+ * second half is swallowed — puts that line back in view. That is the one+ * outcome distinguishable from a healthy move without asserting an exact+ * landing line the reflow is entitled to choose.+ *+ * Reads the ROWS. `readActiveTerminal` would fold in the announcement buffer,+ * which still holds the newest line from when it was printed, so an absence+ * assertion against it would contradict the presence assertion its own caller+ * just made.+ */+async function expectStillScrolledBack(page: Page, newestLine: string): Promise<void> {+ expect(+ await readTerminalRows(page),+ 'the move left a scrolled-back reader at the bottom of the buffer',+ ).not.toContain(newestLine);+}+test.describe('Terminal placement continuity — live Electron', () => {test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');test.skip(!PTY_PLATFORM_SUPPORTED, PTY_PLATFORM_SKIP_REASON);test.skip(!TARGET.exists, TARGET.missingReason);test('moving a populated terminal preserves every live session', async ({ captureStderrFor }) => {- // The static calibration parser totals 225s of sequential condition- // budgets; the 240s outer budget leaves 15s for untimed interaction work.- test.setTimeout(240_000);+ // The static calibration parser totals 235s of sequential condition+ // budgets, which are worst-case ceilings rather than expected costs. The+ // 260s outer budget leaves 25s for everything the parser cannot see: the+ // Electron launch, every focus and keystroke, and the paging round trips.+ test.setTimeout(260_000);const s = seed();const app = await launchApp(s);captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });@@ -476,22 +605,32 @@ test.describe('Terminal placement continuity — live Electron', () => {.toContain(`SCROLL_${token}_120`);await expectScrollbackRetains(page, sentinel, scrollStart);- const toRightMs = await moveTerminal(app, page, 'right');- expect(toRightMs).toBeLessThan(300);+ const liveSurface = await captureLiveTerminal(page);+ await moveTerminal(app, page, 'right');+ await expectTerminalMovedNotRebuilt(liveSurface, 'right');+ await expectStillScrolledBack(page, `SCROLL_${token}_120`);await expect(terminalTabs(page)).toHaveText(['Terminal 1', 'Terminal 2']);await expect(page.getByRole('tab', { name: 'Terminal 2' })).toHaveAttribute('aria-selected','true',);+ // Content retention across the GROW, not reach: the view enters this move+ // at the top of the buffer, and growing 15 rows to 52 leaves almost nothing+ // above it for a broken restore to swallow. The shrink leg below is where+ // reach is actually exercised.await expectScrollbackRetains(page, sentinel, scrollStart);expect(await readShellPid(page, processMarker)).toBe(processId);const rightOutput = `RIGHT_OUTPUT_${token}`;await typeInActiveTerminal(page, `printf '${rightOutput}\\n'\r`);await expect.poll(() => readActiveTerminal(page), { timeout: 15_000 }).toContain(rightOutput);+ // The shrink is the leg that can lose reach: 52 rows down to 15 anchors the+ // newest visible line and lands tens of rows below the markers, so the+ // re-read after it has to page all the way back up.await expectScrollbackRetains(page, sentinel, scrollStart);- const toBottomMs = await moveTerminal(app, page, 'bottom');- expect(toBottomMs).toBeLessThan(300);+ await moveTerminal(app, page, 'bottom');+ await expectTerminalMovedNotRebuilt(liveSurface, 'bottom');+ await expectStillScrolledBack(page, `SCROLL_${token}_120`);await expect(terminalTabs(page)).toHaveText(['Terminal 1', 'Terminal 2']);await expect(page.getByRole('tab', { name: 'Terminal 2' })).toHaveAttribute('aria-selected',@@ -505,7 +644,8 @@ test.describe('Terminal placement continuity — live Electron', () => {const rapidSettlement = waitForTerminalHome(page, 'right');await clickTerminalPlacementItemRapidly(app, 7, page);- expect(await rapidSettlement).toBeLessThan(300);+ await rapidSettlement;+ await expectTerminalMovedNotRebuilt(liveSurface, 'right');await expect(page.locator('section[aria-label="Terminal"]')).toHaveCount(2);await expect(visibleTerminal(page)).toHaveCount(1);await expect(page.locator('#terminal-column section[aria-label="Terminal"]')).toHaveCount(2);@@ -527,9 +667,10 @@ test.describe('Terminal placement continuity — live Electron', () => {test('renderer restart restores the right layout and its live active terminal', async ({captureStderrFor,}) => {- // The static calibration parser totals 255s across both reload cycles;- // the 270s outer budget leaves 15s for untimed interaction work.- test.setTimeout(270_000);+ // The static calibration parser totals 265s across both reload cycles,+ // which are worst-case ceilings rather than expected costs. The 290s outer+ // budget leaves 25s for the untimed interaction work between them.+ test.setTimeout(290_000);const s = seed({ skipRestoreState: true });const app = await launchApp(s);captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });