mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-30 16:39:33 +01:00
Merge #815: fix(web): manual Reload history action for the tmux repaint gap above live output (#814)
# Conflicts: # src/web/CLAUDE.md
This commit is contained in:
commit
4936e07ca2
18 files changed
+2618
-57
No files matched your search
@@ -0,0 +1,7 @@
|
||||
---
|
||||
'aicodeman': patch
|
||||
---
|
||||
|
||||
Fix missing terminal history above live output in agent sessions (seen with OMP) with a manual Reload history action in the existing history banner on desktop and mobile. The action preserves the text being read and output arriving during the download, and can be disabled per device in Settings > Terminal & Input > Scrolling & rendering. Ordinary scrolling only pulls history at the top.
|
||||
|
||||
While you are scrolled up, new output no longer moves the text you are reading once the terminal's scrollback is full. This applies to every session type, whether or not the Reload history setting is on.
|
||||
@@ -228,7 +228,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**Circuit breakers**: the Ralph breaker prevents respawn thrashing (`CLOSED` → `HALF_OPEN` → `OPEN`; reset via `/api/sessions/:id/ralph-circuit-breaker/reset`). **Distinct: the PTY-exit breaker** (`session-pty-exit-breaker.ts`) trips after repeated rapid PTY exits and blocks auto-restarts. ⚠️ It resets ONLY via an explicit `{clearBreaker:true}` body on `POST /api/sessions/:id/interactive`; the frontend's auto-reattach in `selectSession()` sends no body and must never clear it. → [architecture-invariants#circuit-breakers-ralph-and-pty-exit](docs/architecture-invariants.md#circuit-breakers-ralph-and-pty-exit)
|
||||
|
||||
**Full-scrollback replay**: `GET /api/sessions/:id/terminal?full=1` returns the whole tmux scrollback ALONE (`source='mux-full-history'`), superseding the byte buffer. First load of each non-shell TUI session requests it (`_fullHistoryLoaded`); Shell selection, drop recovery, clear and a tile's load use `SHELL_LOAD_QUERY` (constants.js), a bounded window of tmux's RENDERED history (`?full=1&tail=1MiB&alt=recording&lines=10000`), never the raw byte recording, whose full-screen repaints replayed at another pane height push copies of their top row into scrollback; the route reports a client `lines=` bound below the history ceiling that left lines in tmux as `truncationReason: 'tail'`, and `alt=recording` falls back to the visible frame over the tailed byte recording when the pane is in the alternate screen (a nested tmux in a remote or Docker case keeps no tmux history; vim/less take it too while open). A Shell scroll-to-top pulls a bounded `?full=1&tail=` window (a window no longer than the browser's buffer is skipped before the downgrade guard, so it never marks the session exhausted); the unbounded pull stays behind **Load full history**. A Shell split-pane Pane B has its own copy of the bounded pull against its own xterm (`TerminalTile._pullHistory`, terminal-tile.js); keep the two in step. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions) ⚠️ The capture ends with a RELATIVE cursor move back to the pane's caret (never `CUP`), so no line-deleting transform may run over it; those skips key on `isFullCapture`, never on `?full=1` alone. ⚠️ A re-pull must never shrink the buffer (`_replayWouldShrinkBuffer()`). ⚠️ `captureCols`/`captureRows` are absent when no frame was positioned: test `Number.isFinite`, never truthiness. ⚠️ A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery verifies itself: `_scheduleDroppedOutputRecovery` re-arms (bounded by `DROP_RECOVERY_MAX_ATTEMPTS`) while `_onSessionNeedsRefresh` reports no repaint, but never after a capture-fetch `'deadline'`. → [architecture-invariants#full-scrollback-replay](docs/architecture-invariants.md#full-scrollback-replay)
|
||||
**Full-scrollback replay**: `GET /api/sessions/:id/terminal?full=1` returns the whole tmux scrollback ALONE (`source='mux-full-history'`), superseding the byte buffer. First load of each non-shell TUI session requests it (`_fullHistoryLoaded`); Shell selection, drop recovery, clear and a tile's load use `SHELL_LOAD_QUERY` (constants.js), a bounded window of tmux's RENDERED history (`?full=1&tail=1MiB&alt=recording&lines=10000`), never the raw byte recording, whose full-screen repaints replayed at another pane height push copies of their top row into scrollback; the route reports a client `lines=` bound below the history ceiling that left lines in tmux as `truncationReason: 'tail'`, and `alt=recording` falls back to the visible frame over the tailed byte recording when the pane is in the alternate screen (a nested tmux in a remote or Docker case keeps no tmux history; vim/less take it too while open). A Shell scroll-to-top pulls a bounded `?full=1&tail=` window (a window no longer than the browser's buffer is skipped before the downgrade guard, so it never marks the session exhausted); the unbounded pull stays behind **Load full history**. A Shell split-pane Pane B has its own copy of the bounded pull against its own xterm (`TerminalTile._pullHistory`, terminal-tile.js); keep the two in step. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions) ⚠️ The capture ends with a RELATIVE cursor move back to the pane's caret (never `CUP`), so no line-deleting transform may run over it; those skips key on `isFullCapture`, never on `?full=1` alone. ⚠️ A re-pull must never shrink the buffer (`_replayWouldShrinkBuffer()`). ⚠️ `captureCols`/`captureRows` are absent when no frame was positioned: test `Number.isFinite`, never truthiness. ⚠️ A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery verifies itself: `_scheduleDroppedOutputRecovery` re-arms (bounded by `DROP_RECOVERY_MAX_ATTEMPTS`) while `_onSessionNeedsRefresh` reports no repaint, but never after a capture-fetch `'deadline'`. ⚠️ **Reload history** (#814, manual early repair; rules in the invariants paragraph "Repair while reading"): only a `mux-full-history` replay whose live-output generation is unchanged since before its fetch clears `_liveOutputSinceFullPull` and `_historyReloadDismissed`; a refused or non-mux answer to a manual reload retires the action until then; and the buffer load opens BEFORE the fetch, so download-time output queues behind the replay. → [architecture-invariants#full-scrollback-replay](docs/architecture-invariants.md#full-scrollback-replay)
|
||||
|
||||
**Terminal scrollback strip + wheel/touch forwarding**: codex/claude/gemini get the FULL strip (alt-screen, `3J`, mouse DECSETs); tmux-backed opencode, copilot and pi get the MIDDLE strip (alt-screen toggles + mouse DECSETs, `3J` kept); every other tmux-backed mode (shell/antigravity/grok/deepseek/omp) gets the NARROW strip (alt-screen toggles only). Table: `CliCapabilities.altScreen` JSDoc, pinned in test/claude-scrollback-strip.test.ts. ⚠️ Gated on `useMux`: direct-PTY sessions must keep the alt screen. Wheel and touch forward only with observed `cliMouseTracking`: **Claude ≥ 2.1.187, tracked Codex, tracked Copilot, or tracked Pi**. Which CLIs forward is the registry's `wheelForward`, published as `window.__codemanWheelForward` and never an id list in the gate, so a custom `clis.json` entry opts in with it plus `altScreen: 'strip-mux-and-mouse'` (`docs/cli-registry.md`). Codex 0.163.0 fullscreen was measured with `alternate_on=1`, `mouse_any_flag=1`: one SGR report moves one transcript row; see the fresh measurement in architecture-invariants. Inline/untracked Codex retains local history or the capability-gated paging fallback. Copilot has no version gate; a stale/false tracking flag falls back to PageUp/PageDown. Pi has no version gate either, and is fullscreen by default since 1.0.0: it enables tracking once at start, so the flag is what survives a tab switch or reload (xterm's own mode does not). ⚠️ Pi deliberately has no `transcriptPageKeys`: its `tuiMode: regular` binds those keys to the editor, so paging there moves a draft's caret. Touch alone has one more branch (`_shouldForwardTouchToApp`): in any mode, a drag also forwards as SGR wheel reports while xterm ITSELF tracks the mouse with SGR encoding (an app in the pane asked for it; a tracking mode other than `x10` and `coreMouseService.activeEncoding === 'SGR'`, so DEFAULT, X10 and SGR-pixel apps fail closed), because xterm encodes a wheel there but the touch listeners consume the drag. ⚠️ `getClaudeCliVersion()` must never cache a FAILED probe. ⚠️ Hand-report clicks only while the CLI has mouse tracking on: `_shouldReportMouseToCli()` gates all three report sites on `cliMouseTracking` (from `_recordStrippedMouseMode()`, session.ts), or a plain shell prints the reports as literal text. ⚠️ A `TerminalTile` (grid tile, split Pane B) forwards the wheel as SGR reports, pages it and reports clicks through these SAME gates with itself as the target (its terminal, its session, never `activeSessionId`), and scrolls Shift+wheel itself (xterm makes it a horizontal no-op); never copy the mode lists into terminal-tile.js. ⚠️ The hollow-buffer PageUp/PageDown fallback (`_maybePageCliTranscript`) stands down when the last capture reported tmux scrollback (`paneHistoryLines` > 0: a tail replayed after a server restart carries only the attach repaint), so the gesture scrolls locally and the scroll-to-top pull loads `full=1`; 0 and unknown keep paging. Read `_logScrollRouting()` before diagnosing a scroll report. → [architecture-invariants#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding](docs/architecture-invariants.md#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding)
|
||||
**Detached start + service install**: `codeman web -d` relaunches the same entry script `detached:true` (setsid); `nohup` is not what makes it survive. ⚠️ Both `-d` and `service install` must REFUSE when a server is already up on this data dir (pidfile + `/api/status` probe), or a second instance attaches to the first one's live sessions. ⚠️ Never report success not observed: poll `/api/status` until the child answers or dies. `--stop` must verify the pid still looks like Codeman (`ps -o command=`) before signalling. Unit/label names live only in `config/service-names.ts`. `service install` bakes the installing shell's PATH into the unit and never writes `CODEMAN_PASSWORD` into it. → [architecture-invariants#detached-start-and-service-install](docs/architecture-invariants.md#detached-start-and-service-install)
|
||||
|
||||
@@ -41,6 +41,7 @@ export const BROWSER_TEST_GLOBS = [
|
||||
'test/terminal-keycode229-recovery.browser.test.ts',
|
||||
'test/ios-native-input.browser.test.ts',
|
||||
'test/capture-load-window.browser.test.ts',
|
||||
'test/history-gap-repair.browser.test.ts',
|
||||
'test/capture-geometry-retry.browser.test.ts',
|
||||
'test/codex-predictive-echo.test.ts', // also needs a real codex binary
|
||||
'test/split-pane-terminal.browser.test.ts',
|
||||
|
||||
@@ -253,7 +253,9 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect`
|
||||
|
||||
### Full-scrollback replay
|
||||
|
||||
**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 0.3 s at 100k lines); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes may still re-pull `full=1` at the TOP, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; outpLine truncated
|
||||
**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marLine truncated
|
||||
|
||||
**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not Docker or adopted (their local pane hosts a nested tmux client in the alternate screen, so `?full=1` returns one screen the downgrade guard refuses; remote sessions stay eligible, since the route splices the remote scrollback in), not detached, not owned by tiles, with no pull or buffer load in flight, no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). The bar is a polite live region (`role="status"`), but only the truncation notice is announced: a reload-only bar sets `aria-live="off"` before it re-renders, since it comes back on nearly every scroll-up in a busy tab, and its button stays reachable with Tab. Its × is labelled for what the bar carries: "Dismiss history notice" with the notice, "Dismiss Reload history" without it. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrLine truncated
|
||||
|
||||
**The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`.
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ non-updatable. See [Running As A Service](Running-As-A-Service).
|
||||
| Input Field: Send on Enter | Off | With CJK Input on, typed text stays in the pinned field until Enter instead of streaming to the CLI, so on a phone you can scroll the terminal and edit an answer first. With a hardware keyboard, Shift+Enter adds a line (a phone's on-screen keyboard has none). Esc clears, autocorrect is on. |
|
||||
| Extended Keyboard Bar | Per device | Which accessory bar phones get. Shell sessions override it while they are active. |
|
||||
| Wheel Scrolls Local History | Off | Keeps the wheel on the local buffer instead of forwarding it to the CLI. Fullscreen pi leaves that buffer empty and has no paging fallback, so with this on the wheel does nothing there. |
|
||||
| History Reload Button | On (per device) | Offers **Reload history** in the history banner while you are scrolled up in a non-shell session that has had live output since its last full capture; a tap re-pulls the full tmux history and keeps your reading position. |
|
||||
| Auto Copy Selection | Off | Copies highlighted terminal text to the clipboard the moment you finish selecting it. Ctrl+C still copies on demand. |
|
||||
| Trim The Pane Margin On Copy | On | Takes the left margin a full-screen agent CLI paints down its own edge off a copy, so the text pastes flush. Each CLI declares its own width, and the strip never exceeds the indent every selected line shares, so nesting is kept. Claude Code and Codex declare a margin; a shell does not. |
|
||||
| Normal / Bold font weight | xterm defaults | Per device, each slot from 100 to 900. The bundled JetBrains Mono renders every step, so a lighter normal weight makes Claude's bold headings stand out. Applies live to the terminal, both echo overlays and open team panes. |
|
||||
|
||||
@@ -243,10 +243,14 @@ Worth knowing:
|
||||
reloads only the current screen, which keeps tab switches fast.
|
||||
Shell sessions open from a bounded recent tail so a large transcript cannot stall tab
|
||||
switching. Scrolling to the top of a Shell pane pulls the most recent 1 MiB of its tmux
|
||||
history; press **Load full history** to pull the rest explicitly. That notice only
|
||||
history; press **Load full history** to pull the rest explicitly. That truncation notice only
|
||||
appears once you scroll to the top, leaves when you scroll back down, and stays away
|
||||
for that tab once you close it. Sessions whose CLI keeps its own history (fullscreen
|
||||
Claude) never show it, since there is nothing more to load. Automatic output
|
||||
Claude) never show it, since there is nothing more to load. The same bar can also offer
|
||||
**Reload history** while scrolled up in an agent session after new output (toggle:
|
||||
Settings → Terminal & Input → History Reload Button). When a reload finds nothing more
|
||||
than the browser already shows, such as fullscreen Claude whose pane keeps no tmux
|
||||
history, the action is withdrawn until the next full capture. Automatic output
|
||||
recovery stays within the bounded browser buffer.
|
||||
- **Wheel and touch scrolling** are forwarded into Claude's own transcript when a recent
|
||||
Claude runs fullscreen (`CLAUDE_CODE_NO_FLICKER=1`, or `"tui": "fullscreen"` in
|
||||
|
||||
+1
-1
@@ -60,7 +60,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**Where a dialog hands the keyboard back to** (`FocusTrap.focusToReturn()`, keyboard-accessory.js): a dialog that saves focus on open asks this, never `document.activeElement`. By the time a dialog opens, the mouse press that opened it has already moved focus (onto the pressed control in Chromium and Firefox, onto `<body>` in WebKit on macOS, where a button takes no focus from the mouse), and restoring that left the keyboard out of the terminal until it was clicked. The answer is the typing field (textarea, text-like input, editable region) that had focus at `pointerdown`, whenever focus now sits on the pressed control or on `<body>`. ⚠️ `pointerdown`, never `mousedown` or `click`: moving focus is `mousedown`'s default action, so only the earlier event still sees what had the keyboard. ⚠️ One press, from a typing field, by mouse: the field of an earlier press is not carried over (it can be behind a dialog opened since), a press that began on a button (a dialog opened inside a dialog) still returns to the pressed control, any key but a held modifier forgets the press (a keyboard user gets the control back), and a finger or pen records nothing (a focused field there means the on-screen keyboard). The one press that inherits a field is a press on an item inside `[role="menu"]`, from the press that opened the menu (a tile's menu button, then "Session options"); a menu that hands focus back to its trigger before running the item is not covered. ⚠️ Asking spends the press, so nothing pressed inside the opening dialog can hand the keyboard to a field behind it; call it once, when the dialog opens. Callers: `FocusTrap.activate()` (App Settings, Session Options, Help, Kill All, the phone composer) and `_rememberOverlayFocus()` (command palette, Session Manager); the local model window places its own focus. A dialog that never handed focus back (most of the small confirm dialogs) is not changed by this. Tests: `test/dialog-focus-return.test.ts`, `test/dialog-focus-return.browser.test.ts` (real Chromium, not in the gate).
|
||||
|
||||
**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, or `extendedKeyboardBar`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema.
|
||||
**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, `extendedKeyboardBar`, or `historyReloadAction`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema.
|
||||
|
||||
**Settings surface** (`#appSettingsModal` + `#sessionOptionsModal` + `#createCaseModal`): one `set-*` language shared through a single `:is(...)` id scope in styles.css. App Settings' rail is a table of contents over ONE scrolling document (`switchSettingsTab` scrolls); Session Options and Add Case really switch (`switchOptionsTab` / `switchCaseModalTab`), and their larger per-modal size blocks are the design, not drift. ⚠️ **The load/save contract is `getElementById` by id**: renaming or dropping a control id silently stops it loading or saving. ⚠️ The Session Options "Session" entry still keys off `context` (label-only rename). ⚠️ Add Case keeps its legacy `.form-row` markup via an adapter; every `<details>` there needs `.set-adv-chev` plus both marker suppressions. ⚠️ Model cards and the effort segment are views over hidden `<select>`s, which stay the source of truth. ⚠️ `.modal-tabs*` classes are retired; `admin-ui.js` needs `.set-rail-items` + `.set-doc` to survive any restructure. Guard: `test/app-settings-structure.test.ts`. → [architecture-invariants#settings-surface-app-settings-session-options-add-case](../../docs/architecture-invariants.md#settings-surface-app-settings-session-options-add-case)
|
||||
|
||||
|
||||
+258
-33
@@ -801,9 +801,13 @@ class CodemanApp {
|
||||
// the small `full=1` capture instead of the 1 MiB byte tail: see
|
||||
// _notePaneHistory and selectSession.
|
||||
this._paneHistoryLines = new Map(); // Map<sessionId, number>
|
||||
// Cooldown per session for the scroll-to-top "load more history" re-pull.
|
||||
// Per-session cooldown for top-of-buffer pulls; manual actions bypass it.
|
||||
this._fullHistoryRepullAt = new Map(); // Map<sessionId, timestamp>
|
||||
this._fullHistoryRepullInFlight = false;
|
||||
this._liveOutputSinceFullPull = new Set(); // Set<sessionId>
|
||||
this._historyReloadDismissed = new Set(); // Until the next successful full mux replay
|
||||
this._liveOutputGen = new Map(); // Map<sessionId, number>
|
||||
this._earlyReplayTravel = null; // { sessionId, moves: number[] } during a content-anchored replay
|
||||
// Sessions whose last re-pull came back THINNER than the live buffer (a
|
||||
// repaint-mode CLI pane, where tmux keeps no history of its own). The pull is
|
||||
// refused for those and retried far more slowly — see _maybeRefetchFullHistory.
|
||||
@@ -2596,13 +2600,41 @@ class CodemanApp {
|
||||
* @param {number} [queuedBytes] - render-queue bytes at the drop, for the crash trail
|
||||
*/
|
||||
_scheduleDroppedOutputRecovery(sessionId, attempt = 0, queuedBytes) {
|
||||
if (!sessionId || this._clientDropRecoveryTimer) return;
|
||||
if (!sessionId) return;
|
||||
// Nothing of the main terminal's to recover while the tile grid owns it.
|
||||
if (this._tilesOwnTerminal?.()) return;
|
||||
// A slow capture owns the live-output gate. Keep the recovery owed until
|
||||
// it releases instead of spending every retry against the same open load.
|
||||
if (this._isLoadingBuffer) {
|
||||
if (sessionId === this.activeSessionId) {
|
||||
if (this._pendingDroppedOutputRecovery?.sessionId !== sessionId && Number.isFinite(queuedBytes)) {
|
||||
_crashDiag.log(`TERMINAL DROP: ${(queuedBytes / 1024).toFixed(0)}KB queued (recovery deferred)`);
|
||||
}
|
||||
const pending = this._pendingDroppedOutputRecovery;
|
||||
this._pendingDroppedOutputRecovery = {
|
||||
sessionId,
|
||||
attempt: pending?.sessionId === sessionId ? Math.max(pending.attempt, attempt) : attempt,
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this._clientDropRecoveryTimer) return;
|
||||
// Behind the debounce guard: one line per window, not per dropped frame.
|
||||
if (Number.isFinite(queuedBytes)) _crashDiag.log(`TERMINAL DROP: ${(queuedBytes / 1024).toFixed(0)}KB queued`);
|
||||
this._clientDropRecoveryTimer = setTimeout(async () => {
|
||||
this._clientDropRecoveryTimer = null;
|
||||
// A load may have opened after this timer was armed. Defer without
|
||||
// advancing the attempt; _finishBufferLoad resumes only the active tab.
|
||||
if (this._isLoadingBuffer) {
|
||||
if (sessionId === this.activeSessionId) {
|
||||
const pending = this._pendingDroppedOutputRecovery;
|
||||
this._pendingDroppedOutputRecovery = {
|
||||
sessionId,
|
||||
attempt: pending?.sessionId === sessionId ? Math.max(pending.attempt, attempt) : attempt,
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
let repainted = false;
|
||||
let timedOut = false;
|
||||
try {
|
||||
@@ -3465,6 +3497,9 @@ class CodemanApp {
|
||||
if (this._terminalRefreshOwner?.sessionId === sessionId) return false;
|
||||
const refreshOwner = { sessionId };
|
||||
this._terminalRefreshOwner = refreshOwner;
|
||||
// Reload history stands aside for the length of this refresh (see
|
||||
// _historyReloadActionEligible); take it off an already-painted bar now.
|
||||
this._syncHistoryReloadAction?.();
|
||||
try {
|
||||
// A shell can retain a multi-megabyte/100k-line tmux history. Automatic
|
||||
// recovery stays bounded just like normal shell selection (tmux's rendered
|
||||
@@ -3473,6 +3508,8 @@ class CodemanApp {
|
||||
// TUI modes still recover the whole picture, with the downgrade guard for
|
||||
// repaint-mode panes whose tmux capture can be smaller than xterm's buffer.
|
||||
const useFullHistory = this.sessions.get(sessionId)?.mode !== 'shell';
|
||||
// Keep live output received during the capture marked for another full-history pull.
|
||||
const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0;
|
||||
let capture = await this._fetchTerminalCapture(
|
||||
useFullHistory
|
||||
? `/api/sessions/${sessionId}/terminal?full=1`
|
||||
@@ -3481,7 +3518,13 @@ class CodemanApp {
|
||||
);
|
||||
let headersReceivedAt = capture.headersAt;
|
||||
let data = capture.json?.data ?? {};
|
||||
// The full capture would shrink the buffer: tmux holds less than the browser,
|
||||
// the signal `_maybeRefetchFullHistory` retires Reload history on. Record it
|
||||
// and apply it past the ownership guard below, so the next tap does not run
|
||||
// another forced full capture only to be refused.
|
||||
let refusedFullCapture = false;
|
||||
if (useFullHistory && data.terminalBuffer && this._replayWouldShrinkBuffer(data.terminalBuffer)) {
|
||||
refusedFullCapture = true;
|
||||
capture = await this._fetchTerminalCapture(`/api/sessions/${sessionId}/terminal?tail=${TERMINAL_TAIL_SIZE}`);
|
||||
headersReceivedAt = capture.headersAt;
|
||||
data = capture.json?.data ?? {};
|
||||
@@ -3495,6 +3538,10 @@ class CodemanApp {
|
||||
// pane), and an error envelope is not a capture at all.
|
||||
if (this.activeSessionId !== sessionId || this._terminalRefreshOwner !== refreshOwner) return false;
|
||||
if (capture.json?.success !== false) this._notePaneHistory?.(sessionId, data);
|
||||
if (refusedFullCapture) {
|
||||
(this._historyReloadDismissed ||= new Set()).add(sessionId);
|
||||
this._syncHistoryReloadAction?.();
|
||||
}
|
||||
if (data.terminalBuffer) {
|
||||
// This refresh is SERVER-triggered, so a user quietly reading scrollback
|
||||
// did not ask for it and must not be dragged to the bottom by it (#259).
|
||||
@@ -3507,12 +3554,23 @@ class CodemanApp {
|
||||
// after them and fuse into the buffer written below. See
|
||||
// _resetTerminalForReplay.
|
||||
this._resetTerminalForReplay();
|
||||
await this.chunkedTerminalWrite(
|
||||
const { completed } = await this.chunkedTerminalWrite(
|
||||
data.terminalBuffer,
|
||||
TERMINAL_CHUNK_SIZE,
|
||||
undefined,
|
||||
this._bufferLoadFinishOpts(data, headersReceivedAt)
|
||||
);
|
||||
if (
|
||||
completed &&
|
||||
this.activeSessionId === sessionId &&
|
||||
this._terminalRefreshOwner === refreshOwner &&
|
||||
data.source === 'mux-full-history' &&
|
||||
(this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen
|
||||
) {
|
||||
this._liveOutputSinceFullPull?.delete(sessionId);
|
||||
this._historyReloadDismissed?.delete(sessionId);
|
||||
this._syncHistoryReloadAction?.();
|
||||
}
|
||||
// A tail fetch can be partial, and the banner would otherwise keep
|
||||
// describing the pre-refresh buffer (#258).
|
||||
this._setHistoryTruncation(sessionId, data);
|
||||
@@ -3549,7 +3607,11 @@ class CodemanApp {
|
||||
console.error('needsRefresh reload failed:', err);
|
||||
return err?.name === 'AbortError' ? 'deadline' : false;
|
||||
} finally {
|
||||
if (this._terminalRefreshOwner === refreshOwner) this._terminalRefreshOwner = null;
|
||||
if (this._terminalRefreshOwner === refreshOwner) {
|
||||
this._terminalRefreshOwner = null;
|
||||
// Reload history stands aside while this refresh fetches; offer it again.
|
||||
this._syncHistoryReloadAction?.();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5039,6 +5101,9 @@ class CodemanApp {
|
||||
// Clear pending terminal writes
|
||||
this._clearTimer('syncWaitTimeout');
|
||||
this._clearTimer('_clientDropRecoveryTimer');
|
||||
// A recovery deferred behind a load would otherwise resume once the next
|
||||
// load (the reconnect's own refresh) finishes, and run a second full capture.
|
||||
this._pendingDroppedOutputRecovery = null;
|
||||
this.pendingWrites = [];
|
||||
this.writeFrameScheduled = false;
|
||||
// Release the one-chunk-in-flight gate with the rest of the write queue.
|
||||
@@ -6743,6 +6808,7 @@ class CodemanApp {
|
||||
if (state && state.generation !== selectGen) return;
|
||||
this.terminalLoadStates.delete(sessionId);
|
||||
this._updateTerminalLoadTab(sessionId);
|
||||
if (state) this._syncHistoryReloadAction?.();
|
||||
}
|
||||
|
||||
_updateTerminalLoadTab(sessionId) {
|
||||
@@ -9533,6 +9599,7 @@ class CodemanApp {
|
||||
this._tabCompletionBaseText = null;
|
||||
this._clearTimer('_tabCompletionFallback');
|
||||
this._clearTimer('_clientDropRecoveryTimer');
|
||||
this._pendingDroppedOutputRecovery = null;
|
||||
this._terminalRefreshOwner = null;
|
||||
|
||||
// Clean up pending terminal writes to prevent old session data from appearing in new session
|
||||
@@ -9662,8 +9729,8 @@ class CodemanApp {
|
||||
}
|
||||
|
||||
/**
|
||||
* "Load more history": re-pull the whole tmux scrollback when the user scrolls up
|
||||
* while already at the top of what the browser has.
|
||||
* Re-pull tmux history automatically at the top, or explicitly from the
|
||||
* history banner's Load full history / Reload history actions.
|
||||
*
|
||||
* xterm's buffer is only ever a WINDOW onto tmux's real history, and two things
|
||||
* shrink it. tmux repaints the pane rectangle instead of emitting linefeeds
|
||||
@@ -9674,9 +9741,11 @@ class CodemanApp {
|
||||
* everything (history-limit 100k by default), so the fix is to go ask for it with
|
||||
* the same `?full=1` capture a page reload uses (issue #205).
|
||||
*
|
||||
* On demand rather than automatic because that capture is unbounded-ish work: at
|
||||
* the default history limit it can be megabytes, which is fine to pay when the
|
||||
* user is explicitly reaching for history and not fine on every tab switch.
|
||||
* Automatic pulls are top-only and cooldown/latch guarded: a synchronous
|
||||
* capture can cost about 1 s at 100k lines (1,068 ms median for 12.1 MB of
|
||||
* 120-character lines, `capture-pane -p -e -J -S -100000`) and blocks the server event loop.
|
||||
* The manual Reload history action uses a content anchor to hold the reader's
|
||||
* place even when new history fills a gap below them.
|
||||
*
|
||||
* NEVER a downgrade: for a repaint-mode CLI pane tmux keeps no history of its
|
||||
* own, so the capture can be THINNER than what xterm already holds and the
|
||||
@@ -9685,9 +9754,13 @@ class CodemanApp {
|
||||
* gets a much longer cooldown so a hollow pane stops re-fetching megabytes on
|
||||
* every scroll-up (issue #205, round 2).
|
||||
*/
|
||||
async _maybeRefetchFullHistory({ force = false } = {}) {
|
||||
async _maybeRefetchFullHistory({ force = false, anchor = 'top' } = {}) {
|
||||
const sessionId = this.activeSessionId;
|
||||
if (!sessionId || this._fullHistoryRepullInFlight || this._isLoadingBuffer) return;
|
||||
// A drop-recovery refresh owns this session until its replay ends: a second
|
||||
// capture would run back to back with it, and its load would replace this
|
||||
// pull's queue, losing the output that arrived during the download.
|
||||
if (this._terminalRefreshOwner?.sessionId === sessionId) return;
|
||||
if (this.detachedSessions?.has(sessionId)) return;
|
||||
// The parked main terminal has no history to pull while tiles own the screen.
|
||||
if (this._tilesOwnTerminal?.()) return;
|
||||
@@ -9719,11 +9792,16 @@ class CodemanApp {
|
||||
if (!force && now - (this._fullHistoryRepullAt.get(sessionId) || 0) < cooldown) return;
|
||||
this._fullHistoryRepullAt.set(sessionId, now);
|
||||
this._fullHistoryRepullInFlight = true;
|
||||
const loadOwner = this._beginBufferLoad();
|
||||
let replayed = false;
|
||||
// The session-id check below cannot see a tab switch that came BACK during
|
||||
// the fetch (A -> B -> A): the id matches again while `selectSession` is
|
||||
// replaying its own capture, and the reset below would land in the middle
|
||||
// of that write. The select generation moves on every switch, so it can.
|
||||
const selectGen = this._selectGeneration;
|
||||
// Queued output replayed after this load may mark the session again. Never
|
||||
// clear that newer generation along with the capture's original mark.
|
||||
const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0;
|
||||
try {
|
||||
const requestStartedAt = performance.now();
|
||||
const capture = await this._fetchTerminalCapture(
|
||||
@@ -9742,6 +9820,22 @@ class CodemanApp {
|
||||
// recording its empty data would forget the count and hand the next
|
||||
// gesture back to the paging fallback, the bug this pull exists to avoid.
|
||||
if (selectGen === this._selectGeneration && capture.json?.success !== false) this._notePaneHistory?.(sessionId, payload);
|
||||
// A manual reload answered by anything but a full mux capture (an empty
|
||||
// response, or the byte-history fallback the route returns when the pane
|
||||
// capture is blank or failed) cannot fill the gap, and only a mux replay
|
||||
// clears the mark: offering it again would repeat the forced capture on
|
||||
// every tap. Retire it until the next `mux-full-history` replay. Only for
|
||||
// the request still current: a slow answer from before an A -> B -> A
|
||||
// switch must not retire the action a newer capture of A already cleared.
|
||||
if (
|
||||
anchor === 'content' &&
|
||||
this.activeSessionId === sessionId &&
|
||||
selectGen === this._selectGeneration &&
|
||||
capture.json?.success !== false &&
|
||||
payload.source !== 'mux-full-history'
|
||||
) {
|
||||
(this._historyReloadDismissed ||= new Set()).add(sessionId);
|
||||
}
|
||||
const buffer = payload.terminalBuffer;
|
||||
const timing = {
|
||||
trigger: force ? 'full-history-button' : 'full-history-scroll',
|
||||
@@ -9802,6 +9896,7 @@ class CodemanApp {
|
||||
timing.totalMs = performance.now() - requestStartedAt;
|
||||
this._recordTerminalLoadTiming(timing);
|
||||
(this._fullHistoryRepullUseless ||= new Set()).add(sessionId);
|
||||
(this._historyReloadDismissed ||= new Set()).add(sessionId);
|
||||
this._logScrollRouting?.('repull-refused-downgrade');
|
||||
// The browser already holds more than tmux can give back, so there is
|
||||
// nothing further to offer and the indicator must stop promising it.
|
||||
@@ -9819,6 +9914,9 @@ class CodemanApp {
|
||||
this._fullHistoryRepullUseless?.delete(sessionId);
|
||||
const rowsBefore = this.terminal.buffer.active.length;
|
||||
const replayStartedAt = performance.now();
|
||||
const viewportAnchor = anchor === 'content' ? this._captureViewportAnchor() : null;
|
||||
// Ordered, not summed: each move clamps at the buffer edge as it would live.
|
||||
if (anchor === 'content') this._earlyReplayTravel = { sessionId, moves: [] };
|
||||
this._resetTerminalForReplay();
|
||||
const {
|
||||
parsedAt,
|
||||
@@ -9827,11 +9925,17 @@ class CodemanApp {
|
||||
} = await this.chunkedTerminalWrite(
|
||||
buffer,
|
||||
TERMINAL_CHUNK_SIZE,
|
||||
sessionId,
|
||||
loadOwner,
|
||||
this._bufferLoadFinishOpts(payload, headersReceivedAt)
|
||||
);
|
||||
replayed = true; // chunkedTerminalWrite finished this load with the capture cutoff.
|
||||
timing.resetAndParseMs = parsedAt - replayStartedAt;
|
||||
if (!completed || this.activeSessionId !== sessionId || selectGen !== this._selectGeneration) return;
|
||||
if (payload.source === 'mux-full-history' && (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) {
|
||||
this._liveOutputSinceFullPull?.delete(sessionId);
|
||||
this._historyReloadDismissed?.delete(sessionId);
|
||||
this._syncHistoryReloadAction?.();
|
||||
}
|
||||
// Keep shell tab restores bounded too. A user-triggered full-history pull
|
||||
// may be tens of MB; caching it would replay that whole payload again on
|
||||
// the next tab switch before the normal 1MB tail fetch replaces it.
|
||||
@@ -9844,9 +9948,26 @@ class CodemanApp {
|
||||
// UPWARD, so what used to be row 0 (what they were looking at) is now `delta`
|
||||
// rows down; scrolling there reveals the recovered history above it instead
|
||||
// of teleporting them to the bottom the way a normal buffer load does.
|
||||
const delta = parsedBufferLength - rowsBefore;
|
||||
if (delta > 0) this.terminal.scrollToLine(delta);
|
||||
else this.terminal.scrollToTop();
|
||||
if (anchor === 'content') {
|
||||
const baseY = this.terminal.buffer.active.baseY;
|
||||
const clamp = (row) => Math.max(0, Math.min(baseY, row));
|
||||
let row = this._restoreViewportAnchor(viewportAnchor);
|
||||
// Replay travel bypassed the live scroll handler's notice update, so
|
||||
// decide it per move as that handler would: an upward move that reaches
|
||||
// row 0 reveals the notice, a downward move back at live output retires it.
|
||||
let reveal = null;
|
||||
for (const move of this._earlyReplayTravel.moves) {
|
||||
row = clamp(row + move);
|
||||
if (move < 0 && row === 0) reveal = true;
|
||||
else if (move > 0 && row >= baseY - 2) reveal = false;
|
||||
}
|
||||
this.terminal.scrollToLine(row);
|
||||
if (reveal !== null) this._setHistoryNoticeRevealed?.(reveal ? sessionId : null);
|
||||
} else {
|
||||
const delta = parsedBufferLength - rowsBefore;
|
||||
if (delta > 0) this.terminal.scrollToLine(delta);
|
||||
else this.terminal.scrollToTop();
|
||||
}
|
||||
// The load's own replay sampled the sticky-scroll baseline while the
|
||||
// terminal sat at the bottom of a just-rewritten buffer, so the next
|
||||
// flush would scroll back down and undo the restore above. This path is
|
||||
@@ -9862,7 +9983,10 @@ class CodemanApp {
|
||||
} catch {
|
||||
// Transient (offline, 5xx) — the next scroll-up past the cooldown retries.
|
||||
} finally {
|
||||
if (!replayed) this._finishBufferLoad(loadOwner, { flushQueued: true, since: 0 });
|
||||
if (anchor === 'content') this._earlyReplayTravel = null;
|
||||
this._fullHistoryRepullInFlight = false;
|
||||
this._syncHistoryReloadAction?.();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9938,6 +10062,44 @@ class CodemanApp {
|
||||
this._renderHistoryTruncationBanner();
|
||||
}
|
||||
|
||||
/** Whether the active session can offer a manual, content-anchored repair. */
|
||||
_historyReloadActionEligible() {
|
||||
const sessionId = this.activeSessionId;
|
||||
const session = this.sessions.get(sessionId);
|
||||
// Cheap state checks first: the terminal is read only for a marked session.
|
||||
// `_paneHistoryLines` is deliberately not consulted: it is recorded at the last
|
||||
// load, so a session first opened empty keeps 0 after the very burst that
|
||||
// opens the gap (#814). A pane that really holds no history (fullscreen
|
||||
// Claude) captures one screen, `_replayWouldShrinkBuffer` refuses it, and the
|
||||
// refusal dismisses the action until the next `mux-full-history` replay.
|
||||
// Docker and adopted sessions are left out: their local pane hosts a nested
|
||||
// tmux client in the alternate screen, so `?full=1` returns one screen that
|
||||
// the downgrade guard always refuses (the exclusions `paneKeepsNoHistory`
|
||||
// uses in selectSession). Remote sessions stay eligible, since the route
|
||||
// splices the remote scrollback into their capture.
|
||||
return !!(this.loadAppSettingsFromStorage?.()?.historyReloadAction !== false &&
|
||||
session && session.mode !== 'shell' && !session.docker && !session.adopt &&
|
||||
this._liveOutputSinceFullPull?.has(sessionId) &&
|
||||
!this._isLoadingBuffer &&
|
||||
!this.terminalLoadStates?.has(sessionId) && // Tab switches set this before the buffer load opens.
|
||||
this._terminalRefreshOwner?.sessionId !== sessionId && // A drop-recovery refresh is fetching.
|
||||
!this._fullHistoryRepullInFlight && !this.detachedSessions?.has(sessionId) &&
|
||||
!this._historyReloadDismissed?.has(sessionId) && !this._tilesOwnTerminal?.() &&
|
||||
!this.isTerminalAtBottom());
|
||||
}
|
||||
|
||||
/** Only eligibility/session/loading transitions may rebuild the banner. */
|
||||
_syncHistoryReloadAction() {
|
||||
const sessionId = this.activeSessionId;
|
||||
const eligible = this._historyReloadActionEligible();
|
||||
const loading = !!sessionId && this._historyReloadActionLoadingFor === sessionId &&
|
||||
!this._historyReloadDismissed?.has(sessionId);
|
||||
const last = this._historyReloadActionState;
|
||||
if (last && last.sessionId === sessionId && last.eligible === eligible && last.loading === loading) return;
|
||||
this._historyReloadActionState = { sessionId, eligible, loading };
|
||||
this._renderHistoryTruncationBanner();
|
||||
}
|
||||
|
||||
/**
|
||||
* Paint the partial-history banner for the active session.
|
||||
*
|
||||
@@ -9945,12 +10107,12 @@ class CodemanApp {
|
||||
* is gone forever" are not the same message and the old single boolean could
|
||||
* not tell them apart:
|
||||
* - recoverable → offer to load the rest
|
||||
* - exhausted → say so plainly, offer nothing
|
||||
* - exhausted → say so plainly
|
||||
* - at the limit → the full capture ITSELF hit the byte ceiling
|
||||
*
|
||||
* Shown only while revealed (`_setHistoryNoticeRevealed`: the user scrolled
|
||||
* to the top of this tab's buffer) and never again for a session whose notice
|
||||
* the user dismissed on this page.
|
||||
* Notices wait for a scroll to the top and respect their page-long dismissal.
|
||||
* Independently, eligible marked sessions offer Reload history while reading;
|
||||
* the same bar carries it without duplicating a Load full history control.
|
||||
*/
|
||||
_renderHistoryTruncationBanner() {
|
||||
const bar = document.getElementById('historyTruncationBar');
|
||||
@@ -9958,47 +10120,96 @@ class CodemanApp {
|
||||
const sessionId = this.activeSessionId;
|
||||
const state = sessionId ? this._historyTruncation?.get(sessionId) : null;
|
||||
const notice = computeHistoryTruncationNotice(state || {});
|
||||
if (
|
||||
!notice.visible ||
|
||||
this._historyNoticeRevealedFor !== sessionId ||
|
||||
this._historyNoticeDismissed?.has(sessionId)
|
||||
) {
|
||||
const showNotice = notice.visible && this._historyNoticeRevealedFor === sessionId &&
|
||||
!this._historyNoticeDismissed?.has(sessionId);
|
||||
const eligible = this._historyReloadActionEligible?.() ?? false;
|
||||
const loading = !!sessionId && this._historyReloadActionLoadingFor === sessionId &&
|
||||
!this._historyReloadDismissed?.has(sessionId);
|
||||
this._historyReloadActionState = { sessionId, eligible, loading };
|
||||
if (!showNotice && !eligible && !loading) {
|
||||
bar.hidden = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// `#historyTruncationBar` is a polite live region. Only the truncation
|
||||
// notice is news worth announcing; a reload-only bar re-renders on every
|
||||
// eligible scroll-up in a busy tab, so it stays silent and is reached by Tab.
|
||||
// Set before the rewrite below, so the new content is judged by it.
|
||||
bar.setAttribute('aria-live', showNotice ? 'polite' : 'off');
|
||||
bar.textContent = '';
|
||||
const label = document.createElement('span');
|
||||
label.className = 'history-trunc-text';
|
||||
label.textContent = notice.message;
|
||||
label.textContent = showNotice ? notice.message : 'Recent output may be missing from this view.';
|
||||
bar.appendChild(label);
|
||||
|
||||
if (notice.canLoadMore) {
|
||||
if (showNotice && notice.canLoadMore) {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'history-trunc-load';
|
||||
btn.textContent = 'Load full history';
|
||||
// A content-anchored pull from here stands in for Reload history, so it
|
||||
// shares Reload's loading state: the pull flips Reload eligibility, and the
|
||||
// re-render that follows must not bring the button back enabled mid-pull.
|
||||
btn.disabled = loading;
|
||||
btn.textContent = loading ? 'Loading…' : 'Load full history';
|
||||
btn.onclick = () => {
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Loading…';
|
||||
// Forced: the cooldown exists to throttle scroll gestures, not choices.
|
||||
this._maybeRefetchFullHistory({ force: true }).finally(() => {
|
||||
// When Reload history is eligible, this button is shown in its place
|
||||
// (one load control per bar), so it must keep the reader's line the same
|
||||
// way. Checked at click time, not render time: the bar only re-renders on
|
||||
// eligibility transitions, and the reader may have scrolled since.
|
||||
const anchor = this._historyReloadActionEligible() ? 'content' : 'top';
|
||||
// The top anchor keeps no loading state: it would hold the bar up after
|
||||
// a scroll back to live output, where it hides today.
|
||||
if (anchor === 'content') {
|
||||
this._historyReloadActionLoadingFor = sessionId;
|
||||
this._syncHistoryReloadAction();
|
||||
}
|
||||
return this._maybeRefetchFullHistory({ force: true, anchor }).finally(() => {
|
||||
if (anchor === 'content' && this._historyReloadActionLoadingFor === sessionId) {
|
||||
this._historyReloadActionLoadingFor = null;
|
||||
}
|
||||
this._renderHistoryTruncationBanner();
|
||||
});
|
||||
};
|
||||
bar.appendChild(btn);
|
||||
} else if (eligible || loading) {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'history-trunc-load';
|
||||
btn.disabled = loading;
|
||||
btn.textContent = loading ? 'Loading…' : 'Reload history';
|
||||
btn.onclick = () => {
|
||||
if (!this._historyReloadActionEligible()) {
|
||||
this._syncHistoryReloadAction();
|
||||
return;
|
||||
}
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Loading…';
|
||||
this._historyReloadActionLoadingFor = sessionId;
|
||||
this._syncHistoryReloadAction();
|
||||
return this._maybeRefetchFullHistory({ force: true, anchor: 'content' }).finally(() => {
|
||||
if (this._historyReloadActionLoadingFor === sessionId) this._historyReloadActionLoadingFor = null;
|
||||
this._syncHistoryReloadAction();
|
||||
});
|
||||
};
|
||||
bar.appendChild(btn);
|
||||
}
|
||||
|
||||
const dismiss = document.createElement('button');
|
||||
dismiss.type = 'button';
|
||||
dismiss.className = 'history-trunc-dismiss';
|
||||
dismiss.setAttribute('aria-label', 'Dismiss history notice');
|
||||
// Name what the × actually dismisses: a reload-only bar has no notice.
|
||||
dismiss.setAttribute('aria-label', showNotice ? 'Dismiss history notice' : 'Dismiss Reload history');
|
||||
dismiss.textContent = '×';
|
||||
dismiss.onclick = () => {
|
||||
// Sticky for this session until the page reloads: a dismissed notice used
|
||||
// to come straight back on the next tab switch.
|
||||
(this._historyNoticeDismissed ||= new Set()).add(sessionId);
|
||||
bar.hidden = true;
|
||||
// One × dismisses everything this bar carried. A notice dismissal sticks
|
||||
// for the lifetime of this page; a reload dismissal lasts until a
|
||||
// successful full mux replay clears the session's mark.
|
||||
if (showNotice) (this._historyNoticeDismissed ||= new Set()).add(sessionId);
|
||||
if (eligible || loading) (this._historyReloadDismissed ||= new Set()).add(sessionId);
|
||||
this._renderHistoryTruncationBanner();
|
||||
};
|
||||
bar.appendChild(dismiss);
|
||||
|
||||
@@ -10118,6 +10329,7 @@ class CodemanApp {
|
||||
this.activeSessionId = sessionId;
|
||||
this._activateFileBrowserSession?.(sessionId);
|
||||
if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId);
|
||||
this._syncHistoryReloadAction?.();
|
||||
// A keyboard row hold belongs to the session it was taken for: release it here
|
||||
// if this one resizes instead (the geometry work below then fits it).
|
||||
this._reconcileKeyboardHold?.({ resize: false });
|
||||
@@ -10421,9 +10633,12 @@ class CodemanApp {
|
||||
!session?.remote && !session?.docker && !session?.adopt && this._paneHistoryLines?.get(sessionId) === 0;
|
||||
const useFullHistory = !shellSession && (paneKeepsNoHistory || !this._fullHistoryLoaded.has(sessionId));
|
||||
if (useFullHistory) this._fullHistoryLoaded.add(sessionId);
|
||||
// Sample before fetching, as other replays do, so output during download keeps the session marked.
|
||||
const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0;
|
||||
const fetchStartedAt = performance.now();
|
||||
const tailUrl = `/api/sessions/${sessionId}/terminal?tail=${TERMINAL_TAIL_SIZE}`;
|
||||
let capture;
|
||||
let fullHistoryReplay = useFullHistory;
|
||||
try {
|
||||
capture = await this._fetchTerminalCapture(
|
||||
useFullHistory
|
||||
@@ -10444,6 +10659,7 @@ class CodemanApp {
|
||||
_crashDiag.log('FULL CAPTURE ABORTED → tail');
|
||||
// It never loaded, so the next select must be allowed to try again.
|
||||
this._fullHistoryLoaded.delete(sessionId);
|
||||
fullHistoryReplay = false;
|
||||
capture = await this._fetchTerminalCapture(tailUrl);
|
||||
}
|
||||
const headersReceivedAt = capture.headersAt;
|
||||
@@ -10489,7 +10705,7 @@ class CodemanApp {
|
||||
// cannot be actioned, and is indistinguishable from real CLI output.
|
||||
this._setHistoryTruncation(sessionId, data);
|
||||
// Use chunked write for large buffers to avoid UI jank
|
||||
const { parsedAt: freshParsedAt } = await this.chunkedTerminalWrite(
|
||||
const { parsedAt: freshParsedAt, completed } = await this.chunkedTerminalWrite(
|
||||
data.terminalBuffer,
|
||||
TERMINAL_CHUNK_SIZE,
|
||||
bufferLoadOwner,
|
||||
@@ -10500,6 +10716,11 @@ class CodemanApp {
|
||||
this._clearTerminalLoadState(sessionId, selectGen);
|
||||
return;
|
||||
}
|
||||
if (fullHistoryReplay && data.source === 'mux-full-history' && completed && (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) {
|
||||
this._liveOutputSinceFullPull?.delete(sessionId);
|
||||
this._historyReloadDismissed?.delete(sessionId);
|
||||
this._syncHistoryReloadAction?.();
|
||||
}
|
||||
// Ensure terminal is scrolled to bottom after buffer load
|
||||
this.terminal.scrollToBottom();
|
||||
}
|
||||
@@ -10915,6 +11136,10 @@ class CodemanApp {
|
||||
}
|
||||
this.terminalBuffers.delete(sessionId);
|
||||
this.terminalBufferCache.delete(sessionId);
|
||||
this._liveOutputSinceFullPull?.delete(sessionId);
|
||||
this._historyReloadDismissed?.delete(sessionId);
|
||||
this._syncHistoryReloadAction?.();
|
||||
this._liveOutputGen?.delete(sessionId);
|
||||
this._clearHistoryTruncation(sessionId);
|
||||
this._xtermSnapshots?.delete(sessionId);
|
||||
try { localStorage.removeItem(`codeman-xs-${sessionId}`); } catch {}
|
||||
|
||||
@@ -751,6 +751,13 @@
|
||||
'Extended Keyboard Bar': '扩展键盘栏',
|
||||
'Gesture Control (beta)': '手势控制(测试版)',
|
||||
'Wheel Scrolls Local History': '滚轮滚动本地历史',
|
||||
'History Reload Button': '历史重新加载按钮',
|
||||
'When scrolled up after new output, offer a Reload history action that re-reads the full tmux history (a full capture on the server).':
|
||||
'有新输出后向上滚动时,提供“重新加载历史”操作,重新读取完整的 tmux 历史(在服务器上完整捕获)。',
|
||||
'Recent output may be missing from this view.': '此视图可能缺少最近的输出。',
|
||||
'Reload history': '重新加载历史',
|
||||
'Load full history': '加载完整历史',
|
||||
'Dismiss Reload history': '忽略“重新加载历史”',
|
||||
'Auto Copy Selection': '自动复制选中内容',
|
||||
'Selection & clipboard': '选中与剪贴板',
|
||||
'Auto Copy: selection copied': '自动复制:已复制选中内容',
|
||||
|
||||
@@ -2161,6 +2161,13 @@
|
||||
</div>
|
||||
<label class="switch switch-sm"><input type="checkbox" id="appSettingsTerminalWheelLocal"><span class="slider"></span></label>
|
||||
</div>
|
||||
<div class="set-row" data-search="history reload button repair scrollback">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">History Reload Button <span class="set-scope">device</span></span>
|
||||
<span class="set-row-desc">When scrolled up after new output, offer a Reload history action that re-reads the full tmux history (a full capture on the server).</span>
|
||||
</div>
|
||||
<label class="switch switch-sm"><input type="checkbox" id="appSettingsHistoryReloadAction"><span class="slider"></span></label>
|
||||
</div>
|
||||
<div class="set-row" id="appSettingsWebglRendererItem" data-search="webgl renderer gpu terminal">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">WebGL Renderer <span class="set-tag">desktop</span> <span class="set-scope">device</span></span>
|
||||
|
||||
@@ -648,6 +648,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
);
|
||||
document.getElementById('appSettingsTerminalWheelLocal').checked =
|
||||
settings.terminalWheelLocalScrollback ?? defaults.terminalWheelLocalScrollback ?? false;
|
||||
document.getElementById('appSettingsHistoryReloadAction').checked =
|
||||
settings.historyReloadAction ?? defaults.historyReloadAction ?? true;
|
||||
document.getElementById('appSettingsCjkInput').checked = settings.cjkInputEnabled ?? defaults.cjkInputEnabled ?? false;
|
||||
document.getElementById('appSettingsCjkHoldUntilEnter').checked =
|
||||
settings.cjkInputHoldUntilEnter ?? defaults.cjkInputHoldUntilEnter ?? false;
|
||||
@@ -3196,6 +3198,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.getElementById('appSettingsTerminalFontWeightBold')
|
||||
),
|
||||
terminalWheelLocalScrollback: document.getElementById('appSettingsTerminalWheelLocal').checked,
|
||||
historyReloadAction: document.getElementById('appSettingsHistoryReloadAction').checked,
|
||||
cjkInputEnabled: document.getElementById('appSettingsCjkInput').checked,
|
||||
cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked,
|
||||
webglRendererEnabled: document.getElementById('appSettingsWebglRenderer').checked,
|
||||
@@ -3285,6 +3288,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._updateLocalEchoState();
|
||||
// Turning Keep Size Under Keyboard off while it holds releases it now.
|
||||
this._reconcileKeyboardHold?.();
|
||||
this._syncHistoryReloadAction?.();
|
||||
this.applyTerminalFontFamily?.(settings.terminalFontFamily);
|
||||
this.applyTerminalFontWeights?.(settings);
|
||||
|
||||
@@ -3459,6 +3463,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
showTileGridButton: _stg,
|
||||
webglRendererEnabled: _wgl,
|
||||
terminalWheelLocalScrollback: _twls,
|
||||
historyReloadAction: _hra,
|
||||
// Copy-on-select. Per-device (clipboard access differs by device and by
|
||||
// origin: the plain-HTTP LAN install has no navigator.clipboard at all)
|
||||
// and absent from SettingsUpdateSchema (.strict()), so sending it would
|
||||
@@ -4484,6 +4489,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
cjkInputEnabled: false,
|
||||
cjkInputHoldUntilEnter: false,
|
||||
terminalWheelLocalScrollback: false, // mobile scrolls via touch, not wheel
|
||||
historyReloadAction: true,
|
||||
webglRendererEnabled: false, // mobile always uses the DOM renderer
|
||||
skin: 'daylight-blue',
|
||||
};
|
||||
@@ -5216,6 +5222,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
'terminalFontFamily', 'terminalFontWeight', 'terminalFontWeightBold',
|
||||
'language',
|
||||
'terminalWheelLocalScrollback',
|
||||
'historyReloadAction',
|
||||
'autoCopySelection', 'copyStripMargin',
|
||||
'showSessionButton', 'showAwayDigestButton', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds', 'showEditHistory',
|
||||
'showTabDetachButton',
|
||||
|
||||
+131
-13
@@ -1451,6 +1451,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._predictiveEcho =
|
||||
typeof PredictiveEchoOverlay !== 'undefined' ? new PredictiveEchoOverlay(this.terminal) : null;
|
||||
this._predictiveEcho?.setPredictWhen((terminal) => window.CodemanTerminalInput.isCodexComposerRow(terminal));
|
||||
this.terminal.onScroll(() => this._scheduleHistoryReloadActionSync());
|
||||
if (MobileDetection.isTouchDevice()) {
|
||||
this.terminal.onCursorMove(() => this._syncMobileHelperTextareaToCursor());
|
||||
this.terminal.onRender(() => this._syncMobileHelperTextareaToCursor());
|
||||
@@ -4043,6 +4044,86 @@ Object.assign(CodemanApp.prototype, {
|
||||
return buffer.viewportY >= buffer.baseY - 2;
|
||||
},
|
||||
|
||||
/** Capture bounded viewport context, not just repeated TUI borders/status rows. */
|
||||
_captureViewportAnchor() {
|
||||
const buffer = this.terminal.buffer.active;
|
||||
const { viewportY, baseY } = buffer;
|
||||
const context = Array.from(
|
||||
{ length: Math.min(this.terminal.rows || 3, 64, buffer.length - viewportY) },
|
||||
(_, i) => buffer.getLine(viewportY + i)?.translateToString(true) || ''
|
||||
);
|
||||
return { viewportY, rowsFromBottom: baseY - viewportY, context };
|
||||
},
|
||||
|
||||
/** Match the visible context; a lone repeated row is not a reliable anchor. */
|
||||
_restoreViewportAnchor(anchor) {
|
||||
const buffer = this.terminal.buffer.active;
|
||||
const clamp = (row) => Math.max(0, Math.min(buffer.baseY, row));
|
||||
let target = clamp(anchor.viewportY);
|
||||
if (anchor.rowsFromBottom <= 2) {
|
||||
target = clamp(buffer.baseY - anchor.rowsFromBottom);
|
||||
} else {
|
||||
const expected = clamp(buffer.baseY - anchor.rowsFromBottom);
|
||||
const frequencies = new Map();
|
||||
for (const text of anchor.context) {
|
||||
if (text.trim()) frequencies.set(text, (frequencies.get(text) || 0) + 1);
|
||||
}
|
||||
const samples = anchor.context.flatMap((text, offset) =>
|
||||
text.trim() ? [{ text, offset, weight: 1 / frequencies.get(text) }] : []
|
||||
);
|
||||
// Each distinct visible row contributes at most one point: repeated box
|
||||
// borders cannot outvote the tool result the user is actually reading.
|
||||
// Capped at the distinct-row count so a sparse viewport (one unique row
|
||||
// among blanks) can still match; the ambiguity check rejects repeats.
|
||||
const minimumScore = Math.min(frequencies.size, Math.max(2, frequencies.size * 0.6));
|
||||
// Every row a reload fills in BELOW the reader moves the reader's row one
|
||||
// up from `expected`; a capture with fewer rows below moves it down by at
|
||||
// most the one screen the downgrade guard tolerates. So the window leans
|
||||
// up: 4001 candidates from `expected - 4000 + rows` to `expected + rows`,
|
||||
// which lands gaps up to `4000 - rows` exactly even at the scrollback cap,
|
||||
// where the replay trims the top and the old index is no longer a fallback.
|
||||
const rows = this.terminal.rows || 0;
|
||||
const first = Math.max(0, expected - 4000 + rows);
|
||||
const last = Math.min(buffer.baseY, expected + rows);
|
||||
// Cache the search window once: <= 4064 getLine calls, even when all
|
||||
// 4001 candidates match repeated TUI furniture in a 50k-row buffer.
|
||||
const text = Array.from(
|
||||
{ length: Math.min(buffer.length, last + anchor.context.length) - first },
|
||||
(_, i) => buffer.getLine(first + i)?.translateToString(true) || ''
|
||||
);
|
||||
let bestScore = 0;
|
||||
let bestRow = null;
|
||||
let ambiguous = false;
|
||||
for (let row = first; row <= last; row++) {
|
||||
let score = 0;
|
||||
for (const sample of samples) {
|
||||
if (text[row - first + sample.offset] === sample.text) score += sample.weight;
|
||||
}
|
||||
if (score > bestScore + 1e-9) {
|
||||
bestScore = score;
|
||||
bestRow = row;
|
||||
ambiguous = false;
|
||||
} else if (Math.abs(score - bestScore) <= 1e-9) {
|
||||
ambiguous = true;
|
||||
}
|
||||
}
|
||||
// Equally good copies are evidence of repeated furniture, not of the
|
||||
// reader's location. A gap below them makes nearest-to-expected wrong.
|
||||
if (!ambiguous && bestScore + 1e-9 >= minimumScore) target = bestRow;
|
||||
}
|
||||
this.terminal.scrollToLine(target);
|
||||
return target;
|
||||
},
|
||||
|
||||
/** xterm may emit once per scrolled line; sample eligibility once per frame. */
|
||||
_scheduleHistoryReloadActionSync() {
|
||||
if (this._historyReloadActionFrame != null) return;
|
||||
this._historyReloadActionFrame = requestAnimationFrame(() => {
|
||||
this._historyReloadActionFrame = null;
|
||||
this._syncHistoryReloadAction();
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Re-take the sticky-scroll baseline from where the viewport now sits.
|
||||
*
|
||||
@@ -4087,13 +4168,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
/**
|
||||
* Post-scroll companion to _noteTerminalUserScroll: hitting the TOP of the
|
||||
* buffer while scrolling up gives the app a chance to pull the rest of tmux's
|
||||
* scrollback (issue #205, see _maybeRefetchFullHistory). Shell sessions pull a
|
||||
* bounded window because their captures can be large; their banner button is
|
||||
* the unbounded path. Must be called AFTER scrollLines(), since the check is on
|
||||
* the resulting position, and it is deliberately not folded into
|
||||
* _noteTerminalUserScroll for exactly that reason.
|
||||
* After scrollLines(), pull only at the top of the local buffer (#205).
|
||||
* Shells pull a bounded window; full captures while reading require the
|
||||
* explicit Reload history action (#814). The pull owns cooldown/latch and
|
||||
* downgrade guards. Content-anchored replays keep session-scoped travel.
|
||||
*
|
||||
* It is also what brings up the partial-history notice, and what retires it
|
||||
* once a downward scroll is back at live output (_setHistoryNoticeRevealed).
|
||||
@@ -4101,19 +4179,26 @@ Object.assign(CodemanApp.prototype, {
|
||||
* what the pull left rather than flashing the state it is about to replace.
|
||||
*/
|
||||
_maybeLoadMoreHistoryOnScroll(lines) {
|
||||
if (this._earlyReplayTravel?.sessionId === this.activeSessionId) {
|
||||
this._earlyReplayTravel.moves.push(lines);
|
||||
return;
|
||||
}
|
||||
if (lines > 0) {
|
||||
if (this.isTerminalAtBottom()) this._setHistoryNoticeRevealed?.(null);
|
||||
return;
|
||||
}
|
||||
if (lines === 0 || this.terminal?.buffer?.active?.viewportY !== 0) return;
|
||||
// An earlier frame of this gesture already started the pull; its own
|
||||
// completion reveals the notice, so do not flash the pre-pull state now.
|
||||
if (this._fullHistoryRepullInFlight || this._isLoadingBuffer) return;
|
||||
if (lines === 0) return;
|
||||
const buffer = this.terminal?.buffer?.active;
|
||||
if (buffer?.viewportY !== 0) return;
|
||||
const sessionId = this.activeSessionId;
|
||||
// An earlier frame already started a pull and owns the notice reveal.
|
||||
if (this._fullHistoryRepullInFlight || this._isLoadingBuffer) return;
|
||||
Promise.resolve(this._maybeRefetchFullHistory?.())
|
||||
.catch(() => {})
|
||||
.then(() => {
|
||||
if (sessionId && this.activeSessionId === sessionId) this._setHistoryNoticeRevealed?.(sessionId);
|
||||
if (sessionId && this.activeSessionId === sessionId) {
|
||||
this._setHistoryNoticeRevealed?.(sessionId);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
@@ -4698,6 +4783,13 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.terminal.buffer?.active && !this.isTerminalAtBottom() ? this.terminal.buffer.active.viewportY : null;
|
||||
// Which buffer the anchor belongs to, checked again when the write parses.
|
||||
const flushSessionId = this.activeSessionId;
|
||||
// xterm adjusts marker lines when its circular scrollback trims rows. An
|
||||
// absolute viewport index does not track that trim and would move the
|
||||
// reader upward on every live flush at the scrollback cap (#814).
|
||||
const viewportBuffer = this.terminal.buffer?.active;
|
||||
const viewportMarker = preserveViewportY !== null
|
||||
? this.terminal.registerMarker?.(preserveViewportY - (viewportBuffer.baseY + viewportBuffer.cursorY))
|
||||
: null;
|
||||
|
||||
const writeChunk = joined.slice(0, MAX_FRAME_BYTES);
|
||||
if (_joinedLen > MAX_FRAME_BYTES) {
|
||||
@@ -4724,15 +4816,35 @@ Object.assign(CodemanApp.prototype, {
|
||||
// signal, which is the earliest point the anchor can actually be
|
||||
// reasserted. (The synchronous version passed its regression test only
|
||||
// because the test's write mock moved the viewport synchronously.)
|
||||
this._restoreTerminalViewport(preserveViewportY, flushSessionId);
|
||||
// A marker is disposed when its row is trimmed off a full scrollback,
|
||||
// but also when the stream itself erases scrollback with `ESC[3J`,
|
||||
// which the narrow and middle strips keep. Fall back to the absolute
|
||||
// index then, as before markers, rather than sending the reader to row 0.
|
||||
// (RIS does not dispose it: xterm swaps in a new buffer and the marker
|
||||
// stays on its old line, which is the same index as this fallback.)
|
||||
const viewportY = viewportMarker && !viewportMarker.isDisposed ? viewportMarker.line : preserveViewportY;
|
||||
viewportMarker?.dispose();
|
||||
this._restoreTerminalViewport(viewportY, flushSessionId);
|
||||
this._scheduleTerminalWriteFlush();
|
||||
this._noteMobileImeAuthoritativeOutput(flushedOutputSeq, flushSessionId);
|
||||
});
|
||||
} catch (err) {
|
||||
viewportMarker?.dispose();
|
||||
this._terminalWriteInFlight = false;
|
||||
this._terminalWriteInFlightBytes = 0;
|
||||
throw err;
|
||||
}
|
||||
// Only live writes can open a new tmux repaint gap; replays cannot (#814).
|
||||
// Outside the try: the catch above must only cover the write itself.
|
||||
if (writeChunk.length && flushSessionId && !this._isLoadingBuffer) {
|
||||
const marked = (this._liveOutputSinceFullPull ||= new Set());
|
||||
const newlyMarked = !marked.has(flushSessionId);
|
||||
marked.add(flushSessionId);
|
||||
const generations = (this._liveOutputGen ||= new Map());
|
||||
generations.set(flushSessionId, (generations.get(flushSessionId) || 0) + 1);
|
||||
// Mark transitions sync immediately; onScroll is coalesced on all devices.
|
||||
if (newlyMarked) this._syncHistoryReloadAction?.();
|
||||
}
|
||||
const bytesThisFrame = deferred ? MAX_FRAME_BYTES : _joinedLen;
|
||||
const _dt = performance.now() - _t0;
|
||||
if (_dt > 100 || deferred)
|
||||
@@ -5057,6 +5169,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._isLoadingBuffer = false;
|
||||
this._loadBufferQueue = null;
|
||||
this._bufferLoadOwner = null;
|
||||
this._syncHistoryReloadAction?.();
|
||||
// COD-144: replay (rather than discard) queued live events when the load
|
||||
// painted nothing — the queued prompt is the only content a new session has.
|
||||
// A tmux-capture load replays too, but only the tail: `since` cuts the queue
|
||||
@@ -5068,6 +5181,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.batchTerminalWrite(entry.data);
|
||||
}
|
||||
}
|
||||
const recovery = this._pendingDroppedOutputRecovery;
|
||||
this._pendingDroppedOutputRecovery = null;
|
||||
if (recovery && recovery.sessionId === this.activeSessionId) {
|
||||
this._scheduleDroppedOutputRecovery?.(recovery.sessionId, recovery.attempt);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
|
||||
|
||||
@@ -0,0 +1,668 @@
|
||||
/** Real xterm + manual banner actions recover tmux repaint gaps while reading (#814). */
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { chromium, type Browser, type BrowserContext, type Page } from 'playwright';
|
||||
import type { Terminal } from '@xterm/xterm';
|
||||
import { WebServer } from '../src/web/server.js';
|
||||
|
||||
type Anchor = { context: string[]; viewportY: number; rowsFromBottom: number };
|
||||
type HistoryApp = {
|
||||
terminal: Terminal & {
|
||||
_core?: { _renderService?: { dimensions?: { css?: { cell?: { height: number } } } } };
|
||||
};
|
||||
fitAddon: { proposeDimensions(): { cols: number; rows: number } | undefined };
|
||||
sessions: Map<string, object>;
|
||||
activeSessionId: string;
|
||||
hideWelcome(): void;
|
||||
selectSession(sessionId: string): Promise<void>;
|
||||
_onSessionTerminal(event: { id: string; data: string }): void;
|
||||
_liveOutputSinceFullPull: Set<string>;
|
||||
_fullHistoryRepullInFlight: boolean;
|
||||
_isLoadingBuffer: boolean;
|
||||
pendingWrites: string[];
|
||||
_terminalWriteInFlight: boolean;
|
||||
_bufferLoadOwner: unknown;
|
||||
_loadBufferQueue: { data: string; at: number }[] | null;
|
||||
_selectGeneration: number;
|
||||
_initGeneration: number;
|
||||
terminalLoadStates: Map<string, unknown>;
|
||||
_terminalFontReady: Promise<void>;
|
||||
_resizeTimeout: number | null;
|
||||
_lastResizeDims: { cols: number; rows: number } | null;
|
||||
_syncStickyScrollBaseline(): void;
|
||||
_captureViewportAnchor(): Anchor;
|
||||
_syncHistoryReloadAction(): void;
|
||||
loadAppSettingsFromStorage(): Record<string, unknown>;
|
||||
saveAppSettingsToStorage(settings: Record<string, unknown>): void;
|
||||
_setHistoryTruncation(sessionId: string, payload: Record<string, unknown>): void;
|
||||
_setHistoryNoticeRevealed(sessionId: string): void;
|
||||
};
|
||||
type RepairWindow = Window & {
|
||||
app: HistoryApp;
|
||||
repairTest: { pulls: number; anchor: Anchor | null; inject: boolean };
|
||||
repairReadiness?: { cols: number; rows: number; frames: number };
|
||||
tabLoadTest?: { requested: boolean; release(): void; selection: Promise<void> };
|
||||
};
|
||||
|
||||
const SESSION = 'history-repair-browser';
|
||||
const MARKER = 'AFTER-CAPTURE-DURING-DOWNLOAD';
|
||||
let server: WebServer;
|
||||
let browser: Browser;
|
||||
let baseUrl: string;
|
||||
const pageEvents = new WeakMap<Page, string[]>();
|
||||
|
||||
async function setupState(page: Page) {
|
||||
return page.evaluate(() => {
|
||||
const app = (window as RepairWindow).app;
|
||||
const buffer = app?.terminal?.buffer.active;
|
||||
return {
|
||||
appLoaded: document.body.classList.contains('app-loaded'),
|
||||
baseY: buffer?.baseY,
|
||||
length: buffer?.length,
|
||||
viewportY: buffer?.viewportY,
|
||||
cols: app?.terminal?.cols,
|
||||
rows: app?.terminal?.rows,
|
||||
resizePending: Boolean(app?._resizeTimeout),
|
||||
lastResizeDims: app?._lastResizeDims,
|
||||
proposedDims: app?.fitAddon?.proposeDimensions(),
|
||||
cellHeight: app?.terminal?._core?._renderService?.dimensions?.css?.cell?.height,
|
||||
pendingWrites: app?.pendingWrites?.length,
|
||||
terminalWriteInFlight: app?._terminalWriteInFlight,
|
||||
isLoadingBuffer: app?._isLoadingBuffer,
|
||||
bufferLoadOwner: app?._bufferLoadOwner,
|
||||
loadBufferQueue: app?._loadBufferQueue?.length ?? 0,
|
||||
activeSessionId: app?.activeSessionId,
|
||||
selectGeneration: app?._selectGeneration,
|
||||
sessions: app?.sessions ? [...app.sessions.keys()] : [],
|
||||
initGeneration: app?._initGeneration,
|
||||
terminalLoadStates: app?.terminalLoadStates ? [...app.terminalLoadStates] : [],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function failureDetails(page: Page, error: unknown): Promise<Error> {
|
||||
const setup = await setupState(page).catch(String);
|
||||
const buffer = await bufferState(page).catch(String);
|
||||
return new Error(JSON.stringify({ setup, buffer, events: pageEvents.get(page) }), { cause: error });
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
server = new WebServer(0, false, true);
|
||||
await server.start();
|
||||
baseUrl = `http://localhost:${server.boundPort}`;
|
||||
browser = await chromium.launch({ headless: true });
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await browser?.close();
|
||||
await server?.stop();
|
||||
}, 30_000);
|
||||
|
||||
async function openTerminal(
|
||||
touch: boolean,
|
||||
viewport = touch ? { width: 390, height: 640 } : { width: 1280, height: 800 }
|
||||
): Promise<{ context: BrowserContext; page: Page }> {
|
||||
const context = await browser.newContext({
|
||||
hasTouch: touch,
|
||||
isMobile: touch,
|
||||
viewport,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
const events: string[] = [];
|
||||
pageEvents.set(page, events);
|
||||
page.on('console', (message) => {
|
||||
events.push(`console.${message.type()}: ${message.text()}`);
|
||||
if (events.length > 100) events.shift();
|
||||
});
|
||||
page.on('pageerror', (error) => events.push(`pageerror: ${error.stack || error.message}`));
|
||||
try {
|
||||
await page.goto(baseUrl, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForFunction(() => document.body.classList.contains('app-loaded'));
|
||||
await page.waitForFunction(() => {
|
||||
const app = (window as RepairWindow).app;
|
||||
return app?.terminal && app._initGeneration > 0 && !app._isLoadingBuffer && app.terminalLoadStates.size === 0;
|
||||
});
|
||||
await page.evaluate(async (session) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
// A client-only OMP session isolates the rendering path from real CLI/PTYS.
|
||||
// Opening it changes layout, so finish the real resize path BEFORE seeding.
|
||||
app.sessions.set(session, { id: session, mode: 'omp', status: 'idle', name: 'History repair' });
|
||||
app.activeSessionId = session;
|
||||
app.hideWelcome();
|
||||
await app._terminalFontReady;
|
||||
await document.fonts.ready;
|
||||
// Empty xterm can still carry fallback render metrics. Paint a glyph
|
||||
// before fitting, then clear it before the fixture's numbered output.
|
||||
const rendered = Promise.withResolvers<void>();
|
||||
const listener = app.terminal.onRender(() => {
|
||||
listener.dispose();
|
||||
rendered.resolve();
|
||||
});
|
||||
app.terminal.write('W');
|
||||
await rendered.promise;
|
||||
const { promise, resolve } = Promise.withResolvers<void>();
|
||||
app.terminal.write('\x1bc', resolve);
|
||||
await promise;
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
}, SESSION);
|
||||
await page.waitForFunction(() => {
|
||||
const w = window as RepairWindow;
|
||||
const app = w.app;
|
||||
const { cols, rows } = app.terminal;
|
||||
const proposed = app.fitAddon.proposeDimensions();
|
||||
const cellHeight = app.terminal._core?._renderService?.dimensions?.css?.cell?.height || 0;
|
||||
if (
|
||||
cellHeight <= 0 ||
|
||||
proposed?.cols !== cols ||
|
||||
proposed?.rows !== rows ||
|
||||
app._resizeTimeout ||
|
||||
app._isLoadingBuffer ||
|
||||
app.terminalLoadStates.size ||
|
||||
app.pendingWrites.length ||
|
||||
app._terminalWriteInFlight ||
|
||||
app._lastResizeDims?.cols !== cols ||
|
||||
app._lastResizeDims?.rows !== rows
|
||||
) {
|
||||
w.repairReadiness = undefined;
|
||||
return false;
|
||||
}
|
||||
// Synchronous rAF polling: require the initial match plus two more frames.
|
||||
// An async predicate returns a truthy Promise, which Playwright won't retry.
|
||||
const previous = w.repairReadiness;
|
||||
const frames = previous?.cols === cols && previous.rows === rows ? previous.frames + 1 : 1;
|
||||
w.repairReadiness = { cols, rows, frames };
|
||||
return frames >= 3;
|
||||
});
|
||||
await page.evaluate(
|
||||
async ({ session, marker }) => {
|
||||
const w = window as RepairWindow;
|
||||
const app = w.app;
|
||||
// Startup resets and resize clears have already parsed at fitted geometry.
|
||||
w.repairTest = { pulls: 0, anchor: null, inject: false };
|
||||
const captureAnchor = app._captureViewportAnchor.bind(app);
|
||||
app._captureViewportAnchor = () => {
|
||||
const anchor = captureAnchor();
|
||||
w.repairTest.anchor = anchor;
|
||||
return anchor;
|
||||
};
|
||||
const realFetch = window.fetch.bind(window);
|
||||
window.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(typeof input === 'string' ? input : ((input as Request).url ?? input));
|
||||
if (!url.includes(`/api/sessions/${session}/terminal`)) return realFetch(input, init);
|
||||
if (!url.includes('full=1')) throw new Error(`Unexpected history request: ${url}`);
|
||||
w.repairTest.pulls++;
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
status: 200,
|
||||
headers: new Headers(),
|
||||
json: async () => {
|
||||
// This is after headers and before replay, inside the real load window.
|
||||
if (w.repairTest.inject) app._onSessionTerminal({ id: session, data: `\r\n${marker}\r\n` });
|
||||
const terminalBuffer =
|
||||
Array.from({ length: 144 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}`).join('\r\n') + '\r\n';
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
terminalBuffer,
|
||||
source: 'mux-full-history',
|
||||
paneHistoryLines: 121,
|
||||
truncated: false,
|
||||
fullSize: terminalBuffer.length,
|
||||
retainedBytes: terminalBuffer.length,
|
||||
},
|
||||
};
|
||||
},
|
||||
}) as unknown as Promise<Response>;
|
||||
}) as typeof window.fetch;
|
||||
// All output still enters through the production terminal event path.
|
||||
app._onSessionTerminal({
|
||||
id: session,
|
||||
data: Array.from({ length: 60 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}\r\n`).join(''),
|
||||
});
|
||||
await new Promise<void>((resolve) => app.terminal.write('', resolve));
|
||||
},
|
||||
{ session: SESSION, marker: MARKER }
|
||||
);
|
||||
await page.waitForFunction(() => {
|
||||
const app = (window as RepairWindow).app;
|
||||
const buffer = app.terminal.buffer.active;
|
||||
return (
|
||||
buffer.length === 61 &&
|
||||
buffer.baseY === 61 - app.terminal.rows &&
|
||||
!app.pendingWrites.length &&
|
||||
!app._terminalWriteInFlight &&
|
||||
Array.from({ length: 60 }, (_, i) => buffer.getLine(i)?.translateToString(true)).every(
|
||||
(row, i) => row === `NUMBER-${String(i).padStart(3, '0')}`
|
||||
)
|
||||
);
|
||||
});
|
||||
// The initial 60 lines stand in for the last successful full-history replay.
|
||||
await page.evaluate((session) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
app.terminal.scrollToBottom();
|
||||
app._syncStickyScrollBaseline();
|
||||
app._liveOutputSinceFullPull.delete(session);
|
||||
}, SESSION);
|
||||
} catch (error) {
|
||||
const state = await setupState(page).catch(String);
|
||||
await context.close();
|
||||
throw new Error(`Terminal setup failed: ${JSON.stringify({ state, events })}`, { cause: error });
|
||||
}
|
||||
return { context, page };
|
||||
}
|
||||
|
||||
/** Finger down scrolls history up; cancel at the endpoint to avoid momentum. */
|
||||
async function scrollHistoryByTouch(page: Page, distance: number): Promise<void> {
|
||||
const box = await page.locator('#terminalContainer').boundingBox();
|
||||
if (!box) throw new Error('Terminal container is not visible');
|
||||
const x = box.x + box.width / 2;
|
||||
const y = box.y + Math.min(80, box.height / 4);
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
const before = await page.evaluate(() => (window as RepairWindow).app.terminal.buffer.active.viewportY);
|
||||
try {
|
||||
await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] });
|
||||
await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x, y: y + distance }] });
|
||||
await page.waitForFunction((previous) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
return app.terminal.buffer.active.viewportY !== previous || app._fullHistoryRepullInFlight;
|
||||
}, before);
|
||||
// A trusted cancellation ends the drag without xterm/app momentum changing
|
||||
// the reading position after the gesture or starting another top pull.
|
||||
await cdp.send('Input.dispatchTouchEvent', { type: 'touchCancel', touchPoints: [] });
|
||||
} finally {
|
||||
await cdp.detach();
|
||||
}
|
||||
}
|
||||
|
||||
async function burst(page: Page): Promise<void> {
|
||||
await page.evaluate((session) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
// tmux scrolls a whole screen and repaints the last 24 rows. The numbered
|
||||
// rows 60..119 exist only in tmux and are deliberately absent from this stream.
|
||||
const repaint = Array.from({ length: 24 }, (_, row) => `\x1b[${row + 1};1H\x1b[2KNUMBER-${120 + row}`).join('');
|
||||
app._onSessionTerminal({ id: session, data: `\x1b[24S${repaint}` });
|
||||
}, SESSION);
|
||||
await page.waitForFunction((session) => (window as RepairWindow).app._liveOutputSinceFullPull.has(session), SESSION);
|
||||
}
|
||||
|
||||
async function bufferState(page: Page) {
|
||||
return page.evaluate((marker) => {
|
||||
const w = window as RepairWindow;
|
||||
const buffer = w.app.terminal.buffer.active;
|
||||
const rows = Array.from(
|
||||
{ length: buffer.length },
|
||||
(_, i) => buffer.getLine(i)?.translateToString(true).trim() || ''
|
||||
);
|
||||
const anchor = w.repairTest.anchor;
|
||||
// The first non-blank visible row the anchor captured, and where it sat.
|
||||
const anchorRow = anchor ? anchor.context.findIndex((text) => text.trim()) : -1;
|
||||
return {
|
||||
numbers: rows.filter((row) => /^NUMBER-\d+$/.test(row)),
|
||||
markerHits: rows.filter((row) => row.includes(marker)).length,
|
||||
anchorOffset: anchor ? rows.indexOf(anchor.context[anchorRow]) - buffer.viewportY : null,
|
||||
expectedOffset: anchor ? anchorRow : undefined,
|
||||
pulls: w.repairTest.pulls,
|
||||
viewportY: buffer.viewportY,
|
||||
baseY: buffer.baseY,
|
||||
session: w.app.activeSessionId,
|
||||
length: buffer.length,
|
||||
pendingWrites: w.app.pendingWrites.length,
|
||||
terminalWriteInFlight: w.app._terminalWriteInFlight,
|
||||
bufferLoadOwner: w.app._bufferLoadOwner,
|
||||
loadBufferQueue: w.app._loadBufferQueue,
|
||||
selectGeneration: w.app._selectGeneration,
|
||||
initGeneration: w.app._initGeneration,
|
||||
sessions: [...w.app.sessions.keys()],
|
||||
marked: w.app._liveOutputSinceFullPull.has(w.app.activeSessionId),
|
||||
loading: w.app._isLoadingBuffer,
|
||||
inFlight: w.app._fullHistoryRepullInFlight,
|
||||
};
|
||||
}, MARKER);
|
||||
}
|
||||
|
||||
async function waitForRepair(page: Page): Promise<void> {
|
||||
await page.waitForFunction(() => {
|
||||
const w = window as RepairWindow;
|
||||
return (
|
||||
w.repairTest.pulls === 1 &&
|
||||
!w.app._fullHistoryRepullInFlight &&
|
||||
!w.app._isLoadingBuffer &&
|
||||
!w.app.pendingWrites.length &&
|
||||
!w.app._terminalWriteInFlight
|
||||
);
|
||||
});
|
||||
// xterm's parse marker is the completion signal for the production flush.
|
||||
await page.evaluate(async () => {
|
||||
const app = (window as RepairWindow).app;
|
||||
await new Promise<void>((resolve) => app.terminal.write('', resolve));
|
||||
});
|
||||
}
|
||||
|
||||
const allNumbers = Array.from({ length: 144 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}`);
|
||||
|
||||
describe.each([true, false])('manual history gap repair (touch: %s)', (touch) => {
|
||||
async function readHistory(page: Page) {
|
||||
if (touch) await scrollHistoryByTouch(page, 100);
|
||||
else await page.evaluate(() => (window as RepairWindow).app.terminal.scrollToLine(10));
|
||||
const position = await page.evaluate(() => {
|
||||
const b = (window as RepairWindow).app.terminal.buffer.active;
|
||||
return { viewportY: b.viewportY, baseY: b.baseY };
|
||||
});
|
||||
expect(position.viewportY).toBeGreaterThan(0);
|
||||
expect(position.baseY - position.viewportY).toBeGreaterThan(5);
|
||||
}
|
||||
|
||||
it('repairs mid-history only on a banner tap/click and holds the reading line offset', async () => {
|
||||
const { context, page } = await openTerminal(touch);
|
||||
try {
|
||||
await readHistory(page);
|
||||
await burst(page);
|
||||
expect((await bufferState(page)).numbers).not.toContain('NUMBER-090');
|
||||
expect((await bufferState(page)).pulls).toBe(0);
|
||||
const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history', exact: true });
|
||||
await button.waitFor({ state: 'visible' });
|
||||
if (touch) await button.tap();
|
||||
else await button.click();
|
||||
await waitForRepair(page);
|
||||
const state = await bufferState(page);
|
||||
expect(state.numbers).toEqual(allNumbers);
|
||||
expect(state.anchorOffset).toBe(state.expectedOffset);
|
||||
expect(state.pulls).toBe(1);
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('keeps output arriving during the capture download exactly once', async () => {
|
||||
const { context, page } = await openTerminal(touch);
|
||||
try {
|
||||
await readHistory(page);
|
||||
await burst(page);
|
||||
await page.evaluate(() => {
|
||||
(window as RepairWindow).repairTest.inject = true;
|
||||
});
|
||||
const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history', exact: true });
|
||||
if (touch) await button.tap();
|
||||
else await button.click();
|
||||
await waitForRepair(page);
|
||||
const state = await bufferState(page);
|
||||
const detail = JSON.stringify({ state, events: pageEvents.get(page) });
|
||||
expect(state.markerHits, detail).toBe(1);
|
||||
expect(state.numbers, detail).toEqual(allNumbers);
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it.each([false, true])(
|
||||
'keeps the revealed notice and one unobstructed load control (exhausted: %s)',
|
||||
async (exhausted) => {
|
||||
const { context, page } = await openTerminal(touch);
|
||||
try {
|
||||
await readHistory(page);
|
||||
await burst(page);
|
||||
await page.evaluate(
|
||||
({ session, exhausted }) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
app._setHistoryTruncation(session, {
|
||||
truncated: true,
|
||||
truncationReason: 'tail',
|
||||
source: 'mux-full-history',
|
||||
fullSize: 2 * 1024 * 1024,
|
||||
retainedBytes: 1024 * 1024,
|
||||
paneHistoryLines: 121,
|
||||
exhausted,
|
||||
});
|
||||
app._setHistoryNoticeRevealed(session);
|
||||
},
|
||||
{ session: SESSION, exhausted }
|
||||
);
|
||||
const bar = page.locator('#historyTruncationBar');
|
||||
await bar.waitFor({ state: 'visible' });
|
||||
expect(await bar.locator('.history-trunc-text').textContent()).not.toBe(
|
||||
'Recent output may be missing from this view.'
|
||||
);
|
||||
const button = bar.locator('.history-trunc-load');
|
||||
expect(await button.count()).toBe(1);
|
||||
expect(await button.textContent()).toBe(exhausted ? 'Reload history' : 'Load full history');
|
||||
for (const control of await bar.getByRole('button').all()) {
|
||||
expect(
|
||||
await control.evaluate((element) => {
|
||||
const box = element.getBoundingClientRect();
|
||||
return document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2) === element;
|
||||
})
|
||||
).toBe(true);
|
||||
}
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
},
|
||||
60_000
|
||||
);
|
||||
|
||||
it('does not offer a reload action when disabled on this device', async () => {
|
||||
const { context, page } = await openTerminal(touch);
|
||||
try {
|
||||
await page.evaluate(() => {
|
||||
const app = (window as RepairWindow).app;
|
||||
app.saveAppSettingsToStorage({ ...app.loadAppSettingsFromStorage(), historyReloadAction: false });
|
||||
app._syncHistoryReloadAction();
|
||||
});
|
||||
await readHistory(page);
|
||||
await burst(page);
|
||||
// Wait for the same coalesced scroll synchronization used in production.
|
||||
await page.evaluate(() => {
|
||||
const { promise, resolve } = Promise.withResolvers<void>();
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
|
||||
return promise;
|
||||
});
|
||||
expect(await page.getByRole('button', { name: 'Reload history', exact: true }).isVisible()).toBe(false);
|
||||
expect((await bufferState(page)).pulls).toBe(0);
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
it('hides Reload history while a marked incoming tab capture is pending', async () => {
|
||||
const { context, page } = await openTerminal(false);
|
||||
const incoming = `${SESSION}-incoming`;
|
||||
try {
|
||||
await page.evaluate((session) => {
|
||||
const w = window as RepairWindow;
|
||||
const app = w.app;
|
||||
app.terminal.scrollToLine(10);
|
||||
app.sessions.set(session, { id: session, mode: 'omp', status: 'idle', name: 'Incoming history' });
|
||||
app._liveOutputSinceFullPull.add(session);
|
||||
const response = Promise.withResolvers<Response>();
|
||||
const realFetch = window.fetch.bind(window);
|
||||
const terminalBuffer = 'INCOMING-HISTORY\r\n';
|
||||
w.tabLoadTest = {
|
||||
requested: false,
|
||||
release: () =>
|
||||
response.resolve(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
data: { terminalBuffer, source: 'mux-full-history', paneHistoryLines: 1, truncated: false },
|
||||
}),
|
||||
{ status: 200, headers: { 'Content-Type': 'application/json' } }
|
||||
)
|
||||
),
|
||||
selection: Promise.resolve(),
|
||||
};
|
||||
window.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(typeof input === 'string' ? input : ((input as Request).url ?? input));
|
||||
if (!url.includes(`/api/sessions/${session}/terminal`)) return realFetch(input, init);
|
||||
w.tabLoadTest!.requested = true;
|
||||
return response.promise;
|
||||
}) as typeof window.fetch;
|
||||
}, incoming);
|
||||
expect((await bufferState(page)).baseY - (await bufferState(page)).viewportY).toBeGreaterThan(5);
|
||||
await page.evaluate((session) => {
|
||||
const w = window as RepairWindow;
|
||||
w.tabLoadTest!.selection = w.app.selectSession(session);
|
||||
}, incoming);
|
||||
await page.waitForFunction((session) => {
|
||||
const w = window as RepairWindow;
|
||||
return (
|
||||
w.tabLoadTest?.requested &&
|
||||
w.app.activeSessionId === session &&
|
||||
w.app.terminalLoadStates.has(session) &&
|
||||
w.app._isLoadingBuffer
|
||||
);
|
||||
}, incoming);
|
||||
const bar = page.locator('#historyTruncationBar');
|
||||
expect(await bar.getByRole('button', { name: 'Reload history', exact: true }).count()).toBe(0);
|
||||
expect(await bar.isHidden()).toBe(true);
|
||||
await page.evaluate(async () => {
|
||||
const test = (window as RepairWindow).tabLoadTest!;
|
||||
test.release();
|
||||
await test.selection;
|
||||
});
|
||||
await page.waitForFunction((session) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
return (
|
||||
app.activeSessionId === session &&
|
||||
!app.terminalLoadStates.has(session) &&
|
||||
!app._isLoadingBuffer &&
|
||||
!app.pendingWrites.length &&
|
||||
!app._terminalWriteInFlight
|
||||
);
|
||||
}, incoming);
|
||||
expect(
|
||||
await page.evaluate(() => {
|
||||
const buffer = (window as RepairWindow).app.terminal.buffer.active;
|
||||
return buffer.getLine(0)?.translateToString(true);
|
||||
})
|
||||
).toBe('INCOMING-HISTORY');
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('holds an OMP reading row through repeated repaint history and capped live flushes', async () => {
|
||||
const { context, page } = await openTerminal(true);
|
||||
const readingRow = 'Reading tool result: src/engine.ts — preserve this row';
|
||||
try {
|
||||
const before = await page.evaluate(
|
||||
async ({ session, readingRow }) => {
|
||||
const w = window as RepairWindow;
|
||||
const app = w.app;
|
||||
const terminal = app.terminal;
|
||||
const write = async (data: string) => {
|
||||
const { promise, resolve } = Promise.withResolvers<void>();
|
||||
terminal.write(data, resolve);
|
||||
await promise;
|
||||
};
|
||||
terminal.reset();
|
||||
terminal.options.scrollback = 50_000;
|
||||
const repeated = [
|
||||
'╭──────────────────╮',
|
||||
'',
|
||||
'│ Working… │',
|
||||
'╰──────────────────╯',
|
||||
'',
|
||||
'⠋ OMP · processing',
|
||||
];
|
||||
const rows = Array.from({ length: 50_100 }, (_, i) =>
|
||||
i % 1000 === 999 ? `tool output ${'wrapped context '.repeat(18)}` : repeated[i % repeated.length]
|
||||
);
|
||||
await write(rows.join('\r\n') + '\r\n');
|
||||
terminal.scrollToLine(25_000);
|
||||
app._syncStickyScrollBaseline();
|
||||
// Cursor-addressed redraws and CSI S leave repeated TUI furniture in history.
|
||||
const repaint = repeated.map((text, row) => `\x1b[${row + 1};1H\x1b[2K${text}`).join('');
|
||||
app._onSessionTerminal({ id: session, data: `\x1b[6S${repaint}\x1b[6S${repaint}` });
|
||||
await write('');
|
||||
while (app.pendingWrites.length || app._terminalWriteInFlight) {
|
||||
const { promise, resolve } = Promise.withResolvers<void>();
|
||||
requestAnimationFrame(() => resolve());
|
||||
await promise;
|
||||
}
|
||||
// Put the distinctive tool result BELOW the three repeated anchor rows.
|
||||
const buffer = terminal.buffer.active;
|
||||
const top = buffer.viewportY;
|
||||
const snapshot = Array.from(
|
||||
{ length: buffer.length },
|
||||
(_, i) => buffer.getLine(i)?.translateToString(true) || ''
|
||||
);
|
||||
snapshot[top + 5] = readingRow;
|
||||
await write('\x1bc' + snapshot.join('\r\n'));
|
||||
terminal.scrollToLine(top);
|
||||
app._syncStickyScrollBaseline();
|
||||
const seeded = terminal.buffer.active;
|
||||
const captured = Array.from(
|
||||
{ length: seeded.length },
|
||||
(_, i) => seeded.getLine(i)?.translateToString(true) || ''
|
||||
);
|
||||
captured.splice(top + 500, 0, ...Array.from({ length: 120 }, (_, i) => `Recovered tool detail ${i}`));
|
||||
const terminalBuffer = captured.join('\r\n');
|
||||
const realFetch = window.fetch.bind(window);
|
||||
window.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(typeof input === 'string' ? input : ((input as Request).url ?? input));
|
||||
if (!url.includes(`/api/sessions/${session}/terminal`)) return realFetch(input, init);
|
||||
w.repairTest.pulls++;
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
status: 200,
|
||||
headers: new Headers(),
|
||||
json: async () => {
|
||||
app._onSessionTerminal({ id: session, data: '\r\nDownload-time output\r\n' });
|
||||
return {
|
||||
success: true,
|
||||
data: { terminalBuffer, source: 'mux-full-history', paneHistoryLines: 100_000, truncated: false },
|
||||
};
|
||||
},
|
||||
}) as unknown as Promise<Response>;
|
||||
}) as typeof window.fetch;
|
||||
app._liveOutputSinceFullPull.add(session);
|
||||
app._syncHistoryReloadAction();
|
||||
return {
|
||||
offset: captured.indexOf(readingRow) - seeded.viewportY,
|
||||
viewportY: seeded.viewportY,
|
||||
baseY: seeded.baseY,
|
||||
};
|
||||
},
|
||||
{ session: SESSION, readingRow }
|
||||
);
|
||||
const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history', exact: true });
|
||||
await button.tap();
|
||||
await waitForRepair(page);
|
||||
const measure = () =>
|
||||
page.evaluate((readingRow) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
const buffer = app.terminal.buffer.active;
|
||||
let row = -1;
|
||||
for (let i = 0; i < buffer.length; i++) {
|
||||
if (buffer.getLine(i)?.translateToString(true) === readingRow) {
|
||||
row = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { offset: row - buffer.viewportY, viewportY: buffer.viewportY, baseY: buffer.baseY };
|
||||
}, readingRow);
|
||||
const afterReplay = await measure();
|
||||
await page.evaluate((session) => {
|
||||
(window as RepairWindow).app._onSessionTerminal({ id: session, data: '\r\nPost-replay output\r\n' });
|
||||
}, SESSION);
|
||||
await waitForRepair(page);
|
||||
const afterFlush = await measure();
|
||||
expect({ before, afterReplay, afterFlush }).toEqual({
|
||||
before,
|
||||
afterReplay: { ...afterReplay, offset: before.offset },
|
||||
afterFlush: { ...afterFlush, offset: before.offset },
|
||||
});
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 120_000);
|
||||
@@ -121,6 +121,8 @@ function makeApp() {
|
||||
let resolvePull: (() => void) | null = null;
|
||||
const app = {
|
||||
activeSessionId: 's1' as string | null,
|
||||
sessions: new Map([['s1', { mode: 'omp' }]]),
|
||||
_liveOutputSinceFullPull: new Set<string>(),
|
||||
terminal: { buffer: { active: buffer } },
|
||||
// Each gesture's pull is held open until the test settles it.
|
||||
_maybeRefetchFullHistory: vi.fn(
|
||||
@@ -184,6 +186,34 @@ describe('partial-history notice: lazy reveal', () => {
|
||||
expect(loadButton(bar)?.textContent).toBe('Load full history');
|
||||
});
|
||||
|
||||
it.each([0, 200])('marked scrolling from row %s remains top-only', async (viewportY) => {
|
||||
const { app, bar, buffer, settle } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
app._liveOutputSinceFullPull.add('s1');
|
||||
buffer.viewportY = viewportY;
|
||||
app._maybeLoadMoreHistoryOnScroll(-5);
|
||||
await settle();
|
||||
expect(app._maybeRefetchFullHistory).toHaveBeenCalledTimes(viewportY === 0 ? 1 : 0);
|
||||
if (viewportY === 0) expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith();
|
||||
expect(bar.hidden).toBe(viewportY !== 0);
|
||||
});
|
||||
|
||||
it('reveals the resulting notice when a top pull grows the buffer and restores below row zero', async () => {
|
||||
const { app, bar, buffer } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
app._maybeRefetchFullHistory.mockImplementation(async () => {
|
||||
buffer.baseY += 100;
|
||||
buffer.viewportY = 100; // Recovered rows precede the old top reading position.
|
||||
});
|
||||
buffer.viewportY = 0;
|
||||
app._maybeLoadMoreHistoryOnScroll(-500);
|
||||
for (let i = 0; i < 5; i++) await Promise.resolve();
|
||||
expect(buffer.viewportY).toBe(100);
|
||||
expect(app._historyNoticeRevealedFor).toBe('s1');
|
||||
expect(bar.hidden).toBe(false);
|
||||
expect(loadButton(bar)?.textContent).toBe('Load full history');
|
||||
});
|
||||
|
||||
it('a later frame of the same gesture does not flash the pre-pull state while the pull runs', async () => {
|
||||
const { app, bar, buffer } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
|
||||
@@ -182,6 +182,45 @@ async function boot(who: Who, stored: Settings, server: Settings | null) {
|
||||
// What the server already holds for this instance: an admin has saved App Settings before.
|
||||
const SERVER: Settings = { autoNameSessions: false, workspaceHooksEnabled: true, claudeMode: 'auto' };
|
||||
|
||||
describe('the per-device History Reload Button setting', () => {
|
||||
it.each(['non-admin', 'admin', 'single-user'] as const)(
|
||||
'%s saves locally and never sends the device key',
|
||||
async (who) => {
|
||||
const { app, target, box, storedBlob } = await boot(who, { ...SERVER }, SERVER);
|
||||
target._syncHistoryReloadAction = vi.fn();
|
||||
await open_(app);
|
||||
expect(box('appSettingsHistoryReloadAction').checked).toBe(true);
|
||||
expect(app._displaySettingKeySet().has('historyReloadAction')).toBe(true);
|
||||
box('appSettingsHistoryReloadAction').checked = false;
|
||||
await app.saveAppSettings();
|
||||
expect(storedBlob().historyReloadAction).toBe(false);
|
||||
expect(target._syncHistoryReloadAction).toHaveBeenCalledOnce();
|
||||
if (who === 'non-admin') expect(target._apiPut).not.toHaveBeenCalled();
|
||||
else {
|
||||
const [path, body] = target._apiPut.mock.calls[0] as [string, Settings];
|
||||
expect(path).toBe('/api/settings');
|
||||
expect(body).not.toHaveProperty('historyReloadAction');
|
||||
expect(SettingsUpdateSchema.safeParse(body).error?.issues ?? []).toEqual([]);
|
||||
}
|
||||
await open_(app);
|
||||
expect(box('appSettingsHistoryReloadAction').checked).toBe(false);
|
||||
}
|
||||
);
|
||||
|
||||
it('preserves the local choice when another device saved a different value', async () => {
|
||||
const { app, box, storedBlob } = await boot('admin', { historyReloadAction: false }, { historyReloadAction: true });
|
||||
await open_(app);
|
||||
expect(box('appSettingsHistoryReloadAction').checked).toBe(false);
|
||||
expect(storedBlob().historyReloadAction).toBe(false);
|
||||
});
|
||||
|
||||
it('also defaults to enabled on handheld devices', async () => {
|
||||
const { app, win } = await boot('admin', {}, {});
|
||||
win.eval('MobileDetection.isHandheldDevice = () => true;');
|
||||
expect(app.getDefaultSettings().historyReloadAction).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a non-admin in multi-user mode saving App Settings', () => {
|
||||
it('keeps the per-device keys, sends no PUT, keeps the synced key at the server value, and toasts once', async () => {
|
||||
const { app, target, box, storedBlob, toasts, puts } = await boot('non-admin', { ...SERVER }, SERVER);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -250,7 +250,10 @@ describe('terminal capture deadline covers the response body', () => {
|
||||
for (const site of ['_onSessionNeedsRefresh(event = {}) {', 'async _onSessionClearTerminal(data) {']) {
|
||||
const start = app.indexOf(site);
|
||||
expect(start, `${site} not found — renamed?`).toBeGreaterThan(-1);
|
||||
const body = app.slice(start, start + 4000);
|
||||
// The whole method, not a fixed-size window: a byte count broke on an
|
||||
// unrelated comment, and a reset past it would have read as missing.
|
||||
const next = /^ {2}(?:async )?[A-Za-z_$][\w$]*\(/m.exec(app.slice(start + 1));
|
||||
const body = next ? app.slice(start, start + 1 + next.index) : app.slice(start);
|
||||
expect(body, `${site} must clear via _resetTerminalForReplay`).toContain('this._resetTerminalForReplay()');
|
||||
expect(body, `${site} hand-rolled a clear again`).not.toContain('this.terminal.clear()');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* Live flushes at the scrollback cap must preserve the row being read, not its
|
||||
* absolute buffer index. Use real asynchronous xterm parsing so markers track
|
||||
* circular-buffer trimming before the mixin restores the viewport (#814).
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import xtermHeadless, { type Terminal as HeadlessTerminal } from '@xterm/headless';
|
||||
|
||||
const { Terminal } = xtermHeadless as unknown as {
|
||||
Terminal: new (opts: Record<string, unknown>) => HeadlessTerminal;
|
||||
};
|
||||
|
||||
const read = (rel: string) => readFileSync(resolve(import.meta.dirname, '..', rel), 'utf8');
|
||||
const write = (terminal: HeadlessTerminal, data: string) => new Promise<void>((done) => terminal.write(data, done));
|
||||
const topRow = (terminal: HeadlessTerminal) => {
|
||||
const buffer = terminal.buffer.active;
|
||||
return buffer.getLine(buffer.viewportY)?.translateToString(true);
|
||||
};
|
||||
|
||||
function loadHarness(terminal: HeadlessTerminal) {
|
||||
const CodemanApp = function CodemanApp(this: unknown) {};
|
||||
const context = vm.createContext({
|
||||
CodemanApp,
|
||||
window: {},
|
||||
globalThis: {},
|
||||
document: { getElementById: () => null, querySelector: () => null },
|
||||
console,
|
||||
MobileDetection: { isTouchDevice: () => false, getDeviceType: () => 'desktop' },
|
||||
Object,
|
||||
performance,
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
});
|
||||
vm.runInContext(read('src/web/public/constants.js'), context, { filename: 'constants.js' });
|
||||
vm.runInContext(read('src/web/public/terminal-ui.js'), context, { filename: 'terminal-ui.js' });
|
||||
|
||||
const app = new (CodemanApp as unknown as new () => Record<string, any>)();
|
||||
Object.assign(app, {
|
||||
terminal,
|
||||
pendingWrites: [],
|
||||
sessions: new Map([['reading', { mode: 'claude' }]]),
|
||||
activeSessionId: 'reading',
|
||||
_isLoadingBuffer: false,
|
||||
_wasAtBottomBeforeWrite: false,
|
||||
_localEchoOverlay: null,
|
||||
isTerminalAtBottom: () => terminal.buffer.active.viewportY === terminal.buffer.active.baseY,
|
||||
_scheduleTerminalWriteFlush: () => {},
|
||||
_noteMobileImeAuthoritativeOutput: () => {},
|
||||
_hasRecentUserScrollUp: () => false,
|
||||
_syncHistoryReloadAction: () => {},
|
||||
});
|
||||
return app;
|
||||
}
|
||||
|
||||
async function flushAtScrollbackCap(markersEnabled: boolean) {
|
||||
const terminal = new Terminal({ cols: 80, rows: 10, scrollback: 100, allowProposedApi: true });
|
||||
try {
|
||||
// Hide only the marker API for the negative control; writes, buffer trims,
|
||||
// scrolling, and _restoreTerminalViewport remain the real implementations.
|
||||
if (!markersEnabled) Object.defineProperty(terminal, 'registerMarker', { value: undefined });
|
||||
const app = loadHarness(terminal);
|
||||
await write(terminal, Array.from({ length: 200 }, (_, i) => `line ${i}\r\n`).join(''));
|
||||
expect(terminal.buffer.active.baseY).toBe(100);
|
||||
|
||||
const buffer = terminal.buffer.active;
|
||||
let readingRow = -1;
|
||||
for (let row = 0; row < buffer.length; row++) {
|
||||
if (buffer.getLine(row)?.translateToString(true) === 'line 140') {
|
||||
readingRow = row;
|
||||
break;
|
||||
}
|
||||
}
|
||||
expect(readingRow).toBeGreaterThanOrEqual(0);
|
||||
terminal.scrollToLine(readingRow);
|
||||
expect(topRow(terminal)).toBe('line 140');
|
||||
expect(app.isTerminalAtBottom()).toBe(false);
|
||||
|
||||
for (let flush = 0; flush < 5; flush++) {
|
||||
app.pendingWrites.push(Array.from({ length: 4 }, (_, i) => `line ${200 + flush * 4 + i}\r\n`).join(''));
|
||||
app.flushPendingWrites();
|
||||
// This barrier runs after the flush's write callback, including its
|
||||
// viewport restoration. No wall-clock delay stands in for parsing.
|
||||
await write(terminal, '');
|
||||
expect(app._terminalWriteInFlight).toBe(false);
|
||||
}
|
||||
return topRow(terminal);
|
||||
} finally {
|
||||
terminal.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
describe('live terminal viewport at the scrollback cap', () => {
|
||||
it('keeps line 140 visible across five flushes using xterm markers', async () => {
|
||||
expect(await flushAtScrollbackCap(true)).toBe('line 140');
|
||||
});
|
||||
|
||||
it('discriminates against absolute-index restoration without markers', async () => {
|
||||
const row = await flushAtScrollbackCap(false);
|
||||
expect(row).not.toBe('line 140');
|
||||
expect(row).toBe('line 160');
|
||||
});
|
||||
|
||||
// ESC[3J (kept by the narrow and middle strips) erases scrollback and disposes
|
||||
// the marker the same way a trim does; the reader must keep their row, not
|
||||
// land on row 0.
|
||||
it.each([true, false])(
|
||||
'keeps the reader on their row when one flush clears scrollback and reprints it (markers: %s)',
|
||||
async (markersEnabled) => {
|
||||
const terminal = new Terminal({ cols: 80, rows: 10, scrollback: 1000, allowProposedApi: true });
|
||||
try {
|
||||
if (!markersEnabled) Object.defineProperty(terminal, 'registerMarker', { value: undefined });
|
||||
const app = loadHarness(terminal);
|
||||
const history = Array.from({ length: 200 }, (_, i) => `line ${i}\r\n`).join('');
|
||||
await write(terminal, history);
|
||||
terminal.scrollToLine(100);
|
||||
expect(topRow(terminal)).toBe('line 100');
|
||||
expect(app.isTerminalAtBottom()).toBe(false);
|
||||
app.pendingWrites.push(`\x1b[H\x1b[2J\x1b[3J${history}`);
|
||||
app.flushPendingWrites();
|
||||
await write(terminal, '');
|
||||
expect(app._terminalWriteInFlight).toBe(false);
|
||||
expect(topRow(terminal)).toBe('line 100');
|
||||
} finally {
|
||||
terminal.dispose();
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user