mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-16 11:19:33 +01:00
Merge pull request #698: fix(terminal): the wheel no longer moves a Codex selection menu's selection
Conflicts resolved by keeping both sides: - src/web/public/terminal-ui.js (_maybePageCliTranscript): #698's Codex-menu consume check sits right after the open-dialog consume check (its sibling, as the docblock lists them), and #681's unloaded-scrollback fall-through (paneHistoryLines > 0) follows it. - docs/architecture-invariants.md: the hollow-pane paragraph carries #681's unloaded-scrollback sentence and #698's menu rewording. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
commit
0160db9927
6 files changed
+299
-4
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'aicodeman': patch
|
||||
---
|
||||
|
||||
Scrolling over a Codex selection menu no longer moves its selection. When Codex does not track the mouse (measured on 0.162.1 and 0.164.0), Codeman turns the wheel into PageUp and PageDown, which those menus use to move the selection: at the "Implement this plan?" prompt one notch down landed on "No, stay in Plan mode" and one up on "Yes, implement this plan". The wheel is now consumed while such a menu is showing (main pane and tiles) and pages the transcript again once it closes.
|
||||
@@ -245,9 +245,9 @@ Native wheel travel retains upstream pixel/line/page units (100 px = 4 lines; Fi
|
||||
|
||||
**Wheel/touch forwarding is NOT gated on viewport-at-bottom** (#205, `terminal-ui.js:_shouldForwardWheelToApp`): for sessions verified to scroll their own transcript on SGR wheel reports (Claude ≥ 2.1.187 or tracked Codex, with observed `cliMouseTracking`; see the native measurement above), the plain wheel AND touch drags forward as coalesced SGR reports (`_forwardScrollToApp` → `_sendSyntheticSgrWheel`, 40ms batches after the first native report, 5-tick per-event cap; no aggregate byte/tick limit). It used to gate on the viewport being at the bottom so both scrollbacks stayed reachable, but a repaint-mode CLI keeps NO terminal scrollback of its own — xterm's buffer holds only replayed repaint frames, so local scrolling drags the CLI's pinned prompt box up the screen over stale frames; and `scrollToLastNonEmptyLine()` routinely parked the viewport off-bottom, silently pinning the wheel to local. Forwarding now snaps the viewport home first (SGR coordinates address the LIVE screen — a report computed from a scrolled-up viewport would hit-test the wrong row). Local scrollback remains on Shift+wheel and the `terminalWheelLocalScrollback` opt-out (both also cover touch via the shared gate; touch has no Shift, so the setting is its only local pin). Touch asks `_shouldForwardTouchToApp()`, which is that gate plus one branch: in any session mode, a drag and its fling momentum also forward as SGR wheel reports while xterm itself tracks the mouse (`modes.mouseTrackingMode` other than `none`/`x10`) with SGR encoding (`_core.coreMouseService.activeEncoding === 'SGR'`, an xterm private pinned by `test/xterm-private-api.test.ts`; DEFAULT, X10 and SGR-pixel apps fail closed). xterm encodes a native wheel for such an app itself, but the touch listeners consume the drag, and a local scroll shows nothing useful: a direct-PTY app is on xterm's alternate screen, and in a tmux-backed session xterm stays in the normal buffer holding stale tmux repaints. `_wheelScrollLinesFloat()` normalizes `deltaMode` (Firefox fires LINE deltas ≈3/notch — read as pixels that rounded to 0 and fell to the ±1 fallback, ~4× too slow; PAGE deltas scale by `terminal.rows`) while keeping the #154 Shift-axis trap (macOS trackpads put Shift+scroll magnitude on deltaX). Tests: `test/terminal-touch-tap.test.ts`.
|
||||
|
||||
**A false gate on a hollow pane must not mean a DEAD gesture** (#205 round 2, `_maybePageCliTranscript`): every way `_shouldForwardWheelToApp()` returns false leaves a repaint-mode pane scrolling a buffer that has nothing in it (`baseY === 0`) — the version probe came back empty, the CLI really is older than 2.1.187, the `cliMouseTracking` flag is unset (inline claude, or fullscreen right after a server restart), or the user turned on `terminalWheelLocalScrollback`. **opencode is the fifth case, and the gate is false there by design**: its TUI runs on the ALTERNATE SCREEN (1.18.31 measured: tmux `alternate_on=1`, `history_size=0`), so the buffer is hollow, and it IGNORES SGR wheel reports entirely (six `\x1b[<64;…M` reports against an idle pane left the capture byte-identical) while still paging its transcript on PageUp/PageDown (`messages_page_up/down`) — so paging is the only gesture that can reach it, and without it the wheel was silently dead in every opencode tab. The 1.12.0 retest reported exactly that shape for Claude: a wheel that did nothing at all while Fn+Up (PageUp) paged back through intact text, which is the proof that the CLI's own history and the PTY input path were both fine. So under the guard (`_localScrollbackIsHollow()`: the `transcriptPageKeys` capability, gate false, `baseY === 0`) wheel and touch travel is translated into coalesced `\x1b[5~` / `\x1b[6~` through the same 40ms queue as the SGR reports, at half a screen of travel per page key (the key jumps a whole screen; a 1:1 mapping was unusably slow with a discrete wheel). ⚠️ **`baseY === 0` with a pane that still REPORTS scrollback is not hollow, it is unloaded** (`paneHistoryLines` > 0, the last capture's `#{history_size}`): after a server restart the byte recording a tab switch replays (`?tail=`) holds only the tmux client's attach repaint, which scrolls nothing, so an inline Claude session landed here and the page keys moved its composer cursor instead of the transcript (measured 2026-10-21 on the second select after a restart, until a page reload). That case falls through to local scrolling, whose top-of-buffer pull (`_maybeLoadMoreHistoryOnScroll` to `_maybeRefetchFullHistory`) fetches `full=1`, and the gesture scrolls on from there once the pull lands (a slow response can outlive the gesture; the next one scrolls); 0 and unknown counts keep paging (fullscreen Claude, codex, opencode; a remote pane reports no count and a Docker pane 0). Page keys already queued and the gesture debt are dropped on the way out, since they belong to the abandoned route. The `[scroll]` line prints `paneHistoryLines` next to `localScrollbackRows`, and a count turning positive re-logs, so the two states read apart. The trade-off is accepted: while that pull is in flight or has failed, the gesture scrolls an empty buffer and the next upward gesture after the 4 s cooldown retries it, where paging would have moved the composer. An error envelope (`success: false`) records no count, in the pull, the refresh path and the tab switch alike, so one failed capture does not hand the gesture back to paging. ⚠️ The first event of a trackpad-sized gesture (opening under 2 rows) pages AT ONCE and the travel it skipped is owed back by the rest of the gesture (one page per half screen still). Waiting for half a screen first meant an ordinary trackpad flick (well under 19 rows on a 38-row pane) sent nothing at all. A larger opening event is a mouse-wheel notch (100 px is 4 rows) and accumulates as before, or slow notches, each its own gesture past the gap, would page a full screen apiece. ⚠️ What starts a NEW gesture (and so may pre-pay) is narrow, because every boundary is another free page: (1) a TOUCH CONTACT is one gesture, never split by time: the touch paths tag every call, touchmove and momentum frames alike, with `touchId` (one per touchstart), and a different id (or a wheel event after a touch) is a boundary. touchmove only calls once per whole cell of finger travel, so a slow drag arrives as single lines further apart than any gap; on the gap alone 12 lines at 170 ms each sent 12 PageUps (measured through the real listeners, `test/terminal-touch-paging.browser.test.ts`). (2) Outside a contact, 150 ms of quiet (`PAGE_KEY_GESTURE_GAP_MS`), stretched to one second (`PAGE_KEY_DEBT_MS`) while a pre-paid page is still owed in the SAME direction, so slow small wheel ticks (40 px every 250 ms, a Firefox 1-line notch) pay the debt back instead of each pre-paying a page; after a second of quiet the debt lapses and the next small tick pages at once again. The debt also ends the moment travel repays it (reaches or crosses zero): the rest is plain travel and the 150 ms gap applies again. (3) A direction change inside a gesture (within the gap, or within one contact) drops a pre-paid debt (it belongs to the other direction) and accumulates WITHOUT pre-paying, so a +/-3 px trackpad wobble pages once for its opening event and then nothing; a reversal aLine truncated
|
||||
**A false gate on a hollow pane must not mean a DEAD gesture** (#205 round 2, `_maybePageCliTranscript`): every way `_shouldForwardWheelToApp()` returns false leaves a repaint-mode pane scrolling a buffer that has nothing in it (`baseY === 0`) — the version probe came back empty, the CLI really is older than 2.1.187, the `cliMouseTracking` flag is unset (inline claude, or fullscreen right after a server restart), or the user turned on `terminalWheelLocalScrollback`. **opencode is the fifth case, and the gate is false there by design**: its TUI runs on the ALTERNATE SCREEN (1.18.31 measured: tmux `alternate_on=1`, `history_size=0`), so the buffer is hollow, and it IGNORES SGR wheel reports entirely (six `\x1b[<64;…M` reports against an idle pane left the capture byte-identical) while still paging its transcript on PageUp/PageDown (`messages_page_up/down`) — so paging is the only gesture that can reach it, and without it the wheel was silently dead in every opencode tab. The 1.12.0 retest reported exactly that shape for Claude: a wheel that did nothing at all while Fn+Up (PageUp) paged back through intact text, which is the proof that the CLI's own history and the PTY input path were both fine. So under the guard (`_localScrollbackIsHollow()`: the `transcriptPageKeys` capability, gate false, `baseY === 0`) wheel and touch travel is translated into coalesced `\x1b[5~` / `\x1b[6~` through the same 40ms queue as the SGR reports, at half a screen of travel per page key (the key jumps a whole screen; a 1:1 mapping was unusably slow with a discrete wheel). ⚠️ **`baseY === 0` with a pane that still REPORTS scrollback is not hollow, it is unloaded** (`paneHistoryLines` > 0, the last capture's `#{history_size}`): after a server restart the byte recording a tab switch replays (`?tail=`) holds only the tmux client's attach repaint, which scrolls nothing, so an inline Claude session landed here and the page keys moved its composer cursor instead of the transcript (measured 2026-10-21 on the second select after a restart, until a page reload). That case falls through to local scrolling, whose top-of-buffer pull (`_maybeLoadMoreHistoryOnScroll` to `_maybeRefetchFullHistory`) fetches `full=1`, and the gesture scrolls on from there once the pull lands (a slow response can outlive the gesture; the next one scrolls); 0 and unknown counts keep paging (fullscreen Claude, codex, opencode; a remote pane reports no count and a Docker pane 0). Page keys already queued and the gesture debt are dropped on the way out, since they belong to the abandoned route. The `[scroll]` line prints `paneHistoryLines` next to `localScrollbackRows`, and a count turning positive re-logs, so the two states read apart. The trade-off is accepted: while that pull is in flight or has failed, the gesture scrolls an empty buffer and the next upward gesture after the 4 s cooldown retries it, where paging would have moved the composer. An error envelope (`success: false`) records no count, in the pull, the refresh path and the tab switch alike, so one failed capture does not hand the gesture back to paging. ⚠️ The first event of a trackpad-sized gesture (opening under 2 rows) pages AT ONCE and the travel it skipped is owed back by the rest of the gesture (one page per half screen still). Waiting for half a screen first meant an ordinary trackpad flick (well under 19 rows on a 38-row pane) sent nothing at all. A larger opening event is a mouse-wheel notch (100 px is 4 rows) and accumulates as before, or slow notches, each its own gesture past the gap, would page a full screen apiece. ⚠️ What starts a NEW gesture (and so may pre-pay) is narrow, because every boundary is another free page: (1) a TOUCH CONTACT is one gesture, never split by time: the touch paths tag every call, touchmove and momentum frames alike, with `touchId` (one per touchstart), and a different id (or a wheel event after a touch) is a boundary. touchmove only calls once per whole cell of finger travel, so a slow drag arrives as single lines further apart than any gap; on the gap alone 12 lines at 170 ms each sent 12 PageUps (measured through the real listeners, `test/terminal-touch-paging.browser.test.ts`). (2) Outside a contact, 150 ms of quiet (`PAGE_KEY_GESTURE_GAP_MS`), stretched to one second (`PAGE_KEY_DEBT_MS`) while a pre-paid page is still owed in the SAME direction, so slow small wheel ticks (40 px every 250 ms, a Firefox 1-line notch) pay the debt back instead of each pre-paying a page; after a second of quiet the debt lapses and the next small tick pages at once again. The debt also ends the moment travel repays it (reaches or crosses zero): the rest is plain travel and the 150 ms gap applies again. (3) A direction change inside a gesture (within the gap, or within one contact) drops a pre-paid debt (it belongs to the other direction) and accumulates WITHOUT pre-paying, so a +/-3 px trackpad wobble pages once for its opening event and then nothing; a reversal aLine truncated
|
||||
|
||||
**Why the wheel went where it went is LOGGED** (`_logScrollRouting`): one console line per session per distinct decision — `[scroll] <id> → forward-sgr|page-keys|local-scrollback|repull-refused-downgrade (mode=…, cliVersion=…, localScrollbackOptOut=…, mouseTracking=…, localScrollbackRows=…)`. #205 ran two rounds of remote guesswork over questions this line answers directly; keep it when touching the routing.
|
||||
**Why the wheel went where it went is LOGGED** (`_logScrollRouting`): one console line per session per distinct decision — `[scroll] <id> → forward-sgr|page-keys|page-keys-dialog-open|page-keys-menu-open|local-scrollback|repull-refused-downgrade (mode=…, cliVersion=…, localScrollbackOptOut=…, mouseTracking=…, localScrollbackRows=…)`. #205 ran two rounds of remote guesswork over questions this line answers directly; keep it when touching the routing.
|
||||
|
||||
**The wheel listener is CAPTURE-phase and Codeman owns the scroll** (#205 follow-up, measured on the live instance): xterm's viewport is a vscode-style ScrollableElement that consumes wheel events itself (preventDefault + stopPropagation) whenever it believes a scrollbar exists, ignores `attachCustomWheelEventHandler`, and goes DEAF after `terminal.reset()` — a tab switch or full-history replay leaves its scroll dimensions stale, after which wheel events neither scroll nor propagate reliably. A bubble-phase container listener therefore never fired once local scrollback existed (forwarding, deltaMode and the top-of-buffer re-pull all silently dead exactly on sessions WITH history), and after a tab switch nothing scrolled at all ("works at first, breaks after a tab switch"). The container wheel listener is `{capture: true}`, stops propagation, and scrolls locally via buffer-level `terminal.scrollLines()` (immune to the stale scroller). ⚠️ Two cases are deliberately passed through untouched, in this order BEFORE preventDefault: `mouseTrackingMode !== 'none'` (xterm's encoder forwards the wheel to the PTY — htop/vim with mouse on) and `buffer.active.type === 'alternate'` (direct-PTY vim/less: xterm's alt-scroll converts the wheel to cursor keys). Do not "simplify" this back to a bubble listener or re-delegate local scrolling to xterm's viewport. E2E guard: the reload → tab-switch → wheel matrix in the #205 verification scripts.
|
||||
|
||||
|
||||
@@ -1213,6 +1213,9 @@
|
||||
// session, which is usually not the active one: a page key would move its
|
||||
// selector. Consumed, so xterm does not scroll the rows under it either.
|
||||
if (app.tabAlerts?.get(this.sessionId) === 'action') return true;
|
||||
// A Codex selection menu is not an alert, but PageUp/PageDown move its selection (see
|
||||
// CodemanTerminalInput.isCodexSelectionMenu), so it consumes the wheel the same way.
|
||||
if (app._codexMenuOpen?.({ terminal: this.terminal, sessionId: this.sessionId })) return true;
|
||||
if (ev.ctrlKey || Math.abs(ev.deltaX || 0) > Math.abs(ev.deltaY || 0)) return true;
|
||||
if (this._pageKeyGesture?.dir && this._pageKeyGesture.dir !== Math.sign(lines)) this._scrollBytes = '';
|
||||
const step = input.pageKeysForGesture(this._pageKeyGesture, ev, lines, this.terminal.rows, performance.now());
|
||||
|
||||
@@ -319,6 +319,41 @@
|
||||
}
|
||||
}
|
||||
|
||||
// A Codex selection menu on screen: the "Implement this plan?" prompt, the /model, /permissions and
|
||||
// /review pickers, an approval, a question or the trust prompt. Each draws its options as numbered rows
|
||||
// with the selected one marked `› N. ` (a question indents it two spaces, and its notes field reads
|
||||
// `› Add notes`) and a key-hint footer (`enter select · esc back`, `enter
|
||||
// continue · esc back`, `Press enter to confirm ...`). Codex uses PageUp and PageDown there to move
|
||||
// the SELECTION (measured on 0.164.0: PageDown from option 1 lands on option 3), so a wheel turned
|
||||
// into page keys would walk the cursor through the options, one notch onto "Yes, implement this plan".
|
||||
// Read off the live screen rows (the last `rows` rows of the active buffer), counting non-blank rows from
|
||||
// the bottom: the trust prompt is drawn at the TOP of an otherwise blank screen.
|
||||
const CODEX_MENU_OPTION_RE = /^ {0,2}› (?:\d+\. |Add notes)/;
|
||||
// A wrapped key hint continues on rows that start in lower case (`cancel`, `esc to interrupt`) or with a separator.
|
||||
const CODEX_MENU_HINT_WRAP_RE = /^ {2}[a-z←|]/;
|
||||
const CODEX_MENU_FOOTER_RE = /^ {1,4}(?:Press enter to confirm|enter (?:select|continue)|tab (?:to add|or esc to clear) notes)/;
|
||||
function isCodexSelectionMenu(terminal) {
|
||||
try {
|
||||
const buf = terminal.buffer.active;
|
||||
// The non-blank rows from the bottom of the screen up. A menu's key hints are the last thing drawn, and a
|
||||
// narrow pane wraps them over more rows that start in lower case: nothing else may sit under them, so
|
||||
// an answer that quotes the hints (above the composer, a tip and a status row) is not a menu.
|
||||
const rows = [];
|
||||
for (let y = buf.baseY + terminal.rows - 1; y >= buf.baseY; y--) {
|
||||
const text = buf.getLine(y)?.translateToString(true) ?? '';
|
||||
if (text.trim()) rows.push(text);
|
||||
}
|
||||
let footerAt = 0;
|
||||
while (footerAt < rows.length && !CODEX_MENU_FOOTER_RE.test(rows[footerAt])) {
|
||||
if (!CODEX_MENU_HINT_WRAP_RE.test(rows[footerAt])) return false;
|
||||
footerAt++;
|
||||
}
|
||||
return footerAt < rows.length && rows.slice(footerAt + 1).some((text) => CODEX_MENU_OPTION_RE.test(text));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Screen row of the cursor, for the local-echo prompt finders: xterm's cursorY is
|
||||
// baseY-relative, so a viewport parked above the bottom shifts it. Null when off screen.
|
||||
function cursorViewportRow(terminal) {
|
||||
@@ -404,6 +439,7 @@
|
||||
isComposerNavKey,
|
||||
classifyPredictInput,
|
||||
isCodexComposerRow,
|
||||
isCodexSelectionMenu,
|
||||
cursorViewportRow,
|
||||
CODEX_COMPOSER_ROW_RE,
|
||||
BRACKETED_PASTE_START,
|
||||
@@ -6061,8 +6097,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
* pinch), a mostly horizontal swipe (both deltas present, |deltaX| > |deltaY|;
|
||||
* the touch path locks its own axis before it gets here), and any gesture while
|
||||
* the session has an open dialog (tab alert 'action', set by a pending
|
||||
* permission_prompt or elicitation_dialog), so a page key never reaches its
|
||||
* selector.
|
||||
* permission_prompt or elicitation_dialog) or while a Codex selection menu is on
|
||||
* screen (the "Implement this plan?" prompt, a /model picker; see
|
||||
* isCodexSelectionMenu), so a page key never reaches its selector.
|
||||
*
|
||||
* @returns true when the gesture was consumed here (the caller must not also
|
||||
* scroll locally).
|
||||
@@ -6087,6 +6124,12 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._logScrollRouting('page-keys-dialog-open');
|
||||
return true;
|
||||
}
|
||||
// Codex's own selection menus (the "Implement this plan?" prompt among them) are not alerts, but PageUp
|
||||
// and PageDown move their selection, so the wheel is consumed there too.
|
||||
if (this._codexMenuOpen()) {
|
||||
this._logScrollRouting('page-keys-menu-open');
|
||||
return true;
|
||||
}
|
||||
// A hollow buffer whose PANE still holds tmux scrollback is unloaded, not
|
||||
// hollow: after a server restart a tab switch replays a byte tail that is
|
||||
// only the attach repaint (baseY 0), and paging from there moved an inline
|
||||
@@ -6122,6 +6165,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
return true;
|
||||
},
|
||||
|
||||
// Is a Codex selection menu showing in this pane (or the pane `target` names: a tile passes its own
|
||||
// terminal and session)? See isCodexSelectionMenu.
|
||||
_codexMenuOpen(target = {}) {
|
||||
const session = this.sessions?.get(target.sessionId || this.activeSessionId);
|
||||
if (session?.mode !== 'codex') return false;
|
||||
return window.CodemanTerminalInput.isCodexSelectionMenu(target.terminal || this.terminal);
|
||||
},
|
||||
|
||||
/**
|
||||
* One line in the console saying WHY a scroll gesture went where it went.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* Codex's selection menus (the "Implement this plan?" prompt, the /model, /permissions and /review pickers,
|
||||
* approvals, questions, the trust prompt) take PageUp and PageDown as "move the selection". Codeman turns
|
||||
* the wheel into those keys for a Codex pane that does not track the mouse (codex-cli 0.162 and 0.164 never
|
||||
* do), so a wheel notch walked the cursor through the options: one notch down landed on "No, stay in Plan
|
||||
* mode", one up on "Yes, implement this plan". The pane must consume the wheel there and send nothing.
|
||||
*
|
||||
* The screens are the live `tmux capture-pane` frames in test/fixtures/codex-dialogs/.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { STOCK_CLIS } from '../src/config/cli-registry/stock.js';
|
||||
|
||||
const PAGE_KEY_MODES = STOCK_CLIS.filter((e) => e.capabilities.transcriptPageKeys === true).map((e) => e.id);
|
||||
const publicDir = resolve(import.meta.dirname, '../src/web/public');
|
||||
const fixture = (name: string) => readFileSync(resolve(import.meta.dirname, 'fixtures/codex-dialogs', name), 'utf8');
|
||||
|
||||
/** A terminal whose screen shows `text`, padded to `rows` rows (what xterm holds for a hollow pane). */
|
||||
function terminalShowing(text: string, rows = 40) {
|
||||
const lines = text.replace(/\n+$/, '').split('\n');
|
||||
// A capture taller than the pane keeps its bottom rows (the menu), a shorter one sits at the top.
|
||||
const shown = lines.length > rows ? lines.slice(-rows) : lines;
|
||||
const screen = Array.from({ length: rows }, (_, i) => shown[i] ?? '');
|
||||
return {
|
||||
cols: 100,
|
||||
rows,
|
||||
modes: { mouseTrackingMode: 'none' },
|
||||
buffer: {
|
||||
active: {
|
||||
type: 'normal',
|
||||
baseY: 0,
|
||||
viewportY: 0,
|
||||
length: rows,
|
||||
getLine: (y: number) => (screen[y] === undefined ? undefined : { translateToString: () => screen[y] }),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function load() {
|
||||
const CodemanApp = function CodemanApp(this: any) {};
|
||||
const windowRef: Record<string, any> = { __codemanTranscriptPageKeys: PAGE_KEY_MODES };
|
||||
const context = vm.createContext({
|
||||
window: windowRef,
|
||||
CodemanApp,
|
||||
console: { warn: vi.fn(), log: vi.fn() },
|
||||
_crashDiag: { log: vi.fn() },
|
||||
performance: { now: () => 1_000 },
|
||||
requestAnimationFrame: () => 1,
|
||||
setTimeout: () => 1,
|
||||
clearTimeout: () => undefined,
|
||||
Blob: function Blob() {},
|
||||
URL: { createObjectURL: () => 'blob:x', revokeObjectURL: () => {} },
|
||||
Worker: function Worker(this: any) {
|
||||
this.postMessage = () => {};
|
||||
},
|
||||
MobileDetection: { isTouchDevice: () => true },
|
||||
DEC_SYNC_STRIP_RE: /\x1b\[\?2026[hl]/g,
|
||||
OSC52_STRIP_RE: /\x1b\]52;[^\x07\x1b]*(?:\x07|\x1b\\)/g,
|
||||
TERMINAL_CHUNK_SIZE: 32 * 1024,
|
||||
});
|
||||
vm.runInContext(readFileSync(resolve(publicDir, 'terminal-ui.js'), 'utf8'), context, { filename: 'terminal-ui.js' });
|
||||
return { app: new (CodemanApp as any)(), windowRef };
|
||||
}
|
||||
|
||||
/** Every dialog or menu a Codex pane can be sitting in, and the screens where PageUp must still page. */
|
||||
const MENUS = [
|
||||
'implement-plan.txt',
|
||||
'model-popup.txt',
|
||||
'permissions-popup.txt',
|
||||
'review-popup.txt',
|
||||
'exec-approval.txt',
|
||||
'exec-approval-w36.txt',
|
||||
'edit-approval.txt',
|
||||
'question.txt',
|
||||
'question-1of2.txt',
|
||||
'question-notes.txt',
|
||||
'trust-dialog.txt',
|
||||
'trust-dialog-back.txt',
|
||||
'trust-dialog-w40.txt',
|
||||
'exec-approval-w44.txt',
|
||||
'exec-approval-60x14.txt',
|
||||
'exec-approval-long-command.txt',
|
||||
'network-escalation-approval.txt',
|
||||
'question-option2-selected.txt',
|
||||
'question-2of2-submit-all.txt',
|
||||
'question-notes-typed.txt',
|
||||
'question-w36.txt', // the key hint one segment per row
|
||||
'question-w60.txt',
|
||||
];
|
||||
const NOT_MENUS = [
|
||||
'idle-start.txt',
|
||||
'composer-typed.txt',
|
||||
'working.txt',
|
||||
'after-approve.txt',
|
||||
'after-deny.txt',
|
||||
'after-question.txt',
|
||||
'slash-popup.txt',
|
||||
'transcript-quotes-dialog.txt',
|
||||
'composer-typed-dialog-text.txt',
|
||||
'composer-typed-dialog-text-w60.txt',
|
||||
];
|
||||
|
||||
describe('isCodexSelectionMenu on live captures', () => {
|
||||
const { windowRef } = load();
|
||||
const isMenu = (name: string) => windowRef.CodemanTerminalInput.isCodexSelectionMenu(terminalShowing(fixture(name)));
|
||||
|
||||
it.each(MENUS)('reads %s as a menu', (name) => {
|
||||
expect(isMenu(name), name).toBe(true);
|
||||
});
|
||||
|
||||
it.each(NOT_MENUS)('does not read %s as a menu', (name) => {
|
||||
expect(isMenu(name), name).toBe(false);
|
||||
});
|
||||
|
||||
it('still reads a narrow question whose option descriptions wrap over many rows', () => {
|
||||
// The selected option sat 16 rows up from the bottom at 36 columns; sentence-length descriptions on
|
||||
// a phone-width pane push it further, and an earlier row cap lost it (the menu was missed and the
|
||||
// wheel moved the selection again).
|
||||
const rows = fixture('question-w36.txt').split('\n');
|
||||
const at = rows.findIndex((row) => /^\s{0,2}› 1\./.test(row));
|
||||
expect(at).toBeGreaterThan(-1);
|
||||
rows.splice(at + 1, 0, ...Array.from({ length: 12 }, (_, i) => ` wrapped description row ${i + 1}`));
|
||||
const terminal = terminalShowing(rows.join('\n'), 60);
|
||||
expect(windowRef.CodemanTerminalInput.isCodexSelectionMenu(terminal)).toBe(true);
|
||||
});
|
||||
|
||||
it('is false for a terminal it cannot read', () => {
|
||||
expect(windowRef.CodemanTerminalInput.isCodexSelectionMenu(undefined)).toBe(false);
|
||||
expect(windowRef.CodemanTerminalInput.isCodexSelectionMenu({ rows: 10, buffer: { active: { baseY: 0 } } })).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the wheel over a Codex pane', () => {
|
||||
function codexPane(screen: string) {
|
||||
const { app } = load();
|
||||
const sent: string[] = [];
|
||||
app.activeSessionId = 'sess-1';
|
||||
app.sessions = new Map([['sess-1', { mode: 'codex', cliMouseTracking: false }]]);
|
||||
app._sendInputEphemeral = (_id: string, data: string) => sent.push(data);
|
||||
app.terminal = terminalShowing(screen);
|
||||
return { app, sent };
|
||||
}
|
||||
|
||||
it('sends no page key while the "Implement this plan?" menu is open, and consumes the wheel', () => {
|
||||
const { app, sent } = codexPane(fixture('implement-plan.txt'));
|
||||
for (const lines of [-30, 30, -30, 30]) expect(app._maybePageCliTranscript({ shiftKey: false }, lines)).toBe(true);
|
||||
app._flushWheelSgrQueue();
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('still pages the transcript from the composer', () => {
|
||||
const { app, sent } = codexPane(fixture('composer-typed.txt'));
|
||||
expect(app._maybePageCliTranscript({ shiftKey: false }, -30)).toBe(true);
|
||||
app._flushWheelSgrQueue();
|
||||
expect(sent).toEqual(['\x1b[5~']);
|
||||
});
|
||||
|
||||
it('only looks at Codex: another page-key CLI showing the same text is paged as before', () => {
|
||||
const { app, sent } = codexPane(fixture('implement-plan.txt'));
|
||||
app.sessions.set('sess-1', { mode: 'opencode' });
|
||||
app._maybePageCliTranscript({ shiftKey: false }, -30);
|
||||
app._flushWheelSgrQueue();
|
||||
expect(sent).toEqual(['\x1b[5~']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a tile asks the same question', () => {
|
||||
it('consumes the wheel for an open Codex menu in its own terminal and session', () => {
|
||||
const tile = readFileSync(resolve(publicDir, 'terminal-tile.js'), 'utf8');
|
||||
expect(tile).toContain('app._codexMenuOpen?.({ terminal: this.terminal, sessionId: this.sessionId })');
|
||||
const { app } = load();
|
||||
app.sessions = new Map([
|
||||
['active', { mode: 'claude' }],
|
||||
['tile', { mode: 'codex' }],
|
||||
]);
|
||||
app.terminal = terminalShowing(fixture('composer-typed.txt'));
|
||||
const tileTerminal = terminalShowing(fixture('implement-plan.txt'));
|
||||
// the tile's own terminal and session decide, not the active pane's
|
||||
expect(app._codexMenuOpen({ terminal: tileTerminal, sessionId: 'tile' })).toBe(true);
|
||||
expect(app._codexMenuOpen({ terminal: tileTerminal, sessionId: 'active' })).toBe(false);
|
||||
expect(app._codexMenuOpen()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -843,6 +843,54 @@ describe("the dialog check reads the TILE's session, never the active tab's", ()
|
||||
});
|
||||
});
|
||||
|
||||
describe("a Codex selection menu on the tile's own screen", () => {
|
||||
const MENU = [
|
||||
' Implement this plan?',
|
||||
'',
|
||||
'› 1. Yes, implement this plan Switch to Default and start coding',
|
||||
' 2. Yes, clear context and implement Start a fresh thread (current context: 2% used)',
|
||||
' 3. No, stay in Plan mode Continue planning with the model',
|
||||
'',
|
||||
' enter select · esc back',
|
||||
];
|
||||
/** Puts `rows` on the bottom of the tile's 24-row screen, the way xterm's buffer answers getLine. */
|
||||
function showOnScreen(term: { rows: number; buffer: { active: Record<string, unknown> } }, rows: string[]) {
|
||||
const screen = [...Array(term.rows - rows.length).fill(''), ...rows];
|
||||
term.buffer.active.getLine = (y: number) => ({ translateToString: () => screen[y] ?? '' });
|
||||
}
|
||||
|
||||
it('consumes the wheel without paging, and pages again once the menu is gone', async () => {
|
||||
const app = makeApp({ other: { mode: 'claude' }, 's-tile': { mode: 'codex' } }, 'other');
|
||||
const { ws, term, mount } = await connectTile(app, { mode: 'codex' });
|
||||
showOnScreen(term, MENU);
|
||||
|
||||
for (const lines of [-18, 18, -18]) {
|
||||
const ev = wheelLines(lines);
|
||||
mount.fire('wheel', ev);
|
||||
// Consumed (xterm does not scroll the stale rows under the menu either), and no key was sent.
|
||||
expect(ev.preventDefault).toHaveBeenCalled();
|
||||
}
|
||||
expect(flushed(ws)).toEqual([]);
|
||||
|
||||
// Menu closed: the composer is back on screen and the same wheel pages the transcript.
|
||||
showOnScreen(term, ['› Ask Codex to do anything', '', ' GPT-6-Astra medium · ~/cases/x', ' ? for shortcuts']);
|
||||
mount.fire('wheel', wheelLines(-18));
|
||||
expect(flushed(ws)).toEqual([{ t: 'i', d: PAGE_UP }]);
|
||||
});
|
||||
|
||||
it("asks about THIS tile's terminal, not the active tab's", async () => {
|
||||
const app = makeApp({ other: { mode: 'codex' }, 's-tile': { mode: 'codex' } }, 'other');
|
||||
(app as App & { terminal: unknown }).terminal = {
|
||||
rows: 24,
|
||||
buffer: { active: { getLine: () => ({ translateToString: () => '' }) } },
|
||||
};
|
||||
const { ws, term, mount } = await connectTile(app, { mode: 'codex' });
|
||||
showOnScreen(term, MENU);
|
||||
mount.fire('wheel', wheelLines(-18));
|
||||
expect(flushed(ws)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rows the tile pushed above the screen itself are not history', () => {
|
||||
it('pages after a one-screen capture taken at a taller size (the first load)', async () => {
|
||||
serveCapture(lines(40), 40); // the PTY was 40 rows when it was captured
|
||||
|
||||
Reference in new issue
Block a user