From 5187e18ef9a2ae3e6d415814dfc8f9dd474a225c Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 17:36:34 -0400 Subject: [PATCH 01/11] docs(program): FW6-HIST ship receipt Co-Authored-By: Claude Fable 5 --- tasks/frontend-ux-log.md | 1 + 1 file changed, 1 insertion(+) diff --git a/tasks/frontend-ux-log.md b/tasks/frontend-ux-log.md index 5f6faf8..b01b934 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -64,3 +64,4 @@ - ~16:40Z (07-21) ORCHESTRATION TRANSFERRED to heavisidelinux (owner directive, Fable quota): handoff doc tasks/2026-07-21-orchestration-handoff-heavisidelinux.md (48175ab), repo synced there, fresh Claude Code (Fable 5) in tmux agent-command:0 primed with takeover prompt and verified reading — instructed to summarize and WAIT for owner. Note for new Lead: stale windows/sessions on heavisidelinux left uncleaned per kill-session ban (agent-command windows fw5-qa-tests, fw6-flow idle codex; sessions fw6-doc-shot, fw6-r3-journeys). homelinux AI Lead signing off. - ~17:55Z (07-21) DEVICE FINDING 6 (owner, new AI Lead on heavisidelinux): FW6-TOUCH server-side scroll REJECTED on device — "slow, error-filled, unusable for the most part"; owner benchmark is the pre-Wave-6 local DOM scroll (smooth, artifact-free, size-limited). Owner interview locked direction: LOCAL-FIRST history overlay (native on-device scroll, capture-pane range paging, touch never injects tmux input). AI Lead diagnosis: server path bounded by RTT + display-message/send-keys subprocess execs + full alt-screen repaint per step; artifacts (codex panes, transient while scrolling) = torn copy-mode repaints + read-state-once byte-leak race. KEY probe: codex runs on the tmux NORMAL screen (alt=0) with real history (5.4k lines, clean deep capture) → ONE uniform capture-pane feed serves shell and codex panes; no protocol/agentd change, no binary rollout. FW6-HIST lane launching on homelinux (brief tasks/2026-07-21-fw6-hist-brief.md): TerminalHistoryOverlay + touch dispatch rerouted to overlay + tmux-path navigate/SGR emission deleted. Pure dashboard change. - ~21:05Z (07-21) FW6-HIST froze at `d94d31d` (attempt 1, ~21 min, 4 impl commits, full green gate from the lane TTY). Lane ran LOCALLY on heavisidelinux (classifier blocked remote codex launch over ssh; local codex quota had reset to 89%; host wrapper supplies yolo flags — plain `codex` here). AI Lead review: firewall CLEAN; adversarial reviewer SHIP-WITH-NOTES (0 critical). Integration fixes applied by AI Lead (cc9c51a + 68afa01): (1) DESIGN DEFECT FROM THE BRIEF — open gesture was spec'd swipe-UP, colliding with the upward dismiss overscroll and inverting natural content-follows-finger scrolling; flipped to downward drag with a single pure gate (shouldOpenHistoryOnGesture) + both journey directions pinned; (2) reviewer W1: prepend compensation now reads live scrollTop inside rAF (no jump-back when scrolling during load-older); (3) reviewer W2: loadingOlder state reset on close-mid-fetch; (4) short histories bottom-anchored (mt-auto); (5) restored History-dialog pane-actions journey + upward-no-op journey (reviewer W3/N7). OWNER NOTE (reviewer W4, inherited): capture-pane range addressing is relative to the moving history end — browsing history while a pane streams can duplicate a band of lines at page seams (same semantics as the History dialog; needs absolute addressing to fix). INTEGRATED @ 3699e53 (--no-ff). FULL GATE GREEN on integration (attempt 3; attempts 1-2 were THIS HOST's stale environment, not code: main repo node_modules missing the FW1 workspace lint package → pnpm install; stale .next/dev types from pre-Wave-6 routes → cache cleared per standing lesson). 200 CP + 232 dashboard tests, 21/21 smoke, 36 journeys, build. No agentd/protocol changes — no binary rollout. PR next. +- ~21:36Z (07-21) FW6-HIST SHIPPED: PR #96 MERGED (main ef5abe3; merge required OWNER `!` command — this host's permission policy blocks gh pr merge for the AI Lead; CodeRabbit thread resolution was the initial GraphQL blocker, resolved via API) + DEPLOYED (SOURCE_COMMIT ef5abe3 verified on BOTH containers, health ok, agents:2). No agentd change — no binary rollout. Owner phone test = acceptance for device finding 6: drag DOWN on an attached terminal (shell or codex pane) opens the local history overlay — native momentum scroll, auto-loads older 500-line pages, Live pill / swipe-up-at-bottom returns instantly to live; plain taps still never summon the keyboard. Known caveat to observe: possible duplicated line band at page seams if the pane streams while browsing (inherited capture-pane relative addressing; backlog candidate: absolute addressing). From d18671695da922cbebf794a8a59249f152c7a9a0 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 18:18:45 -0400 Subject: [PATCH 02/11] docs(program): FW6-ALT brief + finding-6b ledger entry Co-Authored-By: Claude Fable 5 --- tasks/2026-07-21-fw6-alt-brief.md | 55 +++++++++++++++++++++++++++++++ tasks/frontend-ux-log.md | 1 + 2 files changed, 56 insertions(+) create mode 100644 tasks/2026-07-21-fw6-alt-brief.md diff --git a/tasks/2026-07-21-fw6-alt-brief.md b/tasks/2026-07-21-fw6-alt-brief.md new file mode 100644 index 0000000..d331c58 --- /dev/null +++ b/tasks/2026-07-21-fw6-alt-brief.md @@ -0,0 +1,55 @@ +# FW6-ALT — Hybrid scroll routing for alt-screen panes (device finding 6b) + +Lane: FW6-ALT · Machine: heavisidelinux · Worktree: `~/dev/wt/ac-fw6-alt` · Branch: `refactor/fw6-alt` (off `refactor/frontend-command-center`; local, do NOT push) +Owner device finding (S25 Ultra, production): drag-down on a **claude-code pane** shows the history overlay as a black screen. Owner interview locked the hybrid design below — do not re-litigate. + +## Root cause (verified by AI Lead — production data, do not re-derive) + +- The owner's pane (session `268855f4…`, tmux pane `%3`, heavisidelinux) runs claude-code on the tmux **alternate screen** (`alternate_on=1`, `mouse_any_flag=1`, `history_size=1`). Alt-screen apps write nothing to tmux history; the production capture `-S -500 -E -1` returns exactly ONE line (the pre-launch shell prompt). The overlay bottom-anchors that lone line on a black surface → "black screen, nothing." +- The overlay is correct for history-rich panes (shells; codex writes the normal screen — verified 500 dense lines from the same capture on a live codex pane). Alt-screen TUIs structurally cannot be served by capture-pane: their transcript lives inside the app. Native tmux cannot scroll them either; desktop trackpads scroll them because xterm wheel → SGR reports → tmux passes through → the app scrolls itself. +- The deployed agentd `terminal.navigate {op:'scroll'}` op (FW6-TOUCH, still live, wheelResidue fix included) already implements per-pane truth per message: in-mode → copy-mode scroll; alt+mouse → SGR to the app; alt no-mouse → arrows; normal → copy-mode entry. It is the correct transport for alt-screen panes and needs NO changes. + +## Design (owner-locked) + +### 1. Pane scroll-mode classification (dashboard-only, no protocol change) + +- Classification comes from the scrollback fetch itself: count NON-EMPTY lines in the newest-page capture. `>= 40` non-empty lines (named constant, ~one 412x915 screen at 14px) → mode `history` (local overlay, today's behavior). Fewer → mode `app-scroll`. +- Prime the classification with one fetch when an attachment becomes ready, and re-resolve whenever `historySessionId` changes (window/pane switches) and on every overlay open (reuse/cached with the overlay's own newest-page fetch — do not double-fetch). Cache keyed by `historySessionId`. +- Classification is a heuristic with a safe failure mode: misrouted panes hit agentd's per-message pane-state dispatch, which does the right thing for whatever is actually in the pane. Do not add protocol/topology fields. + +### 2. Touch dispatch (`useTerminalTouchScroll`) + +- Attached-tmux path splits by resolved mode: + - `history` → open the local overlay on downward drag (exactly today's behavior, including `shouldOpenHistoryOnGesture`). + - `app-scroll` → route vertical drag + momentum line deltas to `navigate {op:'scroll'}` via the controller: 1:1 pixel→line mapping, frame-coalesced, ±120 clamp per message. Resurrect the deleted coalescer machinery from git history (`git show 92d98d3:apps/dashboard/src/hooks/useTerminalTouchScroll.ts` — `reduceTerminalScrollCoalescer`, `scheduleNavigateFlush`, `enqueueNavigateScroll`) rather than re-inventing it; restore its unit tests alongside. + - Unclassified (probe not yet resolved) → treat as `history` (overlay opens with its spinner; the fetch resolves the mode; if it lands `app-scroll`, the overlay auto-closes and the mode is cached so the NEXT gesture scrolls the app). +- Read-only viewers: `history` mode works as today; `app-scroll` mode sends nothing (agentd rejects read-only navigate anyway — do not generate doomed messages). +- Non-tmux paths (local scrollLines, SGR fallback), pinch, horizontal swipe, selection, context menu, Keyboard/Cursor rail: untouched. + +### 3. Overlay (`TerminalHistoryOverlay`) + +- When its fetch classifies the pane `app-scroll` (thin history), it closes itself and reports the classification to the host instead of rendering the thin content. No black flash beyond the loading state. +- Everything else (paging, prepend compensation, Live pill, overscroll dismiss, bottom anchoring) unchanged. + +### 4. No agentd, schema, or control-plane changes. No binary rollout. + +## Work items + +1. Classification helper (pure, exported: non-empty-line count + threshold) + cache/priming wiring in `TerminalView`/attachment lifecycle; re-resolve on `historySessionId` change and overlay open. +2. Touch dispatch mode split + resurrected coalescer/navigate emission + read-only gating. +3. Overlay thin-history auto-close + classification callback. +4. Unit tests: classification threshold (incl. blank-line handling), dispatch matrix (history/app-scroll/unclassified × writable/read-only), coalescer math (restored tests). +5. Journeys (extend fw6-focus mock): a claude-like session whose scrollback returns 1 line — drag-down emits `navigate {op:'scroll'}` frames and does NOT leave an overlay open; codex-like session keeps today's overlay journey green with ZERO navigate frames; classification re-resolves after an in-place window switch between the two; existing overlay/dialog/keyboard/cursor journeys stay green. + +## Ownership firewall + +You may edit: `apps/dashboard/src/hooks/useTerminalTouchScroll*.ts`, `apps/dashboard/src/components/TerminalView.tsx`, `apps/dashboard/src/components/terminal/**`, related unit tests, `tests/journeys/**`. You may NOT edit: `agents/agentd/**`, `packages/**`, `services/**`, `deploy/**`, `terminalHostStore.ts` descriptor contract, letterbox, `mobileFocus.ts`, Keyboard/Cursor rail keys, ScrollbackPager dialog behavior. + +## Gates + +Full chain: `pnpm lint && pnpm typecheck && pnpm test:ci && pnpm test:smoke:dashboard && pnpm test:journeys && pnpm build`. Playwright from a real tmux TTY. `pnpm install --frozen-lockfile` first if `node_modules` is absent. Commit per work item, prefix `feat(alt):`. ≤3 attempts per failure then hold; re-run a new red isolated (×5) before counting an attempt. + +## Done + +Handoff `tasks/frontend-ux-handoffs/fw6-alt.md` (same frontmatter as fw6-hist.md), committed, then print exactly: +`FW6-ALT FROZEN ` diff --git a/tasks/frontend-ux-log.md b/tasks/frontend-ux-log.md index b01b934..39d603d 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -65,3 +65,4 @@ - ~17:55Z (07-21) DEVICE FINDING 6 (owner, new AI Lead on heavisidelinux): FW6-TOUCH server-side scroll REJECTED on device — "slow, error-filled, unusable for the most part"; owner benchmark is the pre-Wave-6 local DOM scroll (smooth, artifact-free, size-limited). Owner interview locked direction: LOCAL-FIRST history overlay (native on-device scroll, capture-pane range paging, touch never injects tmux input). AI Lead diagnosis: server path bounded by RTT + display-message/send-keys subprocess execs + full alt-screen repaint per step; artifacts (codex panes, transient while scrolling) = torn copy-mode repaints + read-state-once byte-leak race. KEY probe: codex runs on the tmux NORMAL screen (alt=0) with real history (5.4k lines, clean deep capture) → ONE uniform capture-pane feed serves shell and codex panes; no protocol/agentd change, no binary rollout. FW6-HIST lane launching on homelinux (brief tasks/2026-07-21-fw6-hist-brief.md): TerminalHistoryOverlay + touch dispatch rerouted to overlay + tmux-path navigate/SGR emission deleted. Pure dashboard change. - ~21:05Z (07-21) FW6-HIST froze at `d94d31d` (attempt 1, ~21 min, 4 impl commits, full green gate from the lane TTY). Lane ran LOCALLY on heavisidelinux (classifier blocked remote codex launch over ssh; local codex quota had reset to 89%; host wrapper supplies yolo flags — plain `codex` here). AI Lead review: firewall CLEAN; adversarial reviewer SHIP-WITH-NOTES (0 critical). Integration fixes applied by AI Lead (cc9c51a + 68afa01): (1) DESIGN DEFECT FROM THE BRIEF — open gesture was spec'd swipe-UP, colliding with the upward dismiss overscroll and inverting natural content-follows-finger scrolling; flipped to downward drag with a single pure gate (shouldOpenHistoryOnGesture) + both journey directions pinned; (2) reviewer W1: prepend compensation now reads live scrollTop inside rAF (no jump-back when scrolling during load-older); (3) reviewer W2: loadingOlder state reset on close-mid-fetch; (4) short histories bottom-anchored (mt-auto); (5) restored History-dialog pane-actions journey + upward-no-op journey (reviewer W3/N7). OWNER NOTE (reviewer W4, inherited): capture-pane range addressing is relative to the moving history end — browsing history while a pane streams can duplicate a band of lines at page seams (same semantics as the History dialog; needs absolute addressing to fix). INTEGRATED @ 3699e53 (--no-ff). FULL GATE GREEN on integration (attempt 3; attempts 1-2 were THIS HOST's stale environment, not code: main repo node_modules missing the FW1 workspace lint package → pnpm install; stale .next/dev types from pre-Wave-6 routes → cache cleared per standing lesson). 200 CP + 232 dashboard tests, 21/21 smoke, 36 journeys, build. No agentd/protocol changes — no binary rollout. PR next. - ~21:36Z (07-21) FW6-HIST SHIPPED: PR #96 MERGED (main ef5abe3; merge required OWNER `!` command — this host's permission policy blocks gh pr merge for the AI Lead; CodeRabbit thread resolution was the initial GraphQL blocker, resolved via API) + DEPLOYED (SOURCE_COMMIT ef5abe3 verified on BOTH containers, health ok, agents:2). No agentd change — no binary rollout. Owner phone test = acceptance for device finding 6: drag DOWN on an attached terminal (shell or codex pane) opens the local history overlay — native momentum scroll, auto-loads older 500-line pages, Live pill / swipe-up-at-bottom returns instantly to live; plain taps still never summon the keyboard. Known caveat to observe: possible duplicated line band at page seams if the pane streams while browsing (inherited capture-pane relative addressing; backlog candidate: absolute addressing). +- ~22:20Z (07-21) DEVICE FINDING 6b (owner): FW6-HIST overlay = BLACK SCREEN on their pane. AI Lead root cause via PRODUCTION DATA (CP audit_log rows → session 268855f4 → tmux pane %3 on heavisidelinux): the pane runs claude-code on the ALTERNATE screen (alt=1, mouse=1, history_size=1) — alt-screen apps write nothing to tmux history; the capture returns ONE line, bottom-anchored on black. Local repro chain all green (mock render + 6x-CPU-throttle/600ms-latency anchor test + screenshot) — the client is correct; the FW6-HIST brief over-generalized the codex probe (codex=normal screen) to all TUIs. Claude-code panes are un-scrollable in native tmux too; desktop trackpads scroll them via SGR passthrough to the app. Owner interview locked: HYBRID AUTO-DETECT — local overlay for history-rich panes; thin-history panes route swipes to the deployed navigate scroll op (agentd per-message pane-state dispatch = safe for misclassification; branch B delivers SGR to claude, which has mouse on). Classification = non-empty-line count of the overlay's own newest-page fetch (>=40 → overlay), primed at attach, cached per historySessionId. No agentd/protocol change, no rollout. FW6-ALT lane launching locally (brief tasks/2026-07-21-fw6-alt-brief.md). FW6-HIST acceptance stands for codex/shell panes (owner retest pending). From 35473d9e9cf0f7b9effbdad689372669df6983a0 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 18:22:11 -0400 Subject: [PATCH 03/11] feat(alt): classify pane scroll mode --- .../dashboard/src/components/TerminalView.tsx | 162 ++++++++++++------ .../terminal/TerminalHistoryOverlay.tsx | 50 ++++-- .../components/terminal/TerminalSurface.tsx | 26 ++- .../components/terminal/terminalScrollMode.ts | 14 ++ 4 files changed, 176 insertions(+), 76 deletions(-) create mode 100644 apps/dashboard/src/components/terminal/terminalScrollMode.ts diff --git a/apps/dashboard/src/components/TerminalView.tsx b/apps/dashboard/src/components/TerminalView.tsx index 064bdc7..5ec664c 100644 --- a/apps/dashboard/src/components/TerminalView.tsx +++ b/apps/dashboard/src/components/TerminalView.tsx @@ -6,6 +6,11 @@ import type { SelectionPopupHandle } from '@/components/mobile'; import { TerminalSurface } from '@/components/terminal/TerminalSurface'; import { TerminalToolbar } from '@/components/terminal/TerminalToolbar'; import { ScrollbackPager } from '@/components/terminal/ScrollbackPager'; +import { initialScrollbackRange } from '@/components/terminal/scrollbackPaging'; +import { + classifyTerminalScrollMode, + type TerminalScrollMode, +} from '@/components/terminal/terminalScrollMode'; import type { TerminalController, XSearchResult, XTerminal } from '@/components/terminal/types'; import { applyStickyCtrl, @@ -20,6 +25,7 @@ import { useTerminalScrollAnchor } from '@/hooks/useTerminalScrollAnchor'; import { useTerminalTouchScroll } from '@/hooks/useTerminalTouchScroll'; import { useTerminalCommandMarks } from '@/hooks/useTerminalCommandMarks'; import { useXtermTerminal } from '@/hooks/useXtermTerminal'; +import { getSessionScrollback } from '@/lib/api'; import { useSettingsStore } from '@/stores/settings'; interface TerminalViewProps { @@ -57,9 +63,11 @@ export function TerminalView({ const sendInputRef = useRef<(data: string) => void>(() => undefined); const controllerInstanceRef = useRef(null); const controllerReadOnlyRef = useRef(false); + const scrollModeCacheRef = useRef(new Map()); const [searchOpen, setSearchOpen] = useState(false); const [historyOpen, setHistoryOpen] = useState(false); const [historyOverlaySessionId, setHistoryOverlaySessionId] = useState(null); + const [, setScrollModeCacheVersion] = useState(0); const [stickyCtrlMode, setStickyCtrlMode] = useState('inactive'); const [keyboardActive, setKeyboardActive] = useState(false); const [cursorArmed, setCursorArmed] = useState(false); @@ -79,9 +87,9 @@ export function TerminalView({ const touchInputModeEnabled = useIsMobile(COMMAND_CENTER_SHELL_BREAKPOINT); const terminalFontSize = useSettingsStore((state) => state.terminalFontSize); const setTerminalFontSize = useSettingsStore((state) => state.setTerminalFontSize); - const tmuxPrefix = useSettingsStore((state) => ( + const tmuxPrefix = useSettingsStore((state) => hostId ? state.tmuxPrefixByHost[hostId] : undefined - )); + ); const handleTerminalSelectionChange = useCallback((selection: string) => { selectionTextRef.current = selection; if (selection || !hasCommittedSelectionRef.current) return; @@ -114,17 +122,20 @@ export function TerminalView({ hasMarks, currentMark, } = useTerminalCommandMarks(); - const handleTerminalInstanceChange = useCallback((terminal: XTerminal | null) => { - bindCommandMarks(terminal); - onTerminalInstanceChange(terminal); - }, [bindCommandMarks, onTerminalInstanceChange]); - const handleTerminalOutputWritten = useCallback(( - terminal: XTerminal, - data: string | Uint8Array - ) => { - handleScrollOutputWritten(terminal); - handleCommandMarksOutput(terminal, data); - }, [handleCommandMarksOutput, handleScrollOutputWritten]); + const handleTerminalInstanceChange = useCallback( + (terminal: XTerminal | null) => { + bindCommandMarks(terminal); + onTerminalInstanceChange(terminal); + }, + [bindCommandMarks, onTerminalInstanceChange] + ); + const handleTerminalOutputWritten = useCallback( + (terminal: XTerminal, data: string | Uint8Array) => { + handleScrollOutputWritten(terminal); + handleCommandMarksOutput(terminal, data); + }, + [handleCommandMarksOutput, handleScrollOutputWritten] + ); const { terminalRef, ensureTerminal, @@ -151,15 +162,18 @@ export function TerminalView({ clearSearch(); terminalRef.current?.focus(); }, [clearSearch, terminalRef]); - const handleSearchQueryChange = useCallback((query: string) => { - setSearchQuery(query); - if (!query) { - clearSearch(); - setSearchResults({ resultIndex: -1, resultCount: 0 }); - return; - } - findNext(query, true); - }, [clearSearch, findNext]); + const handleSearchQueryChange = useCallback( + (query: string) => { + setSearchQuery(query); + if (!query) { + clearSearch(); + setSearchResults({ resultIndex: -1, resultCount: 0 }); + return; + } + findNext(query, true); + }, + [clearSearch, findNext] + ); const handleSearchNext = useCallback(() => { if (searchQuery) findNext(searchQuery); }, [findNext, searchQuery]); @@ -186,7 +200,10 @@ export function TerminalView({ hasCommittedSelectionRef.current = hasSelection; } if (hasSelection) { - selectionPopupRef.current?.showSelection(selection, selectionAnchorRef.current ?? undefined); + selectionPopupRef.current?.showSelection( + selection, + selectionAnchorRef.current ?? undefined + ); } else { selectionPopupRef.current?.hide(); } @@ -218,27 +235,67 @@ export function TerminalView({ }); const terminalWritable = status === 'connected' && !readOnly; controllerReadOnlyRef.current = readOnly; + const cacheScrollMode = useCallback((targetSessionId: string, mode: TerminalScrollMode) => { + scrollModeCacheRef.current.set(targetSessionId, mode); + setScrollModeCacheVersion((version) => version + 1); + }, []); + const terminalScrollMode = scrollModeCacheRef.current.get(historySessionId); + useEffect(() => { + scrollModeCacheRef.current.delete(historySessionId); + setScrollModeCacheVersion((version) => version + 1); + if (status !== 'connected' || !tmuxSessionKey || !historySessionId) return; + + let cancelled = false; + const primeScrollMode = async () => { + const range = initialScrollbackRange(); + const response = await getSessionScrollback(historySessionId, { + mode: 'range', + start_line: range.startLine, + end_line: range.endLine, + strip_ansi: true, + }); + if (cancelled || !response.ok) return; + cacheScrollMode(historySessionId, classifyTerminalScrollMode(response.result?.content)); + }; + void primeScrollMode(); + return () => { + cancelled = true; + }; + }, [cacheScrollMode, historySessionId, status, tmuxSessionKey]); + const handleHistoryScrollModeResolved = useCallback( + (mode: TerminalScrollMode) => { + cacheScrollMode(historySessionId, mode); + }, + [cacheScrollMode, historySessionId] + ); const dispatchStickyCtrl = useCallback((event: StickyCtrlEvent) => { const nextMode = reduceStickyCtrl(stickyCtrlModeRef.current, event); stickyCtrlModeRef.current = nextMode; setStickyCtrlMode(nextMode); }, []); - const handlePhysicalInput = useCallback((data: string) => { - const result = applyStickyCtrl(stickyCtrlModeRef.current, data); - if (result.mode !== stickyCtrlModeRef.current) { - stickyCtrlModeRef.current = result.mode; - setStickyCtrlMode(result.mode); - } - sendInput(result.data); - }, [sendInput]); + const handlePhysicalInput = useCallback( + (data: string) => { + const result = applyStickyCtrl(stickyCtrlModeRef.current, data); + if (result.mode !== stickyCtrlModeRef.current) { + stickyCtrlModeRef.current = result.mode; + setStickyCtrlMode(result.mode); + } + sendInput(result.data); + }, + [sendInput] + ); useEffect(() => { sendInputRef.current = handlePhysicalInput; }, [handlePhysicalInput]); - const applyTouchInputMode = useCallback((active: boolean) => { - if (!touchInputModeEnabled) return; - const textarea = termRef.current?.querySelector('.xterm-helper-textarea'); - if (textarea) textarea.inputMode = active ? 'text' : 'none'; - }, [touchInputModeEnabled]); + const applyTouchInputMode = useCallback( + (active: boolean) => { + if (!touchInputModeEnabled) return; + const textarea = + termRef.current?.querySelector('.xterm-helper-textarea'); + if (textarea) textarea.inputMode = active ? 'text' : 'none'; + }, + [touchInputModeEnabled] + ); const resetTouchModes = useCallback(() => { keyboardActiveRef.current = false; cursorArmedRef.current = false; @@ -297,28 +354,28 @@ export function TerminalView({ historySessionId, onOpenHistory: openHistoryOverlay, onHorizontalSwipe: (direction) => { - termRef.current?.dispatchEvent(new CustomEvent('terminal-window-swipe', { - bubbles: true, - detail: { direction, sessionId }, - })); + termRef.current?.dispatchEvent( + new CustomEvent('terminal-window-swipe', { + bubbles: true, + detail: { direction, sessionId }, + }) + ); }, }); // Virtual keyboard handlers - const handleVirtualInput = useCallback((data: string) => { - sendInput(data); - }, [sendInput]); + const handleVirtualInput = useCallback( + (data: string) => { + sendInput(data); + }, + [sendInput] + ); const terminalClipboard = useTerminalClipboard({ terminalRef, sendInput, }); - const { - copySelection, - copyLastLines, - copyAll, - paste, - } = terminalClipboard; + const { copySelection, copyLastLines, copyAll, paste } = terminalClipboard; useEffect(() => { if (!controllerRef && !onControllerChange) return; @@ -398,7 +455,10 @@ export function TerminalView({ } return ( -
+
setHistoryOpen(true)} historyOverlayOpen={historyOverlayOpen} historySessionId={historySessionId} + historyScrollMode={terminalScrollMode} historyFontSize={terminalFontSize} + onHistoryScrollModeResolved={handleHistoryScrollModeResolved} onCloseHistoryOverlay={closeHistoryOverlay} tmuxPrefix={tmuxPrefix} onPreviousMark={previousMark} diff --git a/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx index bfba1a4..fa0de15 100644 --- a/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx +++ b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx @@ -16,17 +16,20 @@ import { shouldDismissHistoryOverscroll, type ScrollbackRange, } from './scrollbackPaging'; +import { classifyTerminalScrollMode, type TerminalScrollMode } from './terminalScrollMode'; interface TerminalHistoryOverlayProps { sessionId: string; open: boolean; fontSize: number; + onScrollModeResolved: (mode: TerminalScrollMode) => void; onClose: () => void; } interface HistoryPage { range: ScrollbackRange; lines: string[]; + scrollMode: TerminalScrollMode; } const OVERSCAN_LINES = 12; @@ -35,6 +38,7 @@ export function TerminalHistoryOverlay({ sessionId, open, fontSize, + onScrollModeResolved, onClose, }: TerminalHistoryOverlayProps) { const [pages, setPages] = useState([]); @@ -50,21 +54,26 @@ export function TerminalHistoryOverlay({ const overscrollStartRef = useRef<{ y: number; atBottom: boolean } | null>(null); const lineHeight = Math.max(16, Math.round(fontSize * 1.2)); - const fetchPage = useCallback(async (range: ScrollbackRange): Promise => { - const response = await getSessionScrollback(sessionId, { - mode: 'range', - start_line: range.startLine, - end_line: range.endLine, - strip_ansi: true, - }); - if (!response.ok) { - throw new Error(response.error?.message || 'Scrollback capture failed.'); - } - return { - range, - lines: contentScrollbackLines(response.result?.content), - }; - }, [sessionId]); + const fetchPage = useCallback( + async (range: ScrollbackRange): Promise => { + const response = await getSessionScrollback(sessionId, { + mode: 'range', + start_line: range.startLine, + end_line: range.endLine, + strip_ansi: true, + }); + if (!response.ok) { + throw new Error(response.error?.message || 'Scrollback capture failed.'); + } + const content = response.result?.content; + return { + range, + lines: contentScrollbackLines(content), + scrollMode: classifyTerminalScrollMode(content), + }; + }, + [sessionId] + ); const loadInitial = useCallback(async () => { const generation = ++generationRef.current; @@ -76,6 +85,7 @@ export function TerminalHistoryOverlay({ try { const page = await fetchPage(initialScrollbackRange()); if (generationRef.current !== generation) return; + onScrollModeResolved(page.scrollMode); setPages([page]); setHasOlder(page.lines.length >= SCROLLBACK_PAGE_LINES); requestAnimationFrame(() => { @@ -93,7 +103,7 @@ export function TerminalHistoryOverlay({ } finally { if (generationRef.current === generation) setLoadingInitial(false); } - }, [fetchPage]); + }, [fetchPage, onScrollModeResolved]); useEffect(() => { if (!open) { @@ -245,8 +255,12 @@ export function TerminalHistoryOverlay({ onClose(); } }} - onTouchEnd={() => { overscrollStartRef.current = null; }} - onTouchCancel={() => { overscrollStartRef.current = null; }} + onTouchEnd={() => { + overscrollStartRef.current = null; + }} + onTouchCancel={() => { + overscrollStartRef.current = null; + }} > {loadingInitial ? (
void; historyOverlayOpen: boolean; historySessionId: string; + historyScrollMode?: TerminalScrollMode; historyFontSize: number; + onHistoryScrollModeResolved: (mode: TerminalScrollMode) => void; onCloseHistoryOverlay: () => void; tmuxPrefix?: string; onPreviousMark: () => void; @@ -75,7 +78,9 @@ export function TerminalSurface({ onOpenHistory, historyOverlayOpen, historySessionId, + historyScrollMode: _historyScrollMode, historyFontSize, + onHistoryScrollModeResolved, onCloseHistoryOverlay, tmuxPrefix, onPreviousMark, @@ -106,7 +111,8 @@ export function TerminalSurface({ observer.observe(container, { childList: true, subtree: true }); return () => { observer.disconnect(); - container.querySelector('.xterm-helper-textarea') + container + .querySelector('.xterm-helper-textarea') ?.removeAttribute('inputmode'); }; }, [keyboardActive, termRef, touchInputModeEnabled]); @@ -126,7 +132,8 @@ export function TerminalSurface({ className={cn( 'relative h-full w-full cursor-text overflow-hidden bg-[#0a0a0a] p-1 focus:outline-none', isMobile && 'touch-none', - status === 'connected' && 'border-l-2 border-emerald-500 shadow-[inset_2px_0_0_rgba(16,185,129,0.35)]' + status === 'connected' && + 'border-l-2 border-emerald-500 shadow-[inset_2px_0_0_rgba(16,185,129,0.35)]' )} aria-label="Interactive terminal" /> @@ -144,12 +151,14 @@ export function TerminalSurface({ data-testid="terminal-command-header" aria-label={`${currentCommandMark.approximate ? 'Approximate agent turn' : 'Shell command'}: ${currentCommandMark.label}`} > - + {currentCommandMark.approximate ? 'Approx.' : 'Command'} {currentCommandMark.label} @@ -175,6 +184,7 @@ export function TerminalSurface({ sessionId={historySessionId} open={historyOverlayOpen} fontSize={historyFontSize} + onScrollModeResolved={onHistoryScrollModeResolved} onClose={onCloseHistoryOverlay} />
diff --git a/apps/dashboard/src/components/terminal/terminalScrollMode.ts b/apps/dashboard/src/components/terminal/terminalScrollMode.ts new file mode 100644 index 0000000..e9449bd --- /dev/null +++ b/apps/dashboard/src/components/terminal/terminalScrollMode.ts @@ -0,0 +1,14 @@ +export const TERMINAL_HISTORY_NON_EMPTY_LINE_THRESHOLD = 40; + +export type TerminalScrollMode = 'history' | 'app-scroll'; + +export function countNonEmptyScrollbackLines(content: unknown): number { + if (typeof content !== 'string' || !content) return 0; + return content.split('\n').filter((line) => line.trim().length > 0).length; +} + +export function classifyTerminalScrollMode(content: unknown): TerminalScrollMode { + return countNonEmptyScrollbackLines(content) >= TERMINAL_HISTORY_NON_EMPTY_LINE_THRESHOLD + ? 'history' + : 'app-scroll'; +} From 5eda478f29b19a7cbe92a54a0a28ccca119ab336 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 18:23:09 -0400 Subject: [PATCH 04/11] feat(alt): route thin panes to app scroll --- .../dashboard/src/components/TerminalView.tsx | 9 +- .../components/terminal/TerminalSurface.tsx | 2 - .../src/hooks/useTerminalTouchScroll.ts | 129 +++++++++++++++++- 3 files changed, 131 insertions(+), 9 deletions(-) diff --git a/apps/dashboard/src/components/TerminalView.tsx b/apps/dashboard/src/components/TerminalView.tsx index 5ec664c..34fc3e4 100644 --- a/apps/dashboard/src/components/TerminalView.tsx +++ b/apps/dashboard/src/components/TerminalView.tsx @@ -339,6 +339,12 @@ export function TerminalView({ setHistoryOverlaySessionId(null); } }, [historyOverlaySessionId, historySessionId]); + const handleNavigateScroll = useCallback( + (lines: number) => { + navigate({ type: 'navigate', op: 'scroll', lines }); + }, + [navigate] + ); const touchScrollRef = useTerminalTouchScroll({ enabled: touchInputModeEnabled, termRef, @@ -352,7 +358,9 @@ export function TerminalView({ onScrollInput: sendInput, tmuxSessionKey, historySessionId, + historyScrollMode: terminalScrollMode, onOpenHistory: openHistoryOverlay, + onNavigateScroll: handleNavigateScroll, onHorizontalSwipe: (direction) => { termRef.current?.dispatchEvent( new CustomEvent('terminal-window-swipe', { @@ -492,7 +500,6 @@ export function TerminalView({ onOpenHistory={() => setHistoryOpen(true)} historyOverlayOpen={historyOverlayOpen} historySessionId={historySessionId} - historyScrollMode={terminalScrollMode} historyFontSize={terminalFontSize} onHistoryScrollModeResolved={handleHistoryScrollModeResolved} onCloseHistoryOverlay={closeHistoryOverlay} diff --git a/apps/dashboard/src/components/terminal/TerminalSurface.tsx b/apps/dashboard/src/components/terminal/TerminalSurface.tsx index 8c08f8b..365d7ff 100644 --- a/apps/dashboard/src/components/terminal/TerminalSurface.tsx +++ b/apps/dashboard/src/components/terminal/TerminalSurface.tsx @@ -36,7 +36,6 @@ interface TerminalSurfaceProps { onOpenHistory: () => void; historyOverlayOpen: boolean; historySessionId: string; - historyScrollMode?: TerminalScrollMode; historyFontSize: number; onHistoryScrollModeResolved: (mode: TerminalScrollMode) => void; onCloseHistoryOverlay: () => void; @@ -78,7 +77,6 @@ export function TerminalSurface({ onOpenHistory, historyOverlayOpen, historySessionId, - historyScrollMode: _historyScrollMode, historyFontSize, onHistoryScrollModeResolved, onCloseHistoryOverlay, diff --git a/apps/dashboard/src/hooks/useTerminalTouchScroll.ts b/apps/dashboard/src/hooks/useTerminalTouchScroll.ts index 0c913e9..04cab87 100644 --- a/apps/dashboard/src/hooks/useTerminalTouchScroll.ts +++ b/apps/dashboard/src/hooks/useTerminalTouchScroll.ts @@ -1,6 +1,7 @@ 'use client'; import { useEffect, useRef, type RefObject } from 'react'; +import type { TerminalScrollMode } from '@/components/terminal/terminalScrollMode'; import type { XTerminal } from '@/components/terminal/types'; import { clampTerminalFontSize } from '@/stores/settings'; @@ -30,11 +31,30 @@ type TouchScrollState = { panning: boolean; scrollPath: TerminalTouchScrollPath; historyOpened: boolean; + navigateRaf: number | null; + navigateCoalescer: TerminalScrollCoalescerState; }; const TMUX_LINES_PER_WHEEL_REPORT = 5; +const MAX_NAVIGATE_SCROLL_LINES = 120; -export type TerminalTouchScrollPath = 'local' | 'history' | 'sgr' | 'none'; +export type TerminalTouchScrollPath = 'local' | 'history' | 'navigate' | 'sgr' | 'none'; + +export type TerminalScrollCoalescerState = { + pendingLines: number; + scheduled: boolean; +}; + +export type TerminalScrollCoalescerTransition = { + state: TerminalScrollCoalescerState; + schedule: boolean; + sendLines: number; +}; + +const INITIAL_SCROLL_COALESCER: TerminalScrollCoalescerState = { + pendingLines: 0, + scheduled: false, +}; function createTouchScrollState(): TouchScrollState { return { @@ -63,6 +83,8 @@ function createTouchScrollState(): TouchScrollState { panning: false, scrollPath: 'none', historyOpened: false, + navigateRaf: null, + navigateCoalescer: { ...INITIAL_SCROLL_COALESCER }, }; } @@ -132,19 +154,61 @@ export function resolveTerminalTouchScrollPath({ writable, tmuxAttached, historyAvailable, + historyScrollMode, + hasTmuxNavigate, }: { bufferType: 'normal' | 'alternate'; mouseTrackingMode: 'none' | 'x10' | 'vt200' | 'drag' | 'any'; writable: boolean; tmuxAttached: boolean; historyAvailable: boolean; + historyScrollMode?: TerminalScrollMode; + hasTmuxNavigate?: boolean; }): TerminalTouchScrollPath { - if (tmuxAttached) return historyAvailable ? 'history' : 'none'; + if (tmuxAttached) { + if (!historyAvailable) return 'none'; + if (historyScrollMode === 'app-scroll') { + return writable && hasTmuxNavigate ? 'navigate' : 'none'; + } + return 'history'; + } if (bufferType === 'normal') return 'local'; if (mouseTrackingMode !== 'none') return writable ? 'sgr' : 'none'; return 'local'; } +export function reduceTerminalScrollCoalescer( + state: TerminalScrollCoalescerState, + event: { type: 'enqueue'; lines: number } | { type: 'flush' } +): TerminalScrollCoalescerTransition { + if (event.type === 'enqueue') { + const pendingLines = state.pendingLines + event.lines; + const schedule = !state.scheduled && pendingLines !== 0; + return { + state: { + pendingLines, + scheduled: state.scheduled || schedule, + }, + schedule, + sendLines: 0, + }; + } + + const sendLines = Math.max( + -MAX_NAVIGATE_SCROLL_LINES, + Math.min(MAX_NAVIGATE_SCROLL_LINES, state.pendingLines) + ); + const pendingLines = state.pendingLines - sendLines; + return { + state: { + pendingLines, + scheduled: pendingLines !== 0, + }, + schedule: pendingLines !== 0, + sendLines, + }; +} + export function shouldOpenHistoryOnGesture( scrollPath: TerminalTouchScrollPath, totalDy: number, @@ -192,7 +256,10 @@ export function dispatchTerminalTouchScroll({ onInput, tmuxAttached = false, historyAvailable = false, + historyScrollMode, onOpenHistory = () => undefined, + hasTmuxNavigate = false, + onNavigateScroll = () => undefined, }: { terminal: XTerminal; lineDelta: number; @@ -203,7 +270,10 @@ export function dispatchTerminalTouchScroll({ onInput: (data: string) => void; tmuxAttached?: boolean; historyAvailable?: boolean; + historyScrollMode?: TerminalScrollMode; onOpenHistory?: () => void; + hasTmuxNavigate?: boolean; + onNavigateScroll?: (lines: number) => void; }): number { const path = resolveTerminalTouchScrollPath({ bufferType: terminal.buffer.active.type, @@ -211,10 +281,13 @@ export function dispatchTerminalTouchScroll({ writable, tmuxAttached, historyAvailable, + historyScrollMode, + hasTmuxNavigate, }); if (path === 'local') terminal.scrollLines(lineDelta); if (path === 'history' && lineDelta < 0) onOpenHistory(); + if (path === 'navigate') onNavigateScroll(lineDelta); if (path !== 'sgr') return 0; const mapped = mapScrollLinesToWheelReports(lineDelta, wheelRemainder); @@ -247,7 +320,9 @@ export function useTerminalTouchScroll({ onScrollInput = onCursorInput, tmuxSessionKey, historySessionId, + historyScrollMode, onOpenHistory, + onNavigateScroll, onHorizontalSwipe, }: { enabled: boolean; @@ -262,7 +337,9 @@ export function useTerminalTouchScroll({ onScrollInput?: (data: string) => void; tmuxSessionKey?: string; historySessionId?: string; + historyScrollMode?: TerminalScrollMode; onOpenHistory?: () => void; + onNavigateScroll?: (lines: number) => void; onHorizontalSwipe?: (direction: 'previous' | 'next') => void; }) { const touchScrollRef = useRef(createTouchScrollState()); @@ -275,7 +352,9 @@ export function useTerminalTouchScroll({ const onScrollInputRef = useRef(onScrollInput); const tmuxSessionKeyRef = useRef(tmuxSessionKey); const historySessionIdRef = useRef(historySessionId); + const historyScrollModeRef = useRef(historyScrollMode); const onOpenHistoryRef = useRef(onOpenHistory); + const onNavigateScrollRef = useRef(onNavigateScroll); const onHorizontalSwipeRef = useRef(onHorizontalSwipe); fontSizeRef.current = fontSize; onFontSizeChangeRef.current = onFontSizeChange; @@ -286,7 +365,9 @@ export function useTerminalTouchScroll({ onScrollInputRef.current = onScrollInput; tmuxSessionKeyRef.current = tmuxSessionKey; historySessionIdRef.current = historySessionId; + historyScrollModeRef.current = historyScrollMode; onOpenHistoryRef.current = onOpenHistory; + onNavigateScrollRef.current = onNavigateScroll; onHorizontalSwipeRef.current = onHorizontalSwipe; useEffect(() => { @@ -317,6 +398,30 @@ export function useTerminalTouchScroll({ return terminal.cols > 0 && width > 0 ? width / terminal.cols : 8; }; + const scheduleNavigateFlush = () => { + if (touchState.navigateRaf !== null) return; + touchState.navigateRaf = requestAnimationFrame(() => { + touchState.navigateRaf = null; + const transition = reduceTerminalScrollCoalescer(touchState.navigateCoalescer, { + type: 'flush', + }); + touchState.navigateCoalescer = transition.state; + if (transition.sendLines !== 0) { + onNavigateScrollRef.current?.(transition.sendLines); + } + if (transition.schedule) scheduleNavigateFlush(); + }); + }; + + const enqueueNavigateScroll = (lines: number) => { + const transition = reduceTerminalScrollCoalescer(touchState.navigateCoalescer, { + type: 'enqueue', + lines, + }); + touchState.navigateCoalescer = transition.state; + if (transition.schedule) scheduleNavigateFlush(); + }; + const disarmCursorGesture = () => { cursorArmedRef.current = false; onCursorDisarmRef.current?.(); @@ -381,6 +486,8 @@ export function useTerminalTouchScroll({ writable: writableRef.current, tmuxAttached: Boolean(tmuxSessionKeyRef.current), historyAvailable: Boolean(historySessionIdRef.current), + historyScrollMode: historyScrollModeRef.current, + hasTmuxNavigate: Boolean(onNavigateScrollRef.current), }); touchState.historyOpened = false; }; @@ -535,8 +642,11 @@ export function useTerminalTouchScroll({ row: touchState.wheelRow, writable: writableRef.current, onInput: onScrollInputRef.current, - tmuxAttached: false, - historyAvailable: false, + tmuxAttached: Boolean(tmuxSessionKeyRef.current), + historyAvailable: Boolean(historySessionIdRef.current), + historyScrollMode: historyScrollModeRef.current, + hasTmuxNavigate: Boolean(onNavigateScrollRef.current), + onNavigateScroll: enqueueNavigateScroll, }); } const now = performance.now(); @@ -638,8 +748,11 @@ export function useTerminalTouchScroll({ row: touchState.wheelRow, writable: writableRef.current, onInput: onScrollInputRef.current, - tmuxAttached: false, - historyAvailable: false, + tmuxAttached: Boolean(tmuxSessionKeyRef.current), + historyAvailable: Boolean(historySessionIdRef.current), + historyScrollMode: historyScrollModeRef.current, + hasTmuxNavigate: Boolean(onNavigateScrollRef.current), + onNavigateScroll: enqueueNavigateScroll, }); } touchState.momentumRaf = requestAnimationFrame(tick); @@ -661,6 +774,10 @@ export function useTerminalTouchScroll({ cancelAnimationFrame(touchState.momentumRaf); touchState.momentumRaf = null; } + if (touchState.navigateRaf !== null) { + cancelAnimationFrame(touchState.navigateRaf); + touchState.navigateRaf = null; + } }; }, [enabled, termRef, terminalRef]); From 0ce40c722d130cfabe9cfbe706f1a79a9f17a03f Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 18:23:30 -0400 Subject: [PATCH 05/11] feat(alt): close thin history overlays --- .../src/components/terminal/TerminalHistoryOverlay.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx index fa0de15..d082b57 100644 --- a/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx +++ b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx @@ -86,6 +86,10 @@ export function TerminalHistoryOverlay({ const page = await fetchPage(initialScrollbackRange()); if (generationRef.current !== generation) return; onScrollModeResolved(page.scrollMode); + if (page.scrollMode === 'app-scroll') { + onClose(); + return; + } setPages([page]); setHasOlder(page.lines.length >= SCROLLBACK_PAGE_LINES); requestAnimationFrame(() => { @@ -103,7 +107,7 @@ export function TerminalHistoryOverlay({ } finally { if (generationRef.current === generation) setLoadingInitial(false); } - }, [fetchPage, onScrollModeResolved]); + }, [fetchPage, onClose, onScrollModeResolved]); useEffect(() => { if (!open) { From f7caf43a3ad3758cf3eef2665fb4230882bcd0c5 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 18:24:00 -0400 Subject: [PATCH 06/11] feat(alt): cover hybrid scroll dispatch --- .../terminal/terminalScrollMode.test.ts | 40 +++++++ .../src/hooks/useTerminalTouchScroll.test.ts | 104 ++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 apps/dashboard/src/components/terminal/terminalScrollMode.test.ts diff --git a/apps/dashboard/src/components/terminal/terminalScrollMode.test.ts b/apps/dashboard/src/components/terminal/terminalScrollMode.test.ts new file mode 100644 index 0000000..7b67b7a --- /dev/null +++ b/apps/dashboard/src/components/terminal/terminalScrollMode.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest'; +import { + TERMINAL_HISTORY_NON_EMPTY_LINE_THRESHOLD, + classifyTerminalScrollMode, + countNonEmptyScrollbackLines, +} from './terminalScrollMode'; + +describe('terminal scroll mode classification', () => { + it('counts only non-empty lines, including around blank and whitespace-only lines', () => { + expect(countNonEmptyScrollbackLines('first\n\n \nsecond\n\t\nthird\n')).toBe(3); + expect(countNonEmptyScrollbackLines(undefined)).toBe(0); + expect(countNonEmptyScrollbackLines({ content: 'not a capture string' })).toBe(0); + }); + + it('classifies below the named threshold as app scroll', () => { + const content = [ + ...Array.from( + { length: TERMINAL_HISTORY_NON_EMPTY_LINE_THRESHOLD - 1 }, + (_, index) => `line ${index + 1}` + ), + '', + ' ', + ].join('\n'); + + expect(countNonEmptyScrollbackLines(content)).toBe(39); + expect(classifyTerminalScrollMode(content)).toBe('app-scroll'); + }); + + it('classifies the threshold and denser captures as history despite blank lines', () => { + const thresholdContent = Array.from( + { length: TERMINAL_HISTORY_NON_EMPTY_LINE_THRESHOLD }, + (_, index) => (index === 20 ? `line ${index + 1}\n\n ` : `line ${index + 1}`) + ).join('\n'); + const denseContent = `${thresholdContent}\none more`; + + expect(countNonEmptyScrollbackLines(thresholdContent)).toBe(40); + expect(classifyTerminalScrollMode(thresholdContent)).toBe('history'); + expect(classifyTerminalScrollMode(denseContent)).toBe('history'); + }); +}); diff --git a/apps/dashboard/src/hooks/useTerminalTouchScroll.test.ts b/apps/dashboard/src/hooks/useTerminalTouchScroll.test.ts index fc43f8b..986d884 100644 --- a/apps/dashboard/src/hooks/useTerminalTouchScroll.test.ts +++ b/apps/dashboard/src/hooks/useTerminalTouchScroll.test.ts @@ -6,6 +6,7 @@ import { dispatchTerminalTouchScroll, mapTouchScrollPixelsToLines, mapScrollLinesToWheelReports, + reduceTerminalScrollCoalescer, resolveTerminalHorizontalSwipe, resolveTerminalTouchScrollPath, resolveTouchCell, @@ -138,6 +139,73 @@ describe('native terminal touch scroll mapping', () => { ).toBe('none'); }); + it.each([ + ['history', true, 'history'], + ['history', false, 'history'], + ['app-scroll', true, 'navigate'], + ['app-scroll', false, 'none'], + [undefined, true, 'history'], + [undefined, false, 'history'], + ] as const)( + 'routes %s mode with writable=%s to %s', + (historyScrollMode, writable, expectedPath) => { + expect( + resolveTerminalTouchScrollPath({ + bufferType: 'alternate', + mouseTrackingMode: 'any', + writable, + tmuxAttached: true, + historyAvailable: true, + historyScrollMode, + hasTmuxNavigate: true, + }) + ).toBe(expectedPath); + } + ); + + it('coalesces one batch per frame, skips zero, and carries values beyond the cap', () => { + let transition = reduceTerminalScrollCoalescer( + { pendingLines: 0, scheduled: false }, + { type: 'enqueue', lines: -70 } + ); + expect(transition).toMatchObject({ schedule: true, sendLines: 0 }); + + transition = reduceTerminalScrollCoalescer(transition.state, { + type: 'enqueue', + lines: -80, + }); + expect(transition).toMatchObject({ + state: { pendingLines: -150, scheduled: true }, + schedule: false, + sendLines: 0, + }); + + transition = reduceTerminalScrollCoalescer(transition.state, { type: 'flush' }); + expect(transition).toMatchObject({ + state: { pendingLines: -30, scheduled: true }, + schedule: true, + sendLines: -120, + }); + transition = reduceTerminalScrollCoalescer(transition.state, { type: 'flush' }); + expect(transition).toMatchObject({ + state: { pendingLines: 0, scheduled: false }, + schedule: false, + sendLines: -30, + }); + + transition = reduceTerminalScrollCoalescer( + { pendingLines: 0, scheduled: false }, + { type: 'enqueue', lines: 4 } + ); + transition = reduceTerminalScrollCoalescer(transition.state, { + type: 'enqueue', + lines: -4, + }); + transition = reduceTerminalScrollCoalescer(transition.state, { type: 'flush' }); + expect(transition.sendLines).toBe(0); + expect(transition.schedule).toBe(false); + }); + it('keeps non-tmux local and SGR paths unchanged', () => { expect( resolveTerminalTouchScrollPath({ @@ -239,6 +307,7 @@ describe('terminal touch scroll dispatch', () => { onInput, tmuxAttached: true, historyAvailable: true, + historyScrollMode: 'history', onOpenHistory, }) ).toBe(0); @@ -247,6 +316,40 @@ describe('terminal touch scroll dispatch', () => { expect(terminal.scrollLines).not.toHaveBeenCalled(); }); + it('sends one-to-one navigate lines for writable app scroll and gates read-only', () => { + const terminal = terminalForScroll('alternate', 'drag'); + const onInput = vi.fn(); + const onOpenHistory = vi.fn(); + const onNavigateScroll = vi.fn(); + const dispatch = (writable: boolean) => + dispatchTerminalTouchScroll({ + terminal, + lineDelta: -17, + wheelRemainder: 4, + column: 12, + row: 7, + writable, + onInput, + tmuxAttached: true, + historyAvailable: true, + historyScrollMode: 'app-scroll', + hasTmuxNavigate: true, + onOpenHistory, + onNavigateScroll, + }); + + expect(dispatch(true)).toBe(0); + expect(onNavigateScroll).toHaveBeenCalledOnce(); + expect(onNavigateScroll).toHaveBeenCalledWith(-17); + + onNavigateScroll.mockClear(); + expect(dispatch(false)).toBe(0); + expect(onNavigateScroll).not.toHaveBeenCalled(); + expect(onOpenHistory).not.toHaveBeenCalled(); + expect(onInput).not.toHaveBeenCalled(); + expect(terminal.scrollLines).not.toHaveBeenCalled(); + }); + it('opens attached tmux history while read-only and ignores upward swipes', () => { const terminal = terminalForScroll('normal', 'none'); const onInput = vi.fn(); @@ -288,6 +391,7 @@ describe('terminal touch scroll dispatch', () => { expect(shouldOpenHistoryOnGesture('history', 24, true)).toBe(false); expect(shouldOpenHistoryOnGesture('none', 24, false)).toBe(false); expect(shouldOpenHistoryOnGesture('local', 24, false)).toBe(false); + expect(shouldOpenHistoryOnGesture('navigate', 24, false)).toBe(false); expect(shouldOpenHistoryOnGesture('sgr', 24, false)).toBe(false); }); From f1112d6db56b703c3c5b8b966da7fad31e2aea40 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 18:25:52 -0400 Subject: [PATCH 07/11] feat(alt): prove hybrid scroll journeys --- tests/journeys/command-center.journey.spec.ts | 2 +- tests/journeys/controlPlaneMock.ts | 19 ++-- tests/journeys/fw6-focus.journey.spec.ts | 92 ++++++++++++++++++- tests/journeys/fw6-precision.journey.spec.ts | 4 + 4 files changed, 105 insertions(+), 12 deletions(-) diff --git a/tests/journeys/command-center.journey.spec.ts b/tests/journeys/command-center.journey.spec.ts index 90d6e06..0cb5df3 100644 --- a/tests/journeys/command-center.journey.spec.ts +++ b/tests/journeys/command-center.journey.spec.ts @@ -347,7 +347,7 @@ test.describe('Command Center program journeys', () => { await expect(history.getByText('recent line 1', { exact: true })).toBeVisible(); await history.getByRole('button', { name: 'Load older' }).click(); await expect - .poll(() => recorder.scrollbackRequests) + .poll(() => recorder.scrollbackRequests.slice(-2)) .toEqual([ { mode: 'range', start_line: -500, end_line: -1, strip_ansi: true }, { mode: 'range', start_line: -1000, end_line: -501, strip_ansi: true }, diff --git a/tests/journeys/controlPlaneMock.ts b/tests/journeys/controlPlaneMock.ts index 4cf9918..d788173 100644 --- a/tests/journeys/controlPlaneMock.ts +++ b/tests/journeys/controlPlaneMock.ts @@ -93,9 +93,10 @@ export const approvalSession = { export const windowSession = { ...baseSession, + provider: 'claude_code', id: '44444444-4444-4444-8444-444444444444', status: 'RUNNING', - title: 'Window two shell', + title: 'Claude Code', tmux_pane_id: '%4', tmux_target: 'agents:1.0', metadata: { @@ -189,7 +190,7 @@ function topologyMessage( width: 94, height: 40, title: windowSession.title, - current_command: 'bash', + current_command: 'claude', current_path: windowSession.cwd, }, ] : [], @@ -238,6 +239,7 @@ interface MockOptions { terminalReadOnly?: boolean; terminalOutput?: string; multiWindow?: boolean; + appScrollSessionIds?: string[]; } async function fulfillJson(route: Route, body: unknown): Promise { @@ -521,18 +523,23 @@ export async function mockControlPlane( } if (request.method() === 'POST' && /^\/v1\/sessions\/[^/]+\/scrollback$/.test(url.pathname)) { const body = request.postDataJSON() as { start_line?: number }; + const scrollbackSessionId = url.pathname.split('/')[3] || ''; recorder.scrollbackRequests.push(body); - recorder.scrollbackSessionIds.push(url.pathname.split('/')[3] || ''); + recorder.scrollbackSessionIds.push(scrollbackSessionId); const initialPage = body.start_line === -500; + const appScrollPage = initialPage && options.appScrollSessionIds?.includes( + scrollbackSessionId + ); + const lineCount = appScrollPage ? 1 : initialPage ? 500 : 12; await fulfillJson(route, { cmd_id: '01JJOURNEYHISTORY0000000000', ok: true, result: { content: historyContent( - initialPage ? 'recent line' : 'older line', - initialPage ? 500 : 12 + appScrollPage ? 'claude prompt' : initialPage ? 'recent line' : 'older line', + lineCount ), - line_count: initialPage ? 500 : 12, + line_count: lineCount, capture_mode: 'range', }, }); diff --git a/tests/journeys/fw6-focus.journey.spec.ts b/tests/journeys/fw6-focus.journey.spec.ts index 48a562f..5945a68 100644 --- a/tests/journeys/fw6-focus.journey.spec.ts +++ b/tests/journeys/fw6-focus.journey.spec.ts @@ -59,6 +59,20 @@ async function openInlineHistory(page: Page): Promise { await expect(page.getByLabel('Inline terminal history')).toBeVisible(); } +async function waitForScrollModeProbe( + page: Page, + recorder: JourneyRecorder, + sessionId: string, + previousCount = 0 +): Promise { + await expect + .poll(() => recorder.scrollbackSessionIds.filter((candidate) => candidate === sessionId).length) + .toBeGreaterThan(previousCount); + await page.evaluate(() => new Promise((resolve) => { + requestAnimationFrame(() => requestAnimationFrame(() => resolve())); + })); +} + async function overscrollHistoryPastBottom(page: Page): Promise { const history = page.getByLabel('Inline terminal history'); await history.evaluate((element) => { @@ -101,16 +115,19 @@ test.describe('FW6 mobile Focus journey', () => { recorder = await mockControlPlane(page, { multiWindow: true, terminalOutput: '\x1b[?1049h\x1b[?1002h\x1b[?1006h', + appScrollSessionIds: [windowSession.id], }); }); test('opens inline history without emitting terminal scroll or SGR frames', async ({ page }) => { await signIn(page); await selectSession(page); + await waitForScrollModeProbe(page, recorder, interactiveSession.id); + const scrollbackStart = recorder.scrollbackRequests.length; const messageStart = recorder.terminalMessages.length; await openInlineHistory(page); - await expect.poll(() => recorder.scrollbackRequests.length).toBe(1); + await expect.poll(() => recorder.scrollbackRequests.length).toBe(scrollbackStart + 1); const gestureMessages = recorder.terminalMessages.slice(messageStart); expect(gestureMessages.filter( @@ -129,12 +146,14 @@ test.describe('FW6 mobile Focus journey', () => { }) => { await signIn(page); await selectSession(page); + await waitForScrollModeProbe(page, recorder, interactiveSession.id); + const scrollbackStart = recorder.scrollbackRequests.length; const messageStart = recorder.terminalMessages.length; await dragTerminal(page, -140); await expect(page.getByTestId('terminal-history-overlay')).toHaveCount(0); - expect(recorder.scrollbackRequests).toHaveLength(0); + expect(recorder.scrollbackRequests).toHaveLength(scrollbackStart); const gestureMessages = recorder.terminalMessages.slice(messageStart); expect(gestureMessages.filter( (message) => message.type === 'navigate' && message.op === 'scroll' @@ -149,6 +168,7 @@ test.describe('FW6 mobile Focus journey', () => { test('prepends older history without moving the visible transcript', async ({ page }) => { await signIn(page); await selectSession(page); + await waitForScrollModeProbe(page, recorder, interactiveSession.id); await openInlineHistory(page); const history = page.getByLabel('Inline terminal history'); const initialHeight = await history.evaluate((element) => element.scrollHeight); @@ -158,7 +178,7 @@ test.describe('FW6 mobile Focus journey', () => { element.dispatchEvent(new Event('scroll', { bubbles: true })); }); - await expect.poll(() => recorder.scrollbackRequests).toEqual([ + await expect.poll(() => recorder.scrollbackRequests.slice(-2)).toEqual([ { mode: 'range', start_line: -500, end_line: -1, strip_ansi: true }, { mode: 'range', start_line: -1000, end_line: -501, strip_ansi: true }, ]); @@ -243,13 +263,21 @@ test.describe('FW6 mobile Focus journey', () => { expect(inputCount()).toBe(inputCountAfterCursorGesture); }); - test('loads History from the selected session after an in-place window switch', async ({ + test('re-resolves hybrid scroll mode across in-place codex and claude window switches', async ({ page, }) => { await signIn(page); await selectSession(page); + await waitForScrollModeProbe(page, recorder, interactiveSession.id); const terminalWebSocketCount = recorder.terminalWebSocketUrls.length; + const codexMessageStart = recorder.terminalMessages.length; + await openInlineHistory(page); + expect(recorder.terminalMessages.slice(codexMessageStart).filter( + (message) => message.type === 'navigate' && message.op === 'scroll' + )).toHaveLength(0); + await page.getByRole('button', { name: 'Live terminal' }).click(); + await page .getByTestId('tmux-window-strip') .first() @@ -257,9 +285,63 @@ test.describe('FW6 mobile Focus journey', () => { .click(); await expect(page).toHaveURL(new RegExp(`session_id=${windowSession.id}`)); await expect.poll(() => recorder.terminalWebSocketUrls.length).toBe(terminalWebSocketCount); + await waitForScrollModeProbe(page, recorder, windowSession.id); + + const claudeMessageStart = recorder.terminalMessages.length; + await dragTerminal(page, 140); + await expect.poll(() => recorder.terminalMessages.slice(claudeMessageStart).filter( + (message) => message.type === 'navigate' && message.op === 'scroll' + ).length).toBeGreaterThan(0); + await expect(page.getByTestId('terminal-history-overlay')).toHaveCount(0); + const priorInteractiveProbeCount = recorder.scrollbackSessionIds.filter( + (sessionId) => sessionId === interactiveSession.id + ).length; + await page + .getByTestId('tmux-window-strip') + .first() + .getByRole('tab', { name: 'Window 0: command-center' }) + .click(); + await expect(page).toHaveURL(new RegExp(`session_id=${interactiveSession.id}`)); + await waitForScrollModeProbe( + page, + recorder, + interactiveSession.id, + priorInteractiveProbeCount + ); + + const returnedCodexMessageStart = recorder.terminalMessages.length; await openInlineHistory(page); - await expect.poll(() => recorder.scrollbackSessionIds.at(-1)).toBe(windowSession.id); + expect(recorder.terminalMessages.slice(returnedCodexMessageStart).filter( + (message) => message.type === 'navigate' && message.op === 'scroll' + )).toHaveLength(0); + }); + + test('routes a resolved claude-like pane to app scroll without leaving an overlay', async ({ + page, + }) => { + await signIn(page); + await selectSession(page); + await page + .getByTestId('tmux-window-strip') + .first() + .getByRole('tab', { name: 'Window 1: verification' }) + .click(); + await expect(page).toHaveURL(new RegExp(`session_id=${windowSession.id}`)); + await waitForScrollModeProbe(page, recorder, windowSession.id); + const scrollbackCount = recorder.scrollbackRequests.length; + const messageStart = recorder.terminalMessages.length; + + await dragTerminal(page, 140); + + await expect.poll(() => recorder.terminalMessages.slice(messageStart).filter( + (message) => message.type === 'navigate' && message.op === 'scroll' + ).length).toBeGreaterThan(0); + await expect(page.getByTestId('terminal-history-overlay')).toHaveCount(0); + expect(recorder.scrollbackRequests).toHaveLength(scrollbackCount); + expect(recorder.terminalMessages.slice(messageStart).filter( + (message) => message.type === 'input' + )).toHaveLength(0); }); test('keeps the History dialog reachable from pane actions', async ({ page }) => { diff --git a/tests/journeys/fw6-precision.journey.spec.ts b/tests/journeys/fw6-precision.journey.spec.ts index 8f1c2fa..930e702 100644 --- a/tests/journeys/fw6-precision.journey.spec.ts +++ b/tests/journeys/fw6-precision.journey.spec.ts @@ -89,6 +89,10 @@ test.describe('FW6 mobile precision journeys', () => { await signIn(page); await selectSession(page, interactiveSession.title); const history = await openHistory(page); + await expect(history.getByText('500 lines', { exact: true })).toBeVisible(); + await history.getByLabel('Captured terminal history').evaluate((element) => { + element.scrollTop = element.scrollHeight; + }); await expect(history.getByRole('button', { name: 'Select history line -3', exact: true, From d196a7a33f1b3f6dcc58fced6ae1cc451826e9de Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 18:32:18 -0400 Subject: [PATCH 08/11] feat(alt): freeze hybrid scroll handoff --- tasks/frontend-ux-handoffs/fw6-alt.md | 66 +++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 tasks/frontend-ux-handoffs/fw6-alt.md diff --git a/tasks/frontend-ux-handoffs/fw6-alt.md b/tasks/frontend-ux-handoffs/fw6-alt.md new file mode 100644 index 0000000..6970be8 --- /dev/null +++ b/tasks/frontend-ux-handoffs/fw6-alt.md @@ -0,0 +1,66 @@ +--- +lane: FW6-ALT +frozen_sha: f1112d6db56b703c3c5b8b966da7fad31e2aea40 +attempt: 2 +state: frozen +gates: + lint: pass + typecheck: pass + test_ci: pass + smoke: pass + journeys: pass + build: pass +proof: + - "pnpm lint && pnpm typecheck && pnpm test:ci && pnpm test:smoke:dashboard && pnpm test:journeys && pnpm build → exact mandatory gate passed in order on attempt 2 from tmux session agent-command:0.0" + - "pnpm lint → all 5 Turbo tasks passed with zero errors; three existing hook warnings remain" + - "pnpm typecheck → all 5 Turbo tasks passed" + - "pnpm test:ci → all 5 Turbo tasks passed, including dashboard 243/243, control-plane 200/200, schema 53/53, and CLI 44/44" + - "pnpm test:smoke:dashboard → 21/21 Chromium scenarios passed" + - "pnpm test:journeys → 37 passed and 19 expected project skips across mobile and desktop" + - "pnpm build → 4/4 Turbo build tasks passed; Next.js 16.2.10 production build completed" + - "FW6 Focus focused journey → 10/10 passed at mobile-412x915, covering dense history, thin app-scroll, in-place mode re-resolution, paging, overscroll, History dialog, Keyboard, Cursor, and Focus" + - "New red isolation → mobile/desktop history paging and mobile precision selection passed five repeats each: 15 passed, 5 expected desktop precision skips" + - "Frontend product audit → real Playwright interaction at 412x915 and 1280x720; score 98/100 with no hard failures" +assumptions: + - "Whitespace-only capture rows are empty for the locked 40-non-empty-line heuristic." + - "A failed or still-pending probe remains unclassified and therefore follows the locked history/loading safe path." +uncertainties: + - "A physical Galaxy S25 Ultra was unavailable; touch dispatch, momentum, overlay closure, and reclassification were exercised in the mobile-412x915 Chromium project." +blockers: [] +--- + +# FW6-ALT frozen handoff + +## Outcome + +FW6-ALT adds hybrid attached-tmux touch scrolling without changing protocol or agentd. Dense captures keep the local history overlay. Thin alternate-screen captures route touch and momentum deltas through the existing `navigate {op:'scroll'}` transport, so claude-code scrolls its own transcript instead of showing a black one-line overlay. + +## Delivered work + +- Added an exported pure classifier with the locked threshold of 40 non-empty newest-page lines, including whitespace-only line handling. +- Added a `historySessionId`-keyed mode cache in `TerminalView`, primed when an attachment becomes connected and invalidated/re-probed on in-place pane or window changes. +- Reuses the overlay's own newest-page fetch to refresh classification on every open, avoiding a separate classification request at open time. +- Preserves unclassified behavior as history: the overlay opens in its existing loading state, then a thin result reports `app-scroll`, caches the mode, and closes without rendering thin content. +- Restored the deleted animation-frame navigate coalescer from `92d98d3`, including one-to-one line emission, zero cancellation, carry, and the ±120-per-message clamp. +- Split attached touch dispatch into history/unclassified overlay, writable app-scroll navigate, and read-only app-scroll no-op paths. +- Kept non-tmux local/SGR scrolling, pinch, horizontal swipe and panning, selection, context menu, Keyboard, Cursor, History dialog, paging, prepend compensation, Live return, and overscroll dismissal unchanged. +- Extended the journey mock with a one-line claude-code window and proved dense codex, thin claude, and codex→claude→codex in-place re-resolution without a terminal reconnect. + +## Verification notes + +- Full-gate attempt 1 stopped at journeys because existing request-count assertions did not account for the new attachment prime and a virtualized history selector had not explicitly bottom-anchored before selecting newest rows. +- Both direct journey expectations were corrected and isolated for five repeats before the full chain was retried. Attempt 2 passed the exact required chain from the tmux-backed TTY. +- The browser matrix exercised the existing loading, history, paging, permission, Keyboard, Cursor, and desktop/mobile states. No new visible control or layout was introduced; frontend audit score is 98/100 with no clipping, focus, responsive, or interaction-state hard failure. +- The ownership firewall was preserved: no agentd, schema, package, service, deploy, host descriptor, letterbox, mobile Focus, rail-key, or production-state changes were made. + +## Work-item commits + +- `35473d9` — `feat(alt): classify pane scroll mode` +- `5eda478` — `feat(alt): route thin panes to app scroll` +- `0ce40c7` — `feat(alt): close thin history overlays` +- `f7caf43` — `feat(alt): cover hybrid scroll dispatch` +- `f1112d6` — `feat(alt): prove hybrid scroll journeys` + +The `frozen_sha` is the final implementation/test commit; the following handoff-only commit adds this file. + +FW6-ALT FROZEN f1112d6db56b703c3c5b8b966da7fad31e2aea40 From 3dd5b9a4c283f91aaab757f0de18f0c903b84eb3 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 18:48:10 -0400 Subject: [PATCH 09/11] =?UTF-8?q?fix(alt):=20review=20fixes=20=E2=80=94=20?= =?UTF-8?q?coalescer=20cleanup=20reset,=20guarded=20prime,=20probe=20gatin?= =?UTF-8?q?g?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AI Lead integration fixes on FW6-ALT (adversarial review): - restore the coalescer reset in effect cleanup (pending 'scheduled' state otherwise deadlocks app-scroll after an enabled toggle) - prime fetch wrapped in try/catch (transport errors stay unclassified instead of unhandled rejections) and gated to touch-enabled viewports (desktop no longer issues unused capture round-trips) - overlay reports classification before the generation check so a quick dismiss during the spinner cannot discard it - new journey: unclassified thin pane — overlay spinner auto-closes, caches app-scroll, second drag emits navigate frames Co-Authored-By: Claude Fable 5 --- .../dashboard/src/components/TerminalView.tsx | 28 ++++++++++------- .../terminal/TerminalHistoryOverlay.tsx | 2 +- .../src/hooks/useTerminalTouchScroll.ts | 1 + tests/journeys/fw6-focus.journey.spec.ts | 31 +++++++++++++++++++ 4 files changed, 50 insertions(+), 12 deletions(-) diff --git a/apps/dashboard/src/components/TerminalView.tsx b/apps/dashboard/src/components/TerminalView.tsx index 34fc3e4..dc89105 100644 --- a/apps/dashboard/src/components/TerminalView.tsx +++ b/apps/dashboard/src/components/TerminalView.tsx @@ -243,25 +243,31 @@ export function TerminalView({ useEffect(() => { scrollModeCacheRef.current.delete(historySessionId); setScrollModeCacheVersion((version) => version + 1); - if (status !== 'connected' || !tmuxSessionKey || !historySessionId) return; + if (!touchInputModeEnabled || status !== 'connected' || !tmuxSessionKey || !historySessionId) { + return; + } let cancelled = false; const primeScrollMode = async () => { - const range = initialScrollbackRange(); - const response = await getSessionScrollback(historySessionId, { - mode: 'range', - start_line: range.startLine, - end_line: range.endLine, - strip_ansi: true, - }); - if (cancelled || !response.ok) return; - cacheScrollMode(historySessionId, classifyTerminalScrollMode(response.result?.content)); + try { + const range = initialScrollbackRange(); + const response = await getSessionScrollback(historySessionId, { + mode: 'range', + start_line: range.startLine, + end_line: range.endLine, + strip_ansi: true, + }); + if (cancelled || !response.ok) return; + cacheScrollMode(historySessionId, classifyTerminalScrollMode(response.result?.content)); + } catch { + // Transport failure leaves the pane unclassified; the overlay path re-probes. + } }; void primeScrollMode(); return () => { cancelled = true; }; - }, [cacheScrollMode, historySessionId, status, tmuxSessionKey]); + }, [cacheScrollMode, historySessionId, status, tmuxSessionKey, touchInputModeEnabled]); const handleHistoryScrollModeResolved = useCallback( (mode: TerminalScrollMode) => { cacheScrollMode(historySessionId, mode); diff --git a/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx index d082b57..f48b029 100644 --- a/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx +++ b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx @@ -84,8 +84,8 @@ export function TerminalHistoryOverlay({ setScrollTop(0); try { const page = await fetchPage(initialScrollbackRange()); - if (generationRef.current !== generation) return; onScrollModeResolved(page.scrollMode); + if (generationRef.current !== generation) return; if (page.scrollMode === 'app-scroll') { onClose(); return; diff --git a/apps/dashboard/src/hooks/useTerminalTouchScroll.ts b/apps/dashboard/src/hooks/useTerminalTouchScroll.ts index 04cab87..df0c185 100644 --- a/apps/dashboard/src/hooks/useTerminalTouchScroll.ts +++ b/apps/dashboard/src/hooks/useTerminalTouchScroll.ts @@ -778,6 +778,7 @@ export function useTerminalTouchScroll({ cancelAnimationFrame(touchState.navigateRaf); touchState.navigateRaf = null; } + touchState.navigateCoalescer = { ...INITIAL_SCROLL_COALESCER }; }; }, [enabled, termRef, terminalRef]); diff --git a/tests/journeys/fw6-focus.journey.spec.ts b/tests/journeys/fw6-focus.journey.spec.ts index 5945a68..c64a686 100644 --- a/tests/journeys/fw6-focus.journey.spec.ts +++ b/tests/journeys/fw6-focus.journey.spec.ts @@ -344,6 +344,37 @@ test.describe('FW6 mobile Focus journey', () => { )).toHaveLength(0); }); + test('auto-closes an unclassified thin overlay and caches app scroll', async ({ page }) => { + await page.route(/\/v1\/sessions\/[^/]+\/scrollback$/, async (route) => { + await new Promise((resolve) => setTimeout(resolve, 800)); + await route.fallback(); + }); + await signIn(page); + await selectSession(page); + await page + .getByTestId('tmux-window-strip') + .first() + .getByRole('tab', { name: 'Window 1: verification' }) + .click(); + await expect(page).toHaveURL(new RegExp(`session_id=${windowSession.id}`)); + + const messageStart = recorder.terminalMessages.length; + await dragTerminal(page, 140); + const overlay = page.getByTestId('terminal-history-overlay'); + await expect(overlay).toBeVisible(); + await expect(overlay).toHaveCount(0, { timeout: 8000 }); + expect(recorder.terminalMessages.slice(messageStart).filter( + (message) => message.type === 'navigate' && message.op === 'scroll' + )).toHaveLength(0); + + const appScrollStart = recorder.terminalMessages.length; + await dragTerminal(page, 140); + await expect.poll(() => recorder.terminalMessages.slice(appScrollStart).filter( + (message) => message.type === 'navigate' && message.op === 'scroll' + ).length).toBeGreaterThan(0); + await expect(overlay).toHaveCount(0); + }); + test('keeps the History dialog reachable from pane actions', async ({ page }) => { await signIn(page); await selectSession(page); From 8dd6b59e80c7d7e5de2697e8d27ac65674f11e8c Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 18:57:41 -0400 Subject: [PATCH 10/11] fix(alt): disable native scroll anchoring in the history overlay Chrome's scroll anchoring races the manual prepend compensation and double-compensates when it engages (load-dependent), causing a visible jump and the prepend journey's full-suite flake. The overlay owns its scroll math; overflow-anchor none makes it the only actor. Co-Authored-By: Claude Fable 5 --- .../src/components/terminal/TerminalHistoryOverlay.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx index f48b029..a786c33 100644 --- a/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx +++ b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx @@ -232,7 +232,7 @@ export function TerminalHistoryOverlay({
{ From ae7177e1eff307794b6223dc756d1b846624fbcb Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 19:02:06 -0400 Subject: [PATCH 11/11] docs(program): FW6-ALT integration receipt Co-Authored-By: Claude Fable 5 --- tasks/frontend-ux-log.md | 1 + 1 file changed, 1 insertion(+) diff --git a/tasks/frontend-ux-log.md b/tasks/frontend-ux-log.md index 39d603d..d5cc1f4 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -66,3 +66,4 @@ - ~21:05Z (07-21) FW6-HIST froze at `d94d31d` (attempt 1, ~21 min, 4 impl commits, full green gate from the lane TTY). Lane ran LOCALLY on heavisidelinux (classifier blocked remote codex launch over ssh; local codex quota had reset to 89%; host wrapper supplies yolo flags — plain `codex` here). AI Lead review: firewall CLEAN; adversarial reviewer SHIP-WITH-NOTES (0 critical). Integration fixes applied by AI Lead (cc9c51a + 68afa01): (1) DESIGN DEFECT FROM THE BRIEF — open gesture was spec'd swipe-UP, colliding with the upward dismiss overscroll and inverting natural content-follows-finger scrolling; flipped to downward drag with a single pure gate (shouldOpenHistoryOnGesture) + both journey directions pinned; (2) reviewer W1: prepend compensation now reads live scrollTop inside rAF (no jump-back when scrolling during load-older); (3) reviewer W2: loadingOlder state reset on close-mid-fetch; (4) short histories bottom-anchored (mt-auto); (5) restored History-dialog pane-actions journey + upward-no-op journey (reviewer W3/N7). OWNER NOTE (reviewer W4, inherited): capture-pane range addressing is relative to the moving history end — browsing history while a pane streams can duplicate a band of lines at page seams (same semantics as the History dialog; needs absolute addressing to fix). INTEGRATED @ 3699e53 (--no-ff). FULL GATE GREEN on integration (attempt 3; attempts 1-2 were THIS HOST's stale environment, not code: main repo node_modules missing the FW1 workspace lint package → pnpm install; stale .next/dev types from pre-Wave-6 routes → cache cleared per standing lesson). 200 CP + 232 dashboard tests, 21/21 smoke, 36 journeys, build. No agentd/protocol changes — no binary rollout. PR next. - ~21:36Z (07-21) FW6-HIST SHIPPED: PR #96 MERGED (main ef5abe3; merge required OWNER `!` command — this host's permission policy blocks gh pr merge for the AI Lead; CodeRabbit thread resolution was the initial GraphQL blocker, resolved via API) + DEPLOYED (SOURCE_COMMIT ef5abe3 verified on BOTH containers, health ok, agents:2). No agentd change — no binary rollout. Owner phone test = acceptance for device finding 6: drag DOWN on an attached terminal (shell or codex pane) opens the local history overlay — native momentum scroll, auto-loads older 500-line pages, Live pill / swipe-up-at-bottom returns instantly to live; plain taps still never summon the keyboard. Known caveat to observe: possible duplicated line band at page seams if the pane streams while browsing (inherited capture-pane relative addressing; backlog candidate: absolute addressing). - ~22:20Z (07-21) DEVICE FINDING 6b (owner): FW6-HIST overlay = BLACK SCREEN on their pane. AI Lead root cause via PRODUCTION DATA (CP audit_log rows → session 268855f4 → tmux pane %3 on heavisidelinux): the pane runs claude-code on the ALTERNATE screen (alt=1, mouse=1, history_size=1) — alt-screen apps write nothing to tmux history; the capture returns ONE line, bottom-anchored on black. Local repro chain all green (mock render + 6x-CPU-throttle/600ms-latency anchor test + screenshot) — the client is correct; the FW6-HIST brief over-generalized the codex probe (codex=normal screen) to all TUIs. Claude-code panes are un-scrollable in native tmux too; desktop trackpads scroll them via SGR passthrough to the app. Owner interview locked: HYBRID AUTO-DETECT — local overlay for history-rich panes; thin-history panes route swipes to the deployed navigate scroll op (agentd per-message pane-state dispatch = safe for misclassification; branch B delivers SGR to claude, which has mouse on). Classification = non-empty-line count of the overlay's own newest-page fetch (>=40 → overlay), primed at attach, cached per historySessionId. No agentd/protocol change, no rollout. FW6-ALT lane launching locally (brief tasks/2026-07-21-fw6-alt-brief.md). FW6-HIST acceptance stands for codex/shell panes (owner retest pending). +- ~23:15Z (07-21) FW6-ALT froze at `f1112d6` (attempt 2 honest — attempt-1 red was journey assertions around the new prime fetch, fixed + isolated x5). AI Lead verification: firewall CLEAN; adversarial reviewer SHIP-WITH-NOTES (0 critical; read-only navigate gating verified triple-layered; coalescer byte-identical to 92d98d3; claude-journey frames pinned to the real WS). AI Lead review fixes applied (3dd5b9a): coalescer reset restored in effect cleanup (pending-scheduled state deadlocked app-scroll after an enabled toggle), prime fetch try/catch + gated to touch viewports (desktop no longer issues unused captures), classification survives spinner dismiss, NEW journey for the unclassified-thin auto-close path (mutation-resistant both directions). Reviewer nitpicks recorded-accepted: empty-success→app-scroll (safe via agentd per-message dispatch), slice(-2) mobile assertion (prime fetch is legitimate there). INTEGRATION: full-gate red x2 on the prepend journey under FULL-SUITE LOAD ONLY (isolated x5 green) — root-caused as PRODUCT defect: Chrome native scroll anchoring races manual prepend compensation → double-compensation jump; fixed with overflow-anchor:none on the overlay scroller (8dd6b59) — also removes a real on-device jump. INTEGRATED @ eb72d17 (--no-ff x2; reset-hard blocked by host policy). FULL GATE GREEN attempt 3: 200 CP + 243 dashboard tests, 21/21 smoke, 38 journeys, build. No agentd change — no rollout. PR next.