From 9afea90036f098a29e5c81df64af8433f07f673a Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 12:08:56 -0400 Subject: [PATCH 01/12] docs(program): FW6-TOUCH ship + rollout 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 1e4a594..e797388 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -60,3 +60,4 @@ - ~13:45Z (07-21) FW6-SCROLL SHIPPED: PR #94 MERGED (checks passed, main b98a93a) + DEPLOYED (SOURCE_COMMIT verified, health ok, agents:2). No agentd/binary changes. Owner phone swipe test on an attached pane = acceptance for device finding 4. - ~14:15Z (07-21) DEVICE FINDING 5 (owner): scroll "barely works" — gesture conflicts. AI Lead triage: (1) 5-line wheel quantization (~125px per jump + dead zone), (2) every tap focuses xterm textarea → Android keyboard pops → PTY resize mid-read, (3) 450ms cursor-arm hijacks slow scroll starts into arrow-key spam. Owner interview locked: agentd-native scroll op over terminal.navigate (copy-mode scroll-up/down N with pane-state dispatch: in-mode / alt+mouse app passthrough via send-keys -l SGR / alt no-mouse arrows / live-view copy-mode entry), explicit keyboard rail key (inputMode none by default on mobile), cursor-drag armed by rail key only (450ms timer DELETED). FW6-TOUCH lane launched (brief ed501a0). agentd rollout will be required. - ~15:30Z (07-21) FW6-TOUCH froze at `3008c25` (attempt 1, ~35 min, 5 impl commits, full green gate incl. Go). AI Lead review: SHIP with 1 integration fix — alt+mouse wheel branch divided count/3 STATELESSLY, so frame-coalesced 1-2-line messages always floored to 0 events (slow drags inert in codex panes — the exact symptom being fixed); added per-bridge signed wheelResidue accumulation (reset on window/pane select) + pure-helper Go test (eddb27f). Also stabilized the roster attach/type journey for real (gate on Connected label, 10/10 isolated) after it burned a second gate cycle. GATE ATTEMPT 2 FULLY GREEN. Lane + builder tmux session cleaned. PR next; agentd rollout required on both hosts. +- ~16:10Z (07-21) FW6-TOUCH SHIPPED: PR #95 MERGED (checks passed, main b835f78) + DEPLOYED (SOURCE_COMMIT verified, health ok, agents:2). agentd binaries rolled on BOTH hosts by AI Lead — pgrep single-process check applied per lesson (1 process each), reconnects clean. Owner phone test = acceptance for device finding 5: swipe-scroll a codex pane (smooth 1:1), tap without keyboard pop-up, Keyboard/Cursor rail keys. From 48175ab04e5cebbd75e9bd4ff339599b21f8baa5 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 13:39:29 -0400 Subject: [PATCH 02/12] docs(program): orchestration handoff to heavisidelinux AI Lead Co-Authored-By: Claude Fable 5 --- ...21-orchestration-handoff-heavisidelinux.md | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 tasks/2026-07-21-orchestration-handoff-heavisidelinux.md diff --git a/tasks/2026-07-21-orchestration-handoff-heavisidelinux.md b/tasks/2026-07-21-orchestration-handoff-heavisidelinux.md new file mode 100644 index 0000000..67aea7c --- /dev/null +++ b/tasks/2026-07-21-orchestration-handoff-heavisidelinux.md @@ -0,0 +1,41 @@ +# Orchestration handoff — AI Lead transfer to heavisidelinux (2026-07-21) + +You are taking over as AI Lead / orchestrator for the agent-command Frontend Command Center program (Autonomous Development Loop per SloaneVault "Integrator-Supervisor Harness"). The previous AI Lead ran from homelinux; orchestration moves here due to model quota. The Human Owner (Chris, S25 Ultra / Brave Android, single user) will give updated instructions directly in this session. + +## Current state (all verified live) + +- **Production**: main @ `b835f78` deployed on Coolify (apps-vps, compose resource `dcgs4ccgkco44w4gkkg0kks8`, verify via container env SOURCE_COMMIT; containers `dashboard-dcgs4…`/`control-plane-dcgs4…`). Health ok, agents:2. Public: https://agents.heavisidetechnology.com +- **agentd**: FW6-TOUCH binary live on BOTH hosts (user systemd service, `~/.local/bin/agentd`; backups `agentd.bak-fw6t`). After ANY binary swap: `pgrep -a agentd` must show EXACTLY ONE process per host (an orphan with the same token causes a ~3s register/kick loop that still looks "online"). +- **Branch**: `refactor/frontend-command-center` = merged to main through PR #95; branch and main are content-identical right now. PRs land via checks-pass → `gh pr merge --merge --admin`. +- **Program**: 0.4.x Frontend/Mobile UX COMPLETE through Wave 6 + 5 device-finding punch-list rounds (attach loop, settings GRANT, FW6-FOCUS, FW6-SCROLL, FW6-TOUCH). Receipts: `tasks/frontend-ux-log.md` (append-only ledger), `tasks/frontend-ux-status.md`, final report `tasks/frontend-ux-final-report.md`, briefs+handoffs in `tasks/`. + +## Open items + +1. **Owner device acceptance pending** for findings 4+5: swipe-scroll feel (codex transcript + copy-mode), tap-without-keyboard, Keyboard/Cursor rail keys. Owner may report tuning feedback — treat as tuning passes, not redesigns. +2. **Device checklist** (`docs/device-checklist.md`) — remaining items the owner hasn't confirmed (PWA/push incl. Brave "Use Google services for push messaging", cold-open restore, pinch font, letterbox, approval overlay, push deep link). +3. **BACKLOG.md** — journey-suite stabilization pass (2 flakes fixed at root already; launch-sheet fill timeout remains), Dependabot #39 (uuid <11.1.1, unused code path, next dep pass), batch-2 review LOWs. +4. **Next program queued (owner-selected): Hermes deep integration** — do not start without owner instruction. + +## Protocol (unchanged, owner-locked) + +- Builders are codex lanes (`codex --yolo`, gpt-5.6-sol xhigh) in tmux windows of THIS `agent-command` session, one worktree per lane (`~/dev/wt/ac-`, branch off `refactor/frontend-command-center`, never pushed). Brief in `tasks/`, completion token ` FROZEN ` printed in the pane; handoff file `tasks/frontend-ux-handoffs/.md`. +- AI Lead: verify freeze (firewall audit vs brief, diff review — the review chain catches real defects every round; last two lanes each shipped one), integrate with `--no-ff`, re-run the FULL gate from a tmux TTY split pane (`pnpm lint && pnpm typecheck && pnpm test:ci && pnpm test:smoke:dashboard && pnpm test:journeys && pnpm build` + Go build/vet/test in agents/agentd), then PR → admin-merge → deploy watch (SOURCE_COMMIT) → agentd rollout if agentd changed → owner phone test as acceptance. +- Autonomy: merges + deploys are autonomous-with-receipt (owner directive). Append every round to `tasks/frontend-ux-log.md` and push. +- Watchers: 5-minute digest loop per lane (commits, Working/idle, context/quota) + instant FROZEN/HELD token detection. Owner standing directive: check every 5 minutes. + +## Hard-won safety rules (do not relearn these) + +- **NEVER `tmux kill-session` on this machine's main tmux server** (historic server crash). Kill only windows/panes you created; lanes run their gates in PRIVATE `tmux -L` sockets or dedicated `new-session -A -s -builder` sessions — clean those up by name. +- Before `send-keys` to any pane: check `pane_current_command` (node = a live codex TUI). A mis-staged multi-line draft is cleared with a single Ctrl-C. +- send-keys prompt text and Enter as separate calls (~2s apart), then verify "Working". +- Playwright MUST run from a real tmux TTY (session shells swallow child output). Clear `apps/dashboard/.next` after route restructures. Kill port squatters (3210/3211) before journeys. +- Two journey tests were flaky under parallel load and are FIXED at root; if a new red appears once, re-run it isolated (×5) before burning a gate attempt — but never wave through a red without that evidence. +- DB (agent_console on db-vps 100.82.152.103): superuser only via `docker exec -u postgres postgres_db psql -h /var/run/postgresql`; migrations run as superuser MUST include GRANTs to `agent_console`. +- Coolify env rows are `encrypt()`-serialized — never write them as plain encrypted strings. + +## Machine notes for this host + +- Repo: `~/dev/agent-command` (synced to origin/refactor/frontend-command-center at handoff). Go at `~/.local/go/bin/go`. codex CLI available; weekly quota was ~21% at handoff — split heavy lanes toward homelinux (ssh homelinux) if it runs low. +- homelinux remains reachable via ssh for lane fan-out and has an identical layout; its tmux session `agent-command` window 0 was the previous orchestration home (windows there may be killed freely). + +Await the owner's updated instructions before launching any new work. From e1839a19f934d3e5454576e6ef5c71e012ef89f7 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 13:41:04 -0400 Subject: [PATCH 03/12] =?UTF-8?q?docs(program):=20orchestration=20transfer?= =?UTF-8?q?=20receipt=20=E2=80=94=20homelinux=20AI=20Lead=20signing=20off?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 e797388..2ef245f 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -61,3 +61,4 @@ - ~14:15Z (07-21) DEVICE FINDING 5 (owner): scroll "barely works" — gesture conflicts. AI Lead triage: (1) 5-line wheel quantization (~125px per jump + dead zone), (2) every tap focuses xterm textarea → Android keyboard pops → PTY resize mid-read, (3) 450ms cursor-arm hijacks slow scroll starts into arrow-key spam. Owner interview locked: agentd-native scroll op over terminal.navigate (copy-mode scroll-up/down N with pane-state dispatch: in-mode / alt+mouse app passthrough via send-keys -l SGR / alt no-mouse arrows / live-view copy-mode entry), explicit keyboard rail key (inputMode none by default on mobile), cursor-drag armed by rail key only (450ms timer DELETED). FW6-TOUCH lane launched (brief ed501a0). agentd rollout will be required. - ~15:30Z (07-21) FW6-TOUCH froze at `3008c25` (attempt 1, ~35 min, 5 impl commits, full green gate incl. Go). AI Lead review: SHIP with 1 integration fix — alt+mouse wheel branch divided count/3 STATELESSLY, so frame-coalesced 1-2-line messages always floored to 0 events (slow drags inert in codex panes — the exact symptom being fixed); added per-bridge signed wheelResidue accumulation (reset on window/pane select) + pure-helper Go test (eddb27f). Also stabilized the roster attach/type journey for real (gate on Connected label, 10/10 isolated) after it burned a second gate cycle. GATE ATTEMPT 2 FULLY GREEN. Lane + builder tmux session cleaned. PR next; agentd rollout required on both hosts. - ~16:10Z (07-21) FW6-TOUCH SHIPPED: PR #95 MERGED (checks passed, main b835f78) + DEPLOYED (SOURCE_COMMIT verified, health ok, agents:2). agentd binaries rolled on BOTH hosts by AI Lead — pgrep single-process check applied per lesson (1 process each), reconnects clean. Owner phone test = acceptance for device finding 5: swipe-scroll a codex pane (smooth 1:1), tap without keyboard pop-up, Keyboard/Cursor rail keys. +- ~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. From 92d98d3a41bbf8eccba76ac6c4f183e89d228ee0 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 16:03:14 -0400 Subject: [PATCH 04/12] docs(program): FW6-HIST brief + finding-6 ledger entry Co-Authored-By: Claude Fable 5 --- tasks/2026-07-21-fw6-hist-brief.md | 49 ++++++++++++++++++++++++++++++ tasks/frontend-ux-log.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 tasks/2026-07-21-fw6-hist-brief.md diff --git a/tasks/2026-07-21-fw6-hist-brief.md b/tasks/2026-07-21-fw6-hist-brief.md new file mode 100644 index 0000000..0932788 --- /dev/null +++ b/tasks/2026-07-21-fw6-hist-brief.md @@ -0,0 +1,49 @@ +# FW6-HIST — Local history overlay for attached-terminal touch scrolling (device finding 6) + +Lane: FW6-HIST · Machine: homelinux · Worktree: `~/dev/wt/ac-fw6-hist` · Branch: `refactor/fw6-hist` (off `refactor/frontend-command-center`; local, do NOT push) +Owner device finding (S25 Ultra, production): FW6-TOUCH server-side scrolling is "slow, error-filled, and unusable for the most part"; the earlier local/DOM scroll experience was "smooth and fast" with no character artifacts, just size-limited. Owner interview locked the direction below — do not re-litigate. + +## Root causes (verified by AI Lead — do not re-derive) + +1. Server-side scroll physics: every coalesced swipe frame = WS `navigate {op:'scroll'}` → CP → agentd `display-message` + `send-keys` subprocess execs (serialized under the manager lock) → full alt-screen tmux repaint → full-frame xterm rebuild on the phone. Feel is bounded by RTT + two process spawns + full redraw per step; it can never match native browser scroll. +2. Artifacts (owner: codex panes, transient while scrolling): torn full-frame copy-mode repaints rendered mid-stream, plus the read-state-once-per-message race in the four-branch agentd dispatch that can deliver literal SGR/arrow bytes to a pane whose mode changed. Local-first scrolling removes both classes structurally — touch never injects tmux input. +3. KEY probe fact (heavisidelinux, live codex pane): codex runs on the tmux NORMAL screen (`alternate_on=0`, `mouse_any_flag=0`) and accumulates real pane history (5,423 lines observed); `capture-pane -S -5300` returns clean, readable transcript text. Therefore capture-pane range paging — the exact feed the ScrollbackPager/History dialog already uses in production (`POST /v1/sessions/:id/scrollback`, mode `range`) — serves shell AND codex panes through ONE uniform path. No snapshot/pipe-pane stream, no protocol change, no agentd change. + +## Design (owner-locked) + +### 1. New inline `TerminalHistoryOverlay` (dashboard-only) + +- Vertical swipe-up on an attached tmux terminal (writable OR read-only — history reads need no write permission) opens an inline overlay covering the terminal surface (NOT a Radix modal; the existing History dialog stays untouched). +- Content: plain-text scrollback lines fetched via the existing `getSessionScrollback(sessionId, {mode:'range', strip_ansi:true})` path, using the already-threaded `historySessionId` (same default/fallback semantics as ScrollbackPager — it must follow the SELECTED pane after FW6-FOCUS window/pane switches). +- Initial fetch = newest `SCROLLBACK_PAGE_LINES` (500) page, rendered anchored at the bottom. Scrolling near the top auto-loads older pages (reuse `scrollbackPaging.ts` helpers and ScrollbackPager's prepend-with-scroll-compensation pattern) — history is effectively unlimited; show a small loading affordance while a page is in flight and stop when `hasOlder` is false. +- Scrolling is 100% native DOM (`overflow-y: auto`, momentum): virtualized like ScrollbackPager but at terminal density (mono font, current terminal font size ≈14px line metrics, terminal background) — not the pager's 32px rows. +- Dismiss: over-scrolling past the bottom edge OR a visible "Live" pill returns to the live attached view. The WS attachment stays connected underneath the whole time — closing is instant, no reattach. Detach/leave/session-switch closes the overlay. +- Overlay content is snapshot semantics (like the History dialog): re-opening refetches the newest page. No live-tail inside the overlay. +- If no session id is resolvable for the current pane, swipe-up is a graceful no-op. + +### 2. Touch dispatch rework (`useTerminalTouchScroll.ts`) + +- For attached tmux terminals (the current `navigate` path): vertical swipe NO LONGER sends anything to tmux. Swipe-up opens the overlay (hand the gesture off so the open feels continuous — at minimum the overlay opens bottom-anchored and immediately responds to native touch scrolling). Swipe-down at live view stays a no-op. +- Delete the touch-path `navigate {op:'scroll'}` emission, the rAF coalescer, and the SGR wheel-report synthesis FOR THE TMUX PATH, plus the now-unused exported pure helpers and their tests. `TerminalView`'s `handleNavigateScroll`/`onNavigateScroll` wiring goes too if nothing else consumes it. +- KEEP unchanged: normal-buffer local `terminal.scrollLines()` path (non-tmux/desktop must not regress); the non-tmux alt-buffer SGR `sendInput` fallback (direct PTY input, no agentd round trip); pinch-zoom, horizontal pan/window swipe, selection, context menu, Keyboard/Cursor rail keys and their gating — all exactly as-is. +- Protocol, schema, CP relay, and agentd scroll op stay UNTOUCHED (desktop/API callers may use the op; touch just stops calling it). No binary rollout this round. + +## Work items + +1. `TerminalHistoryOverlay` component + paging/virtualization (reuse `scrollbackPaging.ts`; extract shared helpers rather than duplicating ScrollbackPager logic where reasonable). +2. Touch dispatcher rework: overlay handoff, tmux-path emission deletion, dead-helper cleanup; `TerminalView`/`PersistentTerminalHost` wiring for the overlay (`historySessionId` threading reuse). +3. Unit tests: gesture gating matrix (attached tmux → overlay incl. read-only; normal buffer → scrollLines; non-tmux alt+mouse → SGR fallback unchanged; no-session → no-op), paging math, dismiss thresholds. +4. Journeys: swipe-up on an attached terminal opens the overlay AND emits ZERO `navigate scroll` frames / ZERO SGR bytes on the terminal WS; older-page load prepends with stable scroll position; bottom over-scroll dismisses back to live without a new terminal WS connection; overlay follows the selected session after a window switch (extend the fw6-focus journey mock); Keyboard/Cursor rail 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/**` (new overlay file, PersistentTerminalHost/TerminalSurface wiring, `scrollbackPaging.ts` extraction), related unit tests, `tests/journeys/**`. You may NOT edit: `agents/agentd/**`, `packages/**`, `services/**`, `deploy/**`, the descriptor-key/attachment contract in `terminalHostStore.ts`, letterbox logic, Focus/zoom (`mobileFocus.ts`), the Keyboard/Cursor rail keys, the existing ScrollbackPager dialog behavior (extraction refactors must keep its tests green), gesture timers not named above. + +## 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. Run `pnpm install --frozen-lockfile` first if `node_modules` is absent. Commit per work item, prefix `feat(hist):`. ≤3 attempts per failure then hold. Known journey load-flake (launch-sheet fill timeout): if it reds once, re-run it isolated (×5) before counting an attempt. + +## Done + +Handoff `tasks/frontend-ux-handoffs/fw6-hist.md` (same frontmatter format as fw6-touch.md), committed, then print exactly: +`FW6-HIST FROZEN ` diff --git a/tasks/frontend-ux-log.md b/tasks/frontend-ux-log.md index 2ef245f..490d2e1 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -62,3 +62,4 @@ - ~15:30Z (07-21) FW6-TOUCH froze at `3008c25` (attempt 1, ~35 min, 5 impl commits, full green gate incl. Go). AI Lead review: SHIP with 1 integration fix — alt+mouse wheel branch divided count/3 STATELESSLY, so frame-coalesced 1-2-line messages always floored to 0 events (slow drags inert in codex panes — the exact symptom being fixed); added per-bridge signed wheelResidue accumulation (reset on window/pane select) + pure-helper Go test (eddb27f). Also stabilized the roster attach/type journey for real (gate on Connected label, 10/10 isolated) after it burned a second gate cycle. GATE ATTEMPT 2 FULLY GREEN. Lane + builder tmux session cleaned. PR next; agentd rollout required on both hosts. - ~16:10Z (07-21) FW6-TOUCH SHIPPED: PR #95 MERGED (checks passed, main b835f78) + DEPLOYED (SOURCE_COMMIT verified, health ok, agents:2). agentd binaries rolled on BOTH hosts by AI Lead — pgrep single-process check applied per lesson (1 process each), reconnects clean. Owner phone test = acceptance for device finding 5: swipe-scroll a codex pane (smooth 1:1), tap without keyboard pop-up, Keyboard/Cursor rail keys. - ~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. From 7f013672c08ae778ae1541c14022df71a6f28cbd Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 16:13:31 -0400 Subject: [PATCH 05/12] feat(hist): add inline terminal history overlay --- .../components/terminal/ScrollbackPager.tsx | 19 +- .../terminal/TerminalHistoryOverlay.tsx | 292 ++++++++++++++++++ .../components/terminal/scrollbackPaging.ts | 61 ++++ 3 files changed, 363 insertions(+), 9 deletions(-) create mode 100644 apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx diff --git a/apps/dashboard/src/components/terminal/ScrollbackPager.tsx b/apps/dashboard/src/components/terminal/ScrollbackPager.tsx index 9205418..e2ea619 100644 --- a/apps/dashboard/src/components/terminal/ScrollbackPager.tsx +++ b/apps/dashboard/src/components/terminal/ScrollbackPager.tsx @@ -10,6 +10,8 @@ import { useNotifications } from '@/stores/notifications'; import { SCROLLBACK_PAGE_LINES, advanceScrollbackSelection, + compensateScrollbackPrepend, + contentScrollbackLines, initialScrollbackRange, numberScrollbackLines, olderScrollbackRange, @@ -33,13 +35,6 @@ const LINE_HEIGHT = 32; const OVERSCAN = 12; const VIEWPORT_LINE_ESTIMATE = 30; -function contentLines(content: unknown): string[] { - if (typeof content !== 'string' || content.length === 0) return []; - const lines = content.split('\n'); - if (content.endsWith('\n')) lines.pop(); - return lines; -} - export function ScrollbackPager({ sessionId, open, onClose }: ScrollbackPagerProps) { const [pages, setPages] = useState([]); const [filter, setFilter] = useState(''); @@ -68,7 +63,7 @@ export function ScrollbackPager({ sessionId, open, onClose }: ScrollbackPagerPro } return { range, - lines: contentLines(response.result?.content), + lines: contentScrollbackLines(response.result?.content), }; }, [sessionId] @@ -126,7 +121,13 @@ export function ScrollbackPager({ sessionId, open, onClose }: ScrollbackPagerPro setPages((current) => [page, ...current]); setHasOlder(page.lines.length >= SCROLLBACK_PAGE_LINES); requestAnimationFrame(() => { - if (element) element.scrollTop += element.scrollHeight - previousHeight; + if (element) { + element.scrollTop = compensateScrollbackPrepend( + element.scrollTop, + previousHeight, + element.scrollHeight + ); + } }); } catch (loadError) { setError( diff --git a/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx new file mode 100644 index 0000000..87358b4 --- /dev/null +++ b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx @@ -0,0 +1,292 @@ +'use client'; + +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { ArrowDown, Loader2, RotateCcw } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { getSessionScrollback } from '@/lib/api'; +import { + SCROLLBACK_PAGE_LINES, + compensateScrollbackPrepend, + contentScrollbackLines, + initialScrollbackRange, + isNearScrollbackTop, + numberScrollbackLines, + olderScrollbackRange, + resolveScrollbackVirtualWindow, + shouldDismissHistoryOverscroll, + type ScrollbackRange, +} from './scrollbackPaging'; + +interface TerminalHistoryOverlayProps { + sessionId: string; + open: boolean; + fontSize: number; + onClose: () => void; +} + +interface HistoryPage { + range: ScrollbackRange; + lines: string[]; +} + +const OVERSCAN_LINES = 12; + +export function TerminalHistoryOverlay({ + sessionId, + open, + fontSize, + onClose, +}: TerminalHistoryOverlayProps) { + const [pages, setPages] = useState([]); + const [loadingInitial, setLoadingInitial] = useState(false); + const [loadingOlder, setLoadingOlder] = useState(false); + const [hasOlder, setHasOlder] = useState(true); + const [error, setError] = useState(null); + const [scrollTop, setScrollTop] = useState(0); + const [viewportHeight, setViewportHeight] = useState(0); + const scrollRef = useRef(null); + const generationRef = useRef(0); + const loadingOlderRef = useRef(false); + 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 loadInitial = useCallback(async () => { + const generation = ++generationRef.current; + setLoadingInitial(true); + setError(null); + setPages([]); + setHasOlder(true); + setScrollTop(0); + try { + const page = await fetchPage(initialScrollbackRange()); + if (generationRef.current !== generation) return; + setPages([page]); + setHasOlder(page.lines.length >= SCROLLBACK_PAGE_LINES); + requestAnimationFrame(() => { + const element = scrollRef.current; + if (!element || generationRef.current !== generation) return; + element.scrollTop = element.scrollHeight; + setScrollTop(element.scrollTop); + setViewportHeight(element.clientHeight); + }); + } catch (loadError) { + if (generationRef.current !== generation) return; + setError( + loadError instanceof Error ? loadError.message : 'Terminal history could not be loaded.' + ); + } finally { + if (generationRef.current === generation) setLoadingInitial(false); + } + }, [fetchPage]); + + useEffect(() => { + if (!open) { + generationRef.current += 1; + loadingOlderRef.current = false; + overscrollStartRef.current = null; + return; + } + void loadInitial(); + }, [loadInitial, open]); + + useEffect(() => { + if (!open) return; + const element = scrollRef.current; + if (!element) return; + const updateHeight = () => setViewportHeight(element.clientHeight); + updateHeight(); + const observer = new ResizeObserver(updateHeight); + observer.observe(element); + return () => observer.disconnect(); + }, [open]); + + const loadOlder = useCallback(async () => { + if (loadingOlderRef.current || !hasOlder) return; + const generation = generationRef.current; + const currentOldest = pages[0]?.range ?? initialScrollbackRange(); + const range = olderScrollbackRange(currentOldest); + const element = scrollRef.current; + const previousHeight = element?.scrollHeight ?? 0; + const previousTop = element?.scrollTop ?? 0; + loadingOlderRef.current = true; + setLoadingOlder(true); + setError(null); + try { + const page = await fetchPage(range); + if (generationRef.current !== generation) return; + setPages((current) => [page, ...current]); + setHasOlder(page.lines.length >= SCROLLBACK_PAGE_LINES); + requestAnimationFrame(() => { + if (!element || generationRef.current !== generation) return; + const nextTop = compensateScrollbackPrepend( + previousTop, + previousHeight, + element.scrollHeight + ); + element.scrollTop = nextTop; + setScrollTop(nextTop); + }); + } catch (loadError) { + if (generationRef.current !== generation) return; + setError( + loadError instanceof Error ? loadError.message : 'Older history could not be loaded.' + ); + } finally { + if (generationRef.current === generation) { + loadingOlderRef.current = false; + setLoadingOlder(false); + } + } + }, [fetchPage, hasOlder, pages]); + + const allLines = useMemo( + () => pages.flatMap((page) => numberScrollbackLines(page.range, page.lines)), + [pages] + ); + const virtualWindow = resolveScrollbackVirtualWindow({ + lineCount: allLines.length, + scrollTop, + viewportHeight, + lineHeight, + overscan: OVERSCAN_LINES, + }); + const visibleLines = allLines.slice(virtualWindow.startIndex, virtualWindow.endIndex); + + if (!open) return null; + + return ( +
+
+
+ {loadingOlder ? 'Loading older…' : hasOlder ? 'History' : 'Start of history'} +
+ +
+ + {error && ( +
+ {error} + +
+ )} + +
{ + const element = event.currentTarget; + setScrollTop(element.scrollTop); + setViewportHeight(element.clientHeight); + if (isNearScrollbackTop(element.scrollTop, lineHeight)) void loadOlder(); + }} + onTouchStart={(event) => { + const touch = event.touches[0]; + const element = event.currentTarget; + if (!touch) return; + overscrollStartRef.current = { + y: touch.clientY, + atBottom: element.scrollHeight - element.clientHeight - element.scrollTop <= 2, + }; + }} + onTouchMove={(event) => { + const start = overscrollStartRef.current; + const touch = event.touches[0]; + if (!start || !touch) return; + if (shouldDismissHistoryOverscroll(start.atBottom, touch.clientY - start.y)) { + overscrollStartRef.current = null; + onClose(); + } + }} + onTouchEnd={() => { overscrollStartRef.current = null; }} + onTouchCancel={() => { overscrollStartRef.current = null; }} + > + {loadingInitial ? ( +
+
+ ) : allLines.length === 0 ? ( +
+ No terminal history was captured. +
+ ) : ( +
+ {visibleLines.map((line, offset) => { + const virtualIndex = virtualWindow.startIndex + offset; + return ( +
+ {line.text || ' '} +
+ ); + })} +
+ )} +
+
+ ); +} diff --git a/apps/dashboard/src/components/terminal/scrollbackPaging.ts b/apps/dashboard/src/components/terminal/scrollbackPaging.ts index 1958bed..b0e268e 100644 --- a/apps/dashboard/src/components/terminal/scrollbackPaging.ts +++ b/apps/dashboard/src/components/terminal/scrollbackPaging.ts @@ -1,4 +1,6 @@ export const SCROLLBACK_PAGE_LINES = 500; +export const HISTORY_OVERSCROLL_DISMISS_PX = 48; +export const SCROLLBACK_TOP_THRESHOLD_LINES = 6; export interface ScrollbackRange { startLine: number; @@ -16,6 +18,18 @@ export interface ScrollbackLineSelection { awaitingExtent: boolean; } +export interface ScrollbackVirtualWindow { + startIndex: number; + endIndex: number; +} + +export function contentScrollbackLines(content: unknown): string[] { + if (typeof content !== 'string' || content.length === 0) return []; + const lines = content.split('\n'); + if (content.endsWith('\n')) lines.pop(); + return lines; +} + export function initialScrollbackRange(): ScrollbackRange { return { startLine: -SCROLLBACK_PAGE_LINES, @@ -31,6 +45,53 @@ export function olderScrollbackRange(range: ScrollbackRange): ScrollbackRange { }; } +export function compensateScrollbackPrepend( + previousScrollTop: number, + previousScrollHeight: number, + nextScrollHeight: number +): number { + return previousScrollTop + Math.max(0, nextScrollHeight - previousScrollHeight); +} + +export function isNearScrollbackTop( + scrollTop: number, + lineHeight: number, + thresholdLines = SCROLLBACK_TOP_THRESHOLD_LINES +): boolean { + return scrollTop <= Math.max(1, lineHeight) * thresholdLines; +} + +export function resolveScrollbackVirtualWindow({ + lineCount, + scrollTop, + viewportHeight, + lineHeight, + overscan, +}: { + lineCount: number; + scrollTop: number; + viewportHeight: number; + lineHeight: number; + overscan: number; +}): ScrollbackVirtualWindow { + const safeLineHeight = Math.max(1, lineHeight); + const safeOverscan = Math.max(0, Math.floor(overscan)); + const startIndex = Math.max(0, Math.floor(scrollTop / safeLineHeight) - safeOverscan); + const visibleCount = Math.ceil(Math.max(0, viewportHeight) / safeLineHeight); + return { + startIndex, + endIndex: Math.min(lineCount, startIndex + visibleCount + safeOverscan * 2), + }; +} + +export function shouldDismissHistoryOverscroll( + startedAtBottom: boolean, + touchDeltaY: number, + threshold = HISTORY_OVERSCROLL_DISMISS_PX +): boolean { + return startedAtBottom && touchDeltaY <= -Math.max(1, threshold); +} + export function numberScrollbackLines( range: ScrollbackRange, lines: string[] From 29377828c1dd1441923b8fc267d4ee536c271c8a Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 16:16:48 -0400 Subject: [PATCH 06/12] feat(hist): hand off tmux touch scroll to history --- .../dashboard/src/components/TerminalView.tsx | 23 ++- .../components/terminal/TerminalSurface.tsx | 16 ++ .../src/hooks/useTerminalTouchScroll.ts | 170 ++++++++---------- 3 files changed, 105 insertions(+), 104 deletions(-) diff --git a/apps/dashboard/src/components/TerminalView.tsx b/apps/dashboard/src/components/TerminalView.tsx index d2706d8..064bdc7 100644 --- a/apps/dashboard/src/components/TerminalView.tsx +++ b/apps/dashboard/src/components/TerminalView.tsx @@ -59,6 +59,7 @@ export function TerminalView({ const controllerReadOnlyRef = useRef(false); const [searchOpen, setSearchOpen] = useState(false); const [historyOpen, setHistoryOpen] = useState(false); + const [historyOverlaySessionId, setHistoryOverlaySessionId] = useState(null); const [stickyCtrlMode, setStickyCtrlMode] = useState('inactive'); const [keyboardActive, setKeyboardActive] = useState(false); const [cursorArmed, setCursorArmed] = useState(false); @@ -268,10 +269,19 @@ export function TerminalView({ stickyCtrlModeRef.current = 'inactive'; setStickyCtrlMode('inactive'); resetTouchModes(); + setHistoryOverlaySessionId(null); }, [resetTouchModes, status]); - const handleNavigateScroll = useCallback((lines: number) => { - navigate({ type: 'navigate', op: 'scroll', lines }); - }, [navigate]); + const closeHistoryOverlay = useCallback(() => setHistoryOverlaySessionId(null), []); + const openHistoryOverlay = useCallback(() => { + if (!tmuxSessionKey || !historySessionId) return; + setHistoryOverlaySessionId(historySessionId); + }, [historySessionId, tmuxSessionKey]); + const historyOverlayOpen = historyOverlaySessionId === historySessionId; + useEffect(() => { + if (historyOverlaySessionId && historyOverlaySessionId !== historySessionId) { + setHistoryOverlaySessionId(null); + } + }, [historyOverlaySessionId, historySessionId]); const touchScrollRef = useTerminalTouchScroll({ enabled: touchInputModeEnabled, termRef, @@ -284,7 +294,8 @@ export function TerminalView({ writable: terminalWritable, onScrollInput: sendInput, tmuxSessionKey, - onNavigateScroll: handleNavigateScroll, + historySessionId, + onOpenHistory: openHistoryOverlay, onHorizontalSwipe: (direction) => { termRef.current?.dispatchEvent(new CustomEvent('terminal-window-swipe', { bubbles: true, @@ -419,6 +430,10 @@ export function TerminalView({ stickyCtrlMode={stickyCtrlMode} onStickyCtrlEvent={dispatchStickyCtrl} onOpenHistory={() => setHistoryOpen(true)} + historyOverlayOpen={historyOverlayOpen} + historySessionId={historySessionId} + historyFontSize={terminalFontSize} + onCloseHistoryOverlay={closeHistoryOverlay} tmuxPrefix={tmuxPrefix} onPreviousMark={previousMark} onNextMark={nextMark} diff --git a/apps/dashboard/src/components/terminal/TerminalSurface.tsx b/apps/dashboard/src/components/terminal/TerminalSurface.tsx index 643047f..56e6600 100644 --- a/apps/dashboard/src/components/terminal/TerminalSurface.tsx +++ b/apps/dashboard/src/components/terminal/TerminalSurface.tsx @@ -9,6 +9,7 @@ import type { StickyCtrlEvent, StickyCtrlMode } from '@/components/mobile/sticky import { Button } from '@/components/ui/button'; import { cn } from '@/lib/utils'; import type { ConnectionStatus, XTerminal } from './types'; +import { TerminalHistoryOverlay } from './TerminalHistoryOverlay'; import { TerminalSearchSheet, type TerminalSearchControlsProps } from './TerminalSearch'; import { TerminalTouchSelection } from './TerminalTouchSelection'; import type { TerminalCommandMarkView } from './commandMarks'; @@ -32,6 +33,10 @@ interface TerminalSurfaceProps { stickyCtrlMode: StickyCtrlMode; onStickyCtrlEvent: (event: StickyCtrlEvent) => void; onOpenHistory: () => void; + historyOverlayOpen: boolean; + historySessionId: string; + historyFontSize: number; + onCloseHistoryOverlay: () => void; tmuxPrefix?: string; onPreviousMark: () => void; onNextMark: () => void; @@ -68,6 +73,10 @@ export function TerminalSurface({ stickyCtrlMode, onStickyCtrlEvent, onOpenHistory, + historyOverlayOpen, + historySessionId, + historyFontSize, + onCloseHistoryOverlay, tmuxPrefix, onPreviousMark, onNextMark, @@ -161,6 +170,13 @@ export function TerminalSurface({