From aecf9a43676a2c5f873081d7fbf96a04a5b6aa9e Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 19:04:17 -0400 Subject: [PATCH 01/26] =?UTF-8?q?docs(program):=20PROGRAM=20COMPLETE=20?= =?UTF-8?q?=E2=80=94=20final=20report,=20closing=20receipts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5 --- tasks/frontend-ux-final-report.md | 38 +++++++++++++++++++++++++++++++ tasks/frontend-ux-log.md | 1 + tasks/frontend-ux-metrics.jsonl | 1 + tasks/frontend-ux-status.md | 2 +- 4 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 tasks/frontend-ux-final-report.md diff --git a/tasks/frontend-ux-final-report.md b/tasks/frontend-ux-final-report.md new file mode 100644 index 00000000..0f95aec0 --- /dev/null +++ b/tasks/frontend-ux-final-report.md @@ -0,0 +1,38 @@ +# Frontend Command Center UX Program — Final Report + +Program: `tasks/2026-07-20-frontend-tmux-ux-master-plan.md` · Started 2026-07-20 ~13:30Z · Completed 2026-07-20 ~23:05Z (~10h wall clock) · AI Lead: Claude (Fable 5) · Builders: codex gpt-5.6-sol (xhigh), 10 lanes + 5 correction rounds across homelinux + heavisidelinux. + +## Accepted outcome + +All five waves shipped to production individually (PRs #86–#90, each CI-green, independently reviewed, deploy-verified by `SOURCE_COMMIT`). Final state: main `6e928a4`, tagged **v0.4.0**, live at agents.heavisidetechnology.com with both hosts connected on the new agentd (topology events active). + +The app now: opens into the Command Center (fleet-first landing, old dashboard deleted); provides native-grade tmux interaction (live topology window strip, window/pane management, splits/zoom, scrollback paging + search, desktop 2-up terminals, mobile quick-switch, persistent cross-route terminal); layers agent superpowers on top (attention overlay with inline approve/deny, prompt composer with read-only gating, unified fleet on one aggregate endpoint, health badges, ⌘K palette); and is operable end-to-end (Add Host enrollment flow, launch rail, unified attention surface, modernized TS7/React19/Zod4 stack, 14-journey Playwright suite). + +## Deliverable references + +Frozen lanes (handoffs in `tasks/frontend-ux-handoffs/`): FW1-MODERN 76d3c5e · FW1-TMUX-GO 7a8e6ee (R2) · FW2-CONTRACTS 38c1a12 (R2) · FW2-TERM 9b34dfb · FW3-SHELL 5bba177 · FW3-TMUX-UI c2bcfbe (R2) · FW4-FLEET f0d7b89 (R2) · FW4-SURFACES 295c9c0 (R2) · FW5-POLISH 9ceed37 · FW5-QA 75d1839. Acceptance: `tasks/frontend-ux-acceptance-checklist.md` (reconciled with evidence per box). Board/log/metrics: `tasks/frontend-ux-status.md`, `frontend-ux-log.md`, `frontend-ux-metrics.jsonl`. + +## Defects caught internally (never reached production) + +1. **Critical (Wave 1, reviewer HOLD):** agentd's topology emission would have crash-looped the agent socket against the deployed CP — shipped default-off, CP tolerance added in Wave 2, then fleet-wide rollout. +2. tmux hook pollution on agentd crash; stale terminal-viewer leak (Wave 1 R2). +3. Fleet endpoint unbounded scan + N+1 and missing role check (Wave 2 R2). +4. Topology staleness freeze + duplicate roster fetches on the hot path (Wave 3 R2); optimistic-confirm and version-gating refinements. +5. Aggregate reconcile clobbering fresher WS state; read-only bypass via composer/Respond; Ctrl+K readline collision; one-time-token heap lingering (Wave 4 R2s). +6. **AI Lead's own brief error:** ordered deletion of a "dead" JSON terminal fallback that a pre-hello race can still exercise — caught by the Wave-5 reviewer, fallback restored, full migration backlogged. +7. Deploy-layer seams (Docker workspace copy, deleted eslintrc) and 16 CodeRabbit findings triaged (real ones fixed, rest resolved with justification). + +## Autonomy actions & human interventions + +- Owner directives honored mid-program: full autonomy for merges/deploys; both-machine lane distribution; tmux window/pane hygiene + reuse (with a caught-before-damage mis-key into a live owner codex pane, now a written rule); homelinux host enrollment + agentd rollouts (owner-executed `!` commands where the permission layer blocked credential/daemon actions — no workarounds attempted). +- Liveness saves: two staged-but-unsubmitted codex prompts caught by watchers; codex safety-dialog kept on assigned model; environment diagnoses (stale `.next` cache, non-TTY Playwright hangs) resolved with written lessons. + +## Remaining for owner + +1. **On-device PWA pass** (install, push, terminal typing on your iPhone) — the only unchecked acceptance item that needs you; everything else was verified in Chromium at mobile/desktop viewports. +2. BACKLOG.md carries four scoped follow-ups: complete binary-only terminal migration, probe short-circuit polish, window-strip arrow auto-activation review, docs-site screenshot. +3. GitHub release notes for v0.4.0 generate from the CHANGELOG if the release workflow is run. + +## Recovery + +Every wave is an independent merge commit on main (`d565b00`→`effab04`→`f3df15d`→`fa0ba72`→`6e928a4`); rollback = redeploy any prior SHA. agentd backups: `~/.local/bin/agentd.bak-fw2` (heavisidelinux). Pre-program DB backup unchanged (no migrations were needed — 038 remains the head). diff --git a/tasks/frontend-ux-log.md b/tasks/frontend-ux-log.md index 9d31e5c9..58c202d9 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -42,3 +42,4 @@ - Wave-4 DEPLOYED (fa0ba72 verified, health ok). Add Host flow, fleet unification, attention overlay, composer, palette all live. - ~06:30Z FW5-POLISH froze at `9ceed37` (attempt 1): gate re-run green in tmux TTY (20/20 smoke, 145 dashboard tests), firewall clean, web-vitals the only (allowed) dep. INTEGRATED (squash). Gate window killed post-run per owner reuse-panes directive. - ~07:50Z WAVE 5 COMPLETE + PROGRAM GATE GREEN at d7583f2 (198 CP + 145 dashboard tests, 20/20 smoke, 14/14 journeys, build, Go). Wave-5 review SHIP-WITH-NOTES: MEDIUM was AI Lead brief error (JSON fallback deletion) — fallback restored, full binary-only migration backlogged; CHANGELOG corrected; LOW/INFO items backlogged. Incident: gate command mis-keyed into a live owner codex pane (pane-index assumption) — caught before submission, composer cleared, pane-targeting rule added to memory. FW5-QA honesty note: flagged 4 NOT-METs rather than rubber-stamping; 2 resolved at integration, 2 remain for owner final review (on-device PWA pass; docs-site screenshot backlogged). +- ~23:05Z Wave-5 PR #90 MERGED (6e928a4) + DEPLOYED (SOURCE_COMMIT verified; both agents reconnected after CP restart). Tagged v0.4.0. Wave-5 windows/worktrees cleaned. PROGRAM COMPLETE — Final Report: tasks/frontend-ux-final-report.md. diff --git a/tasks/frontend-ux-metrics.jsonl b/tasks/frontend-ux-metrics.jsonl index 7f99e23e..4a99e1f9 100644 --- a/tasks/frontend-ux-metrics.jsonl +++ b/tasks/frontend-ux-metrics.jsonl @@ -25,3 +25,4 @@ {"ts":"2026-07-21T05:40:00Z","event":"wave_deployed","wave":4,"sha":"fa0ba72"} {"ts":"2026-07-21T06:30:00Z","event":"lane_frozen","lane":"FW5-POLISH","attempt":1,"frozen_sha":"9ceed37","verdict":"accepted"} {"ts":"2026-07-21T07:50:00Z","event":"wave_complete","wave":5,"reviewer_verdict":"SHIP-WITH-NOTES","gate":"green","program":"final gate green"} +{"ts":"2026-07-20T23:05:00Z","event":"program_complete","final_sha":"6e928a4","tag":"v0.4.0","waves":5,"lanes":10,"correction_rounds":5,"prs":[86,87,88,89,90],"wall_hours":10} diff --git a/tasks/frontend-ux-status.md b/tasks/frontend-ux-status.md index 2afc856e..bd6d4af2 100644 --- a/tasks/frontend-ux-status.md +++ b/tasks/frontend-ux-status.md @@ -54,4 +54,4 @@ Handoffs land in `tasks/frontend-ux-handoffs/` (heavisidelinux lanes commit hand - Firewall breach ⇒ objective correction (revert + re-task). Red wave gate ⇒ wave held, independent lanes may continue. ## Decisions pending Human Owner -(none — full program authorized to run autonomously; owner reviews at program end. Wave 1 merged @ d565b00 and deployed.) +(PROGRAM COMPLETE @ 6e928a4, v0.4.0 — awaiting owner final review + on-device PWA pass. Final Report: tasks/frontend-ux-final-report.md) From ae1298ef84f598390c431edff29f3400631488ba Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 19:27:13 -0400 Subject: [PATCH 02/26] =?UTF-8?q?docs(plan):=20mobile=20tmux=20UX=20progra?= =?UTF-8?q?m=20plan=20=E2=80=94=20study=20synthesis,=20prior-art=20mechani?= =?UTF-8?q?sms,=20backlog=20assessment=20(for=20owner=20review)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5 --- tasks/2026-07-20-mobile-tmux-ux-plan.md | 80 +++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 tasks/2026-07-20-mobile-tmux-ux-plan.md diff --git a/tasks/2026-07-20-mobile-tmux-ux-plan.md b/tasks/2026-07-20-mobile-tmux-ux-plan.md new file mode 100644 index 00000000..49ed15a4 --- /dev/null +++ b/tasks/2026-07-20-mobile-tmux-ux-plan.md @@ -0,0 +1,80 @@ +# Mobile tmux UX Program — Plan for Owner Assessment (2026-07-20) + +Evidence: three-agent deep study at main `6e928a4` (v0.4.0) — element-by-element mobile terminal audit, tap-by-tap journey traces, known-issues + backlog inventory. Target device (owner facts, 2026-07-20): **Samsung Galaxy S25 Ultra, Brave browser (Chromium), thumb-only (no S Pen), single user**. All prior verification assumed iPhone 390×844 in headless Chromium; the actual target is ~412×915 with Android keyboard semantics and adb-debuggable. + +## What the study found (condensed) + +**Two structural root causes of "tmux is still challenged":** +1. **All tmux controls vanish while typing.** `html[data-virtual-keyboard-open] [data-terminal-key-controls] { display:none }` hides BOTH key strips the moment the OS keyboard rises — no Esc, Ctrl-C, arrows, or prefix exactly when interacting. Interrupting an agent mid-type = dismiss keyboard → tap → refocus. +2. **SIGWINCH churn + size clobbering.** Every visualViewport resize/scroll/keyboard animation sends a real tmux resize; full-screen TUIs repaint-storm; a phone attach shrinks the tmux window for the desktop client too (tmux sizes to smallest client). + +**Owner-confirmed pain, quantified:** the terminal gets **~303px of 844 (≈22 rows at hard-coded 11px)** keyboard-closed — chrome is ~55% of the screen: app header + shell header + mode toggle + card header + window strip + toolbar + TWO always-on key strips (~112px, duplicated arrows) + composer. Keyboard-open: **~5–8 rows**. A plain SSH client gives ~50/~30. Enter and arrows are the LAST keys on an overflowing strip. + +**Navigation friction:** in-app selection never carries `attach=1` (only server hrefs do) → every landing needs a manual Attach tap plus a dead "highlighted but not shown" state; cold open restores nothing (4 taps to last night's pane); **the window strip + Prev/Next mutate tmux but don't move the viewer** (the single most confusing trap); cross-host switch is 5 taps and blanks the terminal. + +**Precision/content:** no way to begin a drag selection by touch; copy = "last 50 lines" or all; history pager hidden behind the Actions sheet; copy-mode is an exit trap; pane "directional" nav is fake (linear order); prefix hard-coded to C-b; paste path was written around iOS limits — likely fine on Brave/Android but unverified; read-only state is a bare amber dot. + +## Prior art — what would make it BETTER (survey of web/mobile tmux implementations, 2024–2026) + +Surveyed: Termius, Blink SmartKeys, Termux extra-keys, JuiceSSH, mosh, tmate, ttyd/GoTTY/wetty, sshx, **Zellij's first-party web client (0.43, 2025)**, Wave, Warp, VS Code terminal, WezTerm/kitty, xterm.js ecosystem, plus the 2025 agent-supervision wave (VibeTunnel, DagsHub tmux-mobile, webtmux, muxplex, Happy/Omnara). Full sourced report in the study output; validation: Zellij chose the same two-channel binary/control WS split we have; tmux-mobile independently arrived at per-viewer grouped sessions — which we already ship. + +Mechanisms adopted into this plan (ranked value-for-effort): +1. **Server-side size pinning + letterboxed fixed grid** — pin the viewed window (`window-size manual` on our per-viewer grouped session), scale font to fit width; keyboard show/hide changes visible rows only, never SIGWINCHes. (→ M-D, upgrades decision 4) +2. **Termux-style user-definable key rows** — JSON-configured keys/chords/macros (e.g. a `y↵` approve key, `/compact`, prefix combos) with swipe-up popup layers. (→ M-B, upgrades decision 1) +3. **VirtualKeyboard API overlay mode** — `overlaysContent=true` + `env(keyboard-inset-height)` docks the rail in the keyboard inset; Chromium-only but that includes Brave/Android — your exact platform. visualViewport fallback kept. (→ M-B) +4. **Blink-style sticky/lockable modifiers with layer swap** — tap=one-shot, hold=chain, double-tap=lock Ctrl/Alt; active modifier swaps arrows→Home/End/PgUp/PgDn. (→ M-B) +5. **Termius long-press-drag arrow synthesis** — long-press enters cursor mode, drag emits accelerated arrow keys; double-tap word-select + copy-on-select in our own selection overlay (xterm.js touch is officially weak — replace, don't fight). (→ M-B/M-E) +6. **Scroll-freeze reading mode** — swipe-up freezes a snapshot while live output buffers behind a "N new lines" pill; no more viewport yanked mid-read. (→ M-E) +7. **Thumbnail pane switcher + agent-status badges** — bottom-sheet grid of live `capture-pane` snapshots (infra exists) badged waiting/running/idle; horizontal swipe on terminal = next/prev window. (→ M-C) +8. **Command marks + sticky command header** (VS Code/Warp, honest scope) — OSC 133 via tmux `allow-passthrough` for shell panes; for agent TUI panes (Claude Code emits no OSC 133 — open upstream requests) mark agent-turn boundaries heuristically; xterm decorations + prev/next jump on the rail. (→ M-E, second wave) +9. **Serialize-addon warm reattach** — buffer snapshot paints the pane in one frame on switch/resume instead of replay; makes pane switching feel native-instant. (→ M-C) +10. **Predictive local echo** (mosh, browser-proven by sshx) — deferred/optional: highest implementation risk, and agent supervision is read-heavy; revisit after MW2 if typing feel still lags. + +Cheap extras adopted: keep OS voice-typing unobstructed (Termius markets exactly this for Claude workflows); haptic tick on rail keys (works on Android). Explicitly rejected for PWA: volume-key hacks, mosh UDP roaming (our WS resume tokens are the browser-native equivalent). + +## Vision + +**SSH-client density with agent superpowers.** On the S25 Ultra: ≥40 terminal rows keyboard-closed and ≥20 keyboard-open at a readable font; a single slim key rail that NEVER disappears (only what Android's keyboard can't provide: Esc, sticky-Ctrl, arrows, prefix, History); every navigation lands live in one tap; the grid stays stable while the keyboard animates; and the agent layer (composer, approve, badges) rides on top without stealing rows. + +## Proposed decisions (owner approve/veto) + +1. **One adaptive key rail, always visible.** Merge TmuxKeyBar + VirtualKeyboard into a single ~44px rail docked above the keyboard inset (visible with keyboard open — this alone fixes root cause 1). Contents: Esc · sticky-Ctrl (tap Ctrl then a letter = chord; enables Ctrl-C/D/Z/R/L…) · ↑↓←→ (long-press = Home/End/PgUp/PgDn) · Tab · prefix · History · Copy. Everything else (Shift-Tab, splits, zoom, copy-mode entry) moves to long-press or the Actions sheet. Rarely-used keys are gone from permanent chrome per your steering. +2. **Full-bleed terminal mode.** When attached on mobile: collapse app header + shell header + card header into ONE slim status row (session name · window · status dot · overflow menu); window strip becomes compact (28px) with auto-scroll-to-active; remove the fixed 604px card (fill the viewport, no under-the-fold overflow). Target ≥40 rows closed / ≥20 open. +3. **Readable, adjustable type.** Default mobile font 13px (from 11px hard-coded), settings slider 11–18px, pinch-to-zoom on the terminal surface. Owner picks default. +4. **Stable grid policy.** Resize tmux only on *settled* size changes (keyboard animation end, rotation) — never on visualViewport scroll; and a "phone never resizes tmux" option (letterbox + pan) so your phone stops shrinking the desktop's window. Proposed default: letterbox ON when a desktop client is attached, off otherwise. +5. **Attach-on-navigate everywhere.** In-app roster/recents/quick-switch/window-strip selections carry the same `attach=1` contract server hrefs use; **window strip re-targets the viewer** (select_window + selectSession together); cold open restores the last pane live (0 taps); cross-host switch keeps the old pane warm. Single-user ⇒ auto-attach default ON (closes the old A6 open question). +6. **Single-user simplifications (locked-in scope cuts).** Tenancy/per-user scoping: dropped. iOS-specific fallbacks: dropped. Full screen-reader pass: deprioritized. Multi-viewer stays read-only-default (it's you on phone+desktop) with the existing 1-tap Take Control. +7. **Verify on YOUR device, not a fiction.** Playwright device profile moves to 412×915 Android metrics; an on-device checklist (10 min, guided) runs on your S25 Ultra via Brave at each wave gate — including the **Brave push check** ("Use Google services for push messaging" must be on for web push; likely why notifications may have seemed dead). adb/Chromium remote debugging for anything ambiguous. + +## Workstreams + +- **M-A Canvas & density**: decisions 2+3 — chrome collapse, full-bleed mode, font system, fixed-height removal, read-only/connection state made visible (pill not dot). +- **M-B Input & keys**: decision 1 upgraded by research #2/#3/#4/#5 — ONE user-definable rail (JSON config, swipe-up popup layers, macro keys incl. a `y↵` approve and `/compact`), docked in the keyboard inset via the VirtualKeyboard API (Brave/Android supported; visualViewport fallback), sticky/lockable Ctrl-Alt with layer swap, Termius long-press-drag arrow synthesis, per-host prefix setting (kills hard-coded C-b), copy-mode exit affordance, Android/Brave paste verification + fix, haptic tick. +- **M-C Navigation & attach**: decision 5 — attach contract in-app, window-strip viewer re-targeting, cold-open restore, quick-switch seeding from roster (not only recents), "+ window here" prefilled launch (6 taps → 2), warm-socket window extension (5 min → configurable 30). Plus research #7/#9: thumbnail pane switcher with agent-status badges, horizontal-swipe next/prev window, serialize-addon warm reattach for instant pane switching. +- **M-D Grid stability & resilience**: decision 4 upgraded by research #1 — server-side `window-size manual` pinning on our per-viewer grouped session + letterboxed fixed grid with font-scale-to-fit; settle-based resize for deliberate changes only; WebGL context re-create (currently degrades forever), resume/hard-reset toasts, `idle_timeout` one-tap resume. Includes the carried command-result feedback item (A5: surface dispatch outcomes so optimistic UI has truth). +- **M-E Precision & content**: research #5/#6/#8 — own touch-selection overlay (double-tap word, copy-on-select), scroll-freeze reading mode with "N new lines" pill, exact-range copy (line-numbered selection in the pager), History promoted to the rail, command marks + sticky command header (shell panes via OSC 133 passthrough; agent-turn heuristics for agent panes; second-wave scope), waiting-badges on collapsed cluster rows + filter→pane auto-expand, real directional pane nav (spatial, via topology geometry we already have). +- **M-F Device verification**: decision 7 — Android journey profiles, on-device checklist runs with you, Brave push setting doc + settings-page hint. + +## Execution shape (same ADL model) + +Two waves, four codex lanes, split across both machines; ~comparable to half the last program: +- **MW1**: `MOB-CANVAS` (M-A+M-B; homelinux) ∥ `MOB-FLOW` (M-C+M-D; heavisidelinux) — the structural fixes. +- **MW2**: `MOB-PRECISION` (M-E) ∥ `MOB-VERIFY` (M-F + journey-suite updates + carried small items A9/A10/A11) — then on-device pass with you, PR, deploy, v0.4.1. +Same firewalls/gates/reviews/receipts; per-wave deploy. + +## Backlog assessment (Inventory B → recommendation) + +**Fold into this mobile program (small, adjacent):** legacy `/tmux` hrefs from launch/open responses (A9); probe short-circuit + web-vitals gating (A10); window-strip arrow auto-activation (A11); docs-site screenshot (MW2); command-result feedback topic (A5 → M-D). +**Do now as 10-minute ops tasks (no program needed):** run the GitHub release workflow for v0.4.0 notes; `fs.inotify.max_user_instances=1024` sysctl on heavisidelinux (durable, replaces polling workaround); verify VAPID/web-push end-to-end on your phone WITH the Brave setting (part of M-F anyway). +**Next program candidates (your priority call, in my recommended order):** +1. **Hermes/open-agents deep integration** — the owner-requested 5-track item from 0.3.0, untouched: run lifecycle → Hermes, Hermes as work-item client, `ac` CLI/MCP contract for relay tasks, memory bridge, identity mapping. Biggest strategic value; its own program. +2. **Automation/memory finishing** — distillation is near-dead, budget enforcement thin (0.3.0 findings). Medium. +3. **Binary-only terminal migration** (server+schema+client with ordering guarantee) — clean-up, low urgency, pairs well with any future CP wave. +**Defer indefinitely (recommend):** tmux `-CC` transport (current hooks model is delivering), APK/native (PWA is fine on Android), R3F/Drei + TS-seam + uuid-advisory debt (harmless, batch into a future modernization), `/sessions`-vs-Command-Center merge (works as is), host capability write API (single-user, no need). +**Dropped by your single-user ruling:** tenancy/per-user scoping; iOS support work; full AT/screen-reader audit. + +## What I need from you + +1. Approve/veto the 7 proposed decisions (especially: rail contents, font default, letterbox default, auto-attach ON). +2. Pick the next-program priority (Hermes vs automation-finishing vs neither) so MW2 can hand off cleanly. +3. ~10 minutes on your phone at each of the two wave gates for the on-device checklist — the study's biggest systemic gap is that no wave was ever verified on real hardware, and yours is the only hardware that matters. From d34b3c2658440ba082c2906727cd82e1126c00b4 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 19:33:22 -0400 Subject: [PATCH 03/26] docs(program): wave 6 locked decisions + batch-1 briefs (mobile tmux UX) Co-Authored-By: Claude Fable 5 --- tasks/2026-07-20-fw6-canvas-brief.md | 35 +++++++++++++++++++++++++ tasks/2026-07-20-fw6-flow-brief.md | 35 +++++++++++++++++++++++++ tasks/2026-07-20-mobile-tmux-ux-plan.md | 5 +++- tasks/frontend-ux-log.md | 1 + tasks/frontend-ux-metrics.jsonl | 1 + 5 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 tasks/2026-07-20-fw6-canvas-brief.md create mode 100644 tasks/2026-07-20-fw6-flow-brief.md diff --git a/tasks/2026-07-20-fw6-canvas-brief.md b/tasks/2026-07-20-fw6-canvas-brief.md new file mode 100644 index 00000000..6291181b --- /dev/null +++ b/tasks/2026-07-20-fw6-canvas-brief.md @@ -0,0 +1,35 @@ +# FW6-CANVAS — Mobile terminal canvas, density, and the key rail (Wave 6, batch 1) + +Lane: FW6-CANVAS · Machine: homelinux · Worktree: `~/dev/wt/ac-fw6-canvas` · Branch: `refactor/fw6-canvas` (off `refactor/frontend-command-center`; local, do NOT push) +Context: `tasks/2026-07-20-mobile-tmux-ux-plan.md` (read the OWNER-LOCKED header + root causes). Target device: Samsung S25 Ultra, Brave/Android (~412×915), thumb-only. Single user. Playwright device metrics: use 412×915 Android for new tests. + +## Mission + +The mobile terminal is small, hard to read, and loses every control when the OS keyboard opens. Fix the canvas and the input rail. Success = **≥40 terminal rows keyboard-closed at 14px, ≥20 keyboard-open, and Esc/Ctrl/arrows usable WHILE typing**. + +## Work items + +1. **Full-bleed attached mode.** On mobile, when a terminal is attached: collapse app header, shell header, mode toggle, card header, and terminal toolbar into ONE slim status row (session title · window name · connection/read-only pill · overflow menu opening the Actions sheet). Window strip compresses to ~28px with auto-scroll-to-active-tab. Remove the fixed-height card (`TmuxPageClient.tsx` `h-[calc(100dvh-15rem)] min-h-[420px]`) — the terminal fills the viewport with NO page scroll. Bottom nav hides in attached mode (back via the status row / swipe to roster). Roster/Actions modes keep current chrome. +2. **Readable type.** Mobile default font 11px → **14px** (`useXtermTerminal.ts` ~:61); settings slider 11–18px (settings store + panel); pinch-to-zoom on the terminal surface adjusting font size live (two-finger — currently two-finger touches are dead in `useTerminalTouchScroll.ts` ~:70,:94). +3. **THE RAIL (replaces both key strips).** One component replacing `TmuxKeyBar` + `VirtualKeyboard` (`TerminalSurface.tsx` ~:129-146): + - **Default keys: Esc · sticky-Ctrl · ↑ ↓ ← →** (owner-locked ultra-minimal). Sticky-Ctrl: tap = one-shot chord (next OS-keyboard letter is Ctrl-modified), hold = chained combos, double-tap = lock; while active, the arrow cluster swaps to Home/End/PgUp/PgDn (Blink pattern). + - **Config engine (Termux pattern):** rail contents defined by a JSON config in the settings store — each key = keysym | chord | macro string, with an optional swipe-up popup layer per key. Ship a built-in "expanded" preset (adds Tab · prefix · History · `y↵` approve macro · `/compact` macro) selectable in settings. Long-press on arrows = the nav layer if Ctrl-swap isn't active. + - **Always visible:** dock the rail in the keyboard inset via the VirtualKeyboard API (`navigator.virtualKeyboard.overlaysContent = true` + `env(keyboard-inset-height)` — Chromium/Brave supports it); fall back to visualViewport positioning. **Delete the CSS that hides key controls when the keyboard opens** (`globals.css` ~:129 `[data-terminal-key-controls] { display:none }`) — that rule is the #1 root cause. + - Haptic tick (`navigator.vibrate(8)`) on rail keys; never obstruct the OS keyboard's voice-typing key; ~44px targets; no horizontal scroll for the default set. +4. **Cursor by touch (Termius pattern).** Long-press on the terminal enters cursor mode: drag synthesizes arrow-key sequences proportional to cell delta with 2–3 acceleration tiers; release exits. Pure key synthesis (safe in readline/vim/TUIs). Coexists with the existing long-press context menu via a movement threshold (drag = cursor mode, still = menu). +5. **Per-host tmux prefix.** Kill hard-coded `\x02` (`lib/tmuxKeys.ts` ~:8): per-host prefix setting (default C-b) consumed by rail/prefix macros. +6. **Paste on Brave/Android.** Verify `navigator.clipboard.readText()` works (it should on Chromium/Android with permission); make the paste flow prompt-and-work; remove/replace the misleading iOS "tap and hold to paste" hint (`VirtualKeyboard.tsx` ~:124) where inapplicable. +7. **Tests.** Unit: rail config engine (keysym/chord/macro/popup), sticky-Ctrl state machine, prefix setting. Playwright at **412×915 Android metrics**: full-bleed row budget assertion (≥40 rows at 14px), rail visible with keyboard-open simulation, pinch handler smoke. Existing suites green. + +## Ownership firewall + +You may edit: `apps/dashboard/src/components/(terminal|tmux|mobile|session)/**`, `src/hooks/**` (terminal/keyboard/touch), `src/lib/(tmuxKeys|viewport).ts`, `src/stores/settings.ts` (additive), `src/app/globals.css`, mobile-shell/page-client files for the full-bleed composition (`TmuxMobileShell.tsx`, `TmuxPageClient.tsx`, `SessionWorkbench.tsx`), related tests. You may NOT edit: `packages/**`, `services/**`, `agents/**`, `src/components/layout/**` except hiding bottom-nav in attached mode (minimal, flagged in handoff), terminal WS protocol shapes, `useTerminalConnection.ts` resize logic (FW6-FLOW owns grid policy — coordinate via AI Lead if you must touch it). + +## Gates + +`pnpm lint && pnpm typecheck && pnpm test:ci && pnpm test:smoke:dashboard && pnpm build` — run Playwright from a tmux TTY. Commit per work item, prefix `feat(mobile):`. ≤3 attempts per failure then hold. + +## Done + +Handoff `tasks/frontend-ux-handoffs/fw6-canvas.md`, committed, then print exactly: +`FW6-CANVAS FROZEN ` diff --git a/tasks/2026-07-20-fw6-flow-brief.md b/tasks/2026-07-20-fw6-flow-brief.md new file mode 100644 index 00000000..26366b40 --- /dev/null +++ b/tasks/2026-07-20-fw6-flow-brief.md @@ -0,0 +1,35 @@ +# FW6-FLOW — Attach-everywhere navigation + stable grid (Wave 6, batch 1) + +Lane: FW6-FLOW · Machine: heavisidelinux (cross-stack: Go + TS) · Worktree: `~/dev/wt/ac-fw6-flow` · Branch: `refactor/fw6-flow` (off `origin/refactor/frontend-command-center`; PUSH to origin regularly) +Context: `tasks/2026-07-20-mobile-tmux-ux-plan.md` (OWNER-LOCKED header). Go toolchain `~/.local/go/bin`. tmux SAFETY: tests use private `-L ac-test-*` sockets ONLY (never the default server). + +## Mission + +Every navigation lands live, and the grid stops churning. Success = **0 taps from cold open to last night's pane, window-strip taps change what you SEE, and typing/keyboard animation never SIGWINCHes tmux while a desktop client is attached**. + +## Work items + +1. **Attach-on-navigate everywhere (owner-locked).** In-app selections currently write `session_id` but never `attach=1` (only server hrefs do — `launch.ts:80`, `tmux.ts:37`). Make roster taps (`useTmuxRosterData.ts` ~:407-416), `RecentSessions` (~:10-19), and quick-switch land attached with `mode=terminal`. **Window strip re-targets the viewer**: a tab tap dispatches `select_window` AND switches the viewed pane to that window's active pane (`TmuxWindowStrip.tsx` ~:256-263 + `selectSession`) — same for Prev/Next. Cross-host switch keeps the previous pane warm and attaches the new one in one tap (no roster blanking). +2. **Cold-open restore.** Persist last attached `{host_id, session_id}` (ui store) and on boot with no URL params, restore it live (equivalent of the server's `mode=terminal&attach=1` href). Fallback to roster if the session is gone. +3. **Grid stability (owner-locked: letterbox-when-desktop-attached).** + - **agentd (Go):** on viewer attach, when the new `letterbox` attach option is set, pin the grouped viewer session's window size (`window-size manual` + fixed dimensions from the attach) so the phone client never shrinks the shared window; release/`window-size latest` on detach. Additive `terminal.attach` option in the protocol (extend the existing envelope additively + fixture; TS side in schema). + - **Control plane:** pass the option through; expose whether other (non-viewer) clients are attached to the underlying session if cheaply derivable from existing state — the dashboard decides policy: letterbox when a desktop client shares the window, fit-to-viewport when solo. + - **Dashboard:** letterbox render mode — fixed cols×rows grid, font scales to fit width, vertical pan for overflow; resize dispatches ONLY on settled changes (rotation, keyboard animation END — kill the `visualViewport.scroll`-driven fits at `useTerminalConnection.ts` ~:461-463; debounce until geometry is stable ≥250ms with a min-cell-delta gate). +4. **Warm switching + resume UX.** Serialize/snapshot warm reattach: cache the last buffer per recently-viewed pane client-side and paint it instantly on switch while the live attach resumes (existing capture replay stays the source of truth). Warm-socket window 5min → configurable (default 30min, settings). Toasts: "resumed" vs "session restarted — history truncated"; `idle_timeout`/`detached` states get a one-tap Resume button instead of a dead end. +5. **Command-result feedback (carried A5).** CP: relay `commands.result` outcomes on a UI topic (additive schema + relay, following the `tmux.topology` pattern). Dashboard: optimistic window/pane actions reconcile on real results; failures toast with the error. +6. **WebGL renderer resilience.** On context loss the addon disposes and never returns (`useXtermTerminal.ts` ~:104-111): attempt one re-create after loss (backoff), log a perf-channel metric on permanent fallback. +7. **"+ window here."** When attached, the launch sheet offers a prefilled "new window in this session" mode (host + tmux target prefilled from context) — 2 taps + prompt instead of 6 (`MobileLaunchSheet.tsx` ~:509-521 free-text target today). +8. **Tests.** Go: letterbox pin/release on the private-socket server; attach-option round-trip fixture. TS: attach-contract unit tests (every nav path emits attach), cold-open restore, settled-resize policy (no dispatch during simulated keyboard animation), command-result reconciliation. Playwright 412×915: cold-open→live journey, window-tab switches the view. + +## Ownership firewall + +You may edit: `agents/agentd/**` (viewer/grouped-session attach options only — do NOT touch the PTY transport itself), `packages/ac-schema/**` (additive), `services/control-plane/**` (additive relay/passthrough), `tests/fixtures/protocol/` (NEW fixture files for the additive attach option + command-result topic), `apps/dashboard/src/hooks/**`, `src/stores/**` (ui/settings additive), `src/lib/api.ts` (additive), `src/components/tmux/**` navigation wiring, `src/components/terminal/PersistentTerminalHost.tsx` + connection hooks, `MobileLaunchSheet.tsx` (item 7), related tests. You may NOT edit: the rail/key components, `globals.css`, font/full-bleed composition (FW6-CANVAS owns those), `deploy/**`. Shared-file conflicts with FW6-CANVAS (`TmuxWindowStrip`, mobile shell): CANVAS owns presentation, you own navigation/dispatch wiring — keep your edits to handlers/hooks and flag overlaps in your handoff for AI Lead reconciliation. + +## Gates + +Full TS chain (Playwright from a tmux TTY) + `go build ./... && go vet ./... && go test ./...` in agents/agentd. Commit per work item, prefix `feat(mobile-flow):` / `feat(agentd):`. ≤3 attempts per failure then hold. + +## Done + +Handoff `tasks/frontend-ux-handoffs/fw6-flow.md`, committed and pushed, then print exactly: +`FW6-FLOW FROZEN ` diff --git a/tasks/2026-07-20-mobile-tmux-ux-plan.md b/tasks/2026-07-20-mobile-tmux-ux-plan.md index 49ed15a4..a64212fa 100644 --- a/tasks/2026-07-20-mobile-tmux-ux-plan.md +++ b/tasks/2026-07-20-mobile-tmux-ux-plan.md @@ -1,4 +1,7 @@ -# Mobile tmux UX Program — Plan for Owner Assessment (2026-07-20) +# Mobile tmux UX — WAVE 6 of the Frontend Command Center UX program (2026-07-20) + +**OWNER-LOCKED 2026-07-20 (decision interview):** run as Wave 6 of the existing program (not a separate one). Rail = ultra-minimal DEFAULT (Esc · sticky-Ctrl · ↑↓←→) with the fuller preset + macro keys available via config. Font default 14px (+ slider 11–18 + pinch). Grid = letterbox-when-desktop-attached, settled-only resizes solo. Attach everywhere + cold-open restore. Full-bleed = one status row + compact 28px window strip. Command marks in the second batch. Next program after Wave 6: **Hermes deep integration**. Device verification: ONE guided S25-Ultra/Brave check before the final merge. +Execution: batch 1 lanes FW6-CANVAS (homelinux) + FW6-FLOW (heavisidelinux, cross-stack); batch 2 lanes FW6-PRECISION + FW6-VERIFY after batch-1 integration. Evidence: three-agent deep study at main `6e928a4` (v0.4.0) — element-by-element mobile terminal audit, tap-by-tap journey traces, known-issues + backlog inventory. Target device (owner facts, 2026-07-20): **Samsung Galaxy S25 Ultra, Brave browser (Chromium), thumb-only (no S Pen), single user**. All prior verification assumed iPhone 390×844 in headless Chromium; the actual target is ~412×915 with Android keyboard semantics and adb-debuggable. diff --git a/tasks/frontend-ux-log.md b/tasks/frontend-ux-log.md index 58c202d9..f70a4587 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -43,3 +43,4 @@ - ~06:30Z FW5-POLISH froze at `9ceed37` (attempt 1): gate re-run green in tmux TTY (20/20 smoke, 145 dashboard tests), firewall clean, web-vitals the only (allowed) dep. INTEGRATED (squash). Gate window killed post-run per owner reuse-panes directive. - ~07:50Z WAVE 5 COMPLETE + PROGRAM GATE GREEN at d7583f2 (198 CP + 145 dashboard tests, 20/20 smoke, 14/14 journeys, build, Go). Wave-5 review SHIP-WITH-NOTES: MEDIUM was AI Lead brief error (JSON fallback deletion) — fallback restored, full binary-only migration backlogged; CHANGELOG corrected; LOW/INFO items backlogged. Incident: gate command mis-keyed into a live owner codex pane (pane-index assumption) — caught before submission, composer cleared, pane-targeting rule added to memory. FW5-QA honesty note: flagged 4 NOT-METs rather than rubber-stamping; 2 resolved at integration, 2 remain for owner final review (on-device PWA pass; docs-site screenshot backlogged). - ~23:05Z Wave-5 PR #90 MERGED (6e928a4) + DEPLOYED (SOURCE_COMMIT verified; both agents reconnected after CP restart). Tagged v0.4.0. Wave-5 windows/worktrees cleaned. PROGRAM COMPLETE — Final Report: tasks/frontend-ux-final-report.md. +- ~00:30Z (07-21) PROGRAM REOPENED for WAVE 6 (owner directive): mobile tmux UX, run as Wave 6 of this program. 8 decisions locked via interview (ultra-minimal rail default + config engine, 14px font, letterbox-when-desktop-attached, attach-everywhere + cold-open restore, one-status-row full-bleed, command marks in batch 2, Hermes next, single end on-device check). Plan: tasks/2026-07-20-mobile-tmux-ux-plan.md. Batch 1 launching: FW6-CANVAS (homelinux) + FW6-FLOW (heavisidelinux, cross-stack). Batch 2 (FW6-PRECISION + FW6-VERIFY) briefs at batch-1 integration. diff --git a/tasks/frontend-ux-metrics.jsonl b/tasks/frontend-ux-metrics.jsonl index 4a99e1f9..0e1be5e0 100644 --- a/tasks/frontend-ux-metrics.jsonl +++ b/tasks/frontend-ux-metrics.jsonl @@ -26,3 +26,4 @@ {"ts":"2026-07-21T06:30:00Z","event":"lane_frozen","lane":"FW5-POLISH","attempt":1,"frozen_sha":"9ceed37","verdict":"accepted"} {"ts":"2026-07-21T07:50:00Z","event":"wave_complete","wave":5,"reviewer_verdict":"SHIP-WITH-NOTES","gate":"green","program":"final gate green"} {"ts":"2026-07-20T23:05:00Z","event":"program_complete","final_sha":"6e928a4","tag":"v0.4.0","waves":5,"lanes":10,"correction_rounds":5,"prs":[86,87,88,89,90],"wall_hours":10} +{"ts":"2026-07-21T00:30:00Z","event":"wave_launched","wave":6,"batch":1,"lanes":["FW6-CANVAS","FW6-FLOW"]} From ff6f90da6ede7072e3bac524bd8b3c0f6e4ac63c Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 20:29:48 -0400 Subject: [PATCH 04/26] =?UTF-8?q?feat(mobile):=20full-bleed=20terminal=20(?= =?UTF-8?q?=E2=89=A540=20rows=20@14px),=20single=20configurable=20key=20ra?= =?UTF-8?q?il=20in=20keyboard=20inset,=20sticky-Ctrl,=20touch=20cursor=20d?= =?UTF-8?q?rag,=20per-host=20prefix,=20Android=20paste=20(FW6-CANVAS=20a59?= =?UTF-8?q?3fc6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5 --- .../app/(dashboard)/tmux/TmuxPageClient.tsx | 17 +- apps/dashboard/src/app/globals.css | 26 ++- .../dashboard/src/components/TerminalView.tsx | 70 ++++-- .../components/mobile/TerminalContextMenu.tsx | 13 +- .../src/components/mobile/TerminalKeyRail.tsx | 206 ++++++++++++++++++ .../src/components/mobile/VirtualKeyboard.tsx | 13 +- .../src/components/mobile/stickyCtrl.test.ts | 36 +++ .../src/components/mobile/stickyCtrl.ts | 32 +++ .../mobile/terminalRailConfig.test.ts | 66 ++++++ .../components/mobile/terminalRailConfig.ts | 203 +++++++++++++++++ .../components/session/SessionWorkbench.tsx | 16 +- .../settings/SessionDefaultsPanel.tsx | 175 +++++++++++---- .../terminal/PersistentTerminalHost.tsx | 1 + .../components/terminal/TerminalSurface.tsx | 43 ++-- .../components/terminal/TerminalToolbar.tsx | 5 +- .../terminal/terminalHostStore.test.ts | 1 + .../components/terminal/terminalHostStore.ts | 11 +- .../src/components/terminal/types.ts | 1 + .../src/components/tmux/PromptComposer.tsx | 7 +- .../src/components/tmux/TmuxMobileShell.tsx | 109 ++++++++- .../components/tmux/TmuxTerminalWorkspace.tsx | 5 + .../src/components/tmux/TmuxWindowStrip.tsx | 17 +- .../tmux/accessibilityContracts.test.ts | 24 +- apps/dashboard/src/hooks/useClipboard.ts | 8 +- .../src/hooks/useTerminalClipboard.ts | 5 +- .../src/hooks/useTerminalTouchScroll.test.ts | 34 +++ .../src/hooks/useTerminalTouchScroll.ts | 192 +++++++++++++++- apps/dashboard/src/hooks/useXtermTerminal.ts | 33 ++- apps/dashboard/src/lib/tmuxKeys.test.ts | 21 +- apps/dashboard/src/lib/tmuxKeys.ts | 51 +++-- apps/dashboard/src/stores/settings.ts | 44 ++++ tasks/frontend-ux-handoffs/fw6-canvas.md | 72 ++++++ tests/smoke/dashboard.spec.ts | 104 ++++++++- 33 files changed, 1497 insertions(+), 164 deletions(-) create mode 100644 apps/dashboard/src/components/mobile/TerminalKeyRail.tsx create mode 100644 apps/dashboard/src/components/mobile/stickyCtrl.test.ts create mode 100644 apps/dashboard/src/components/mobile/stickyCtrl.ts create mode 100644 apps/dashboard/src/components/mobile/terminalRailConfig.test.ts create mode 100644 apps/dashboard/src/components/mobile/terminalRailConfig.ts create mode 100644 apps/dashboard/src/hooks/useTerminalTouchScroll.test.ts create mode 100644 tasks/frontend-ux-handoffs/fw6-canvas.md diff --git a/apps/dashboard/src/app/(dashboard)/tmux/TmuxPageClient.tsx b/apps/dashboard/src/app/(dashboard)/tmux/TmuxPageClient.tsx index 7e787944..672c0f8e 100644 --- a/apps/dashboard/src/app/(dashboard)/tmux/TmuxPageClient.tsx +++ b/apps/dashboard/src/app/(dashboard)/tmux/TmuxPageClient.tsx @@ -32,6 +32,7 @@ export default function TmuxPageClient() { const { setSessionIdle, isSessionIdlePending } = useSessionIdle(); const { terminateSession, isTerminating } = useTerminateSession(); const [workbenchViewMode, setWorkbenchViewMode] = useState<'console' | 'terminal'>('terminal'); + const [mobileTerminalAttached, setMobileTerminalAttached] = useState(false); const [sendToDialogOpen, setSendToDialogOpen] = useState(false); const [sendToTargetId, setSendToTargetId] = useState(undefined); const terminalModeRequested = searchParams.get('mode') === 'terminal'; @@ -179,7 +180,7 @@ export default function TmuxPageClient() { onViewModeChange={setWorkbenchViewMode} initialView="terminal" showDetails={!options?.mobileTerminalOnly} - terminalCardClassName={options?.mobileTerminalOnly ? 'h-[calc(100dvh-15rem)] min-h-[420px]' : undefined} + fullBleedMobileTerminal={Boolean(options?.mobileTerminalOnly && mobileTerminalAttached)} autoAttachTerminal={autoAttachRequested} terminalControllerRef={terminalControllerRef} /> @@ -206,8 +207,17 @@ export default function TmuxPageClient() { } return ( -
-
+
+
@@ -259,6 +269,7 @@ export default function TmuxPageClient() { onLaunchChange={handleRefresh} terminalControllerRef={terminalControllerRef} initialMode={terminalModeRequested && selectedSessionId ? 'terminal' : 'roster'} + onAttachedModeChange={setMobileTerminalAttached} terminal={renderWorkbench({ mobileTerminalOnly: true })} emptyTerminal={emptyWorkbench} /> diff --git a/apps/dashboard/src/app/globals.css b/apps/dashboard/src/app/globals.css index 2fd9f07f..0505b410 100644 --- a/apps/dashboard/src/app/globals.css +++ b/apps/dashboard/src/app/globals.css @@ -96,6 +96,11 @@ max-height: 100%; } +.terminal-key-rail { + bottom: max(env(keyboard-inset-height, 0px), var(--keyboard-inset-height, 0px)); + padding-bottom: max(0.25rem, env(safe-area-inset-bottom)); +} + @keyframes command-center-mode-view-in { from { opacity: 0; @@ -111,6 +116,23 @@ animation: command-center-mode-view-in 180ms ease-out; } +@media (max-width: 1023px) { + html[data-mobile-terminal-attached='true'] body > div > header:first-child { + display: none; + } + + html[data-mobile-terminal-attached='true'] main { + min-height: 0; + overflow: hidden; + padding-bottom: 0; + } + + html[data-mobile-terminal-attached='true'] nav[aria-label='Primary mobile navigation'], + html[data-mobile-terminal-attached='true'] [data-terminal-toolbar] { + display: none; + } +} + @media (prefers-reduced-motion: reduce) { .command-center-mode-view { animation: none; @@ -126,10 +148,6 @@ } } -html[data-virtual-keyboard-open='true'] [data-terminal-key-controls] { - display: none; -} - /* Mobile text selection support */ @media (max-width: 767px) { /* Enable text selection on xterm screen */ diff --git a/apps/dashboard/src/components/TerminalView.tsx b/apps/dashboard/src/components/TerminalView.tsx index b86b7288..7ba1d48c 100644 --- a/apps/dashboard/src/components/TerminalView.tsx +++ b/apps/dashboard/src/components/TerminalView.tsx @@ -5,16 +5,25 @@ import { cn } from '@/lib/utils'; 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 type { TerminalController, XSearchResult, XTerminal } from '@/components/terminal/types'; +import { + applyStickyCtrl, + reduceStickyCtrl, + type StickyCtrlEvent, + type StickyCtrlMode, +} from '@/components/mobile/stickyCtrl'; import { useIsMobile } from '@/hooks/useIsMobile'; import { useTerminalClipboard } from '@/hooks/useTerminalClipboard'; import { useTerminalConnection } from '@/hooks/useTerminalConnection'; import { useTerminalScrollAnchor } from '@/hooks/useTerminalScrollAnchor'; import { useTerminalTouchScroll } from '@/hooks/useTerminalTouchScroll'; import { useXtermTerminal } from '@/hooks/useXtermTerminal'; +import { useSettingsStore } from '@/stores/settings'; interface TerminalViewProps { sessionId: string; + hostId?: string; paneId?: string; className?: string; autoAttach?: boolean; @@ -29,6 +38,7 @@ export type { TerminalController } from '@/components/terminal/types'; export function TerminalView({ sessionId, + hostId, paneId, className, autoAttach = false, @@ -42,8 +52,9 @@ export function TerminalView({ const sendInputRef = useRef<(data: string) => void>(() => undefined); const controllerInstanceRef = useRef(null); const controllerReadOnlyRef = useRef(false); - const [hasCommittedSelection, setHasCommittedSelection] = useState(false); const [searchOpen, setSearchOpen] = useState(false); + const [historyOpen, setHistoryOpen] = useState(false); + const [stickyCtrlMode, setStickyCtrlMode] = useState('inactive'); const [searchQuery, setSearchQuery] = useState(''); const [searchResults, setSearchResults] = useState({ resultIndex: -1, @@ -53,12 +64,17 @@ export function TerminalView({ const selectionAnchorRef = useRef<{ x: number; y: number } | null>(null); const selectionPopupRef = useRef(null); const hasCommittedSelectionRef = useRef(false); + const stickyCtrlModeRef = useRef('inactive'); const isMobile = useIsMobile(); + const terminalFontSize = useSettingsStore((state) => state.terminalFontSize); + const setTerminalFontSize = useSettingsStore((state) => state.setTerminalFontSize); + const tmuxPrefix = useSettingsStore((state) => ( + hostId ? state.tmuxPrefixByHost[hostId] : undefined + )); const handleTerminalSelectionChange = useCallback((selection: string) => { selectionTextRef.current = selection; if (selection || !hasCommittedSelectionRef.current) return; hasCommittedSelectionRef.current = false; - setHasCommittedSelection(false); selectionPopupRef.current?.hide(); }, []); @@ -131,7 +147,6 @@ export function TerminalView({ const hasSelection = selection.length > 0; if (hasCommittedSelectionRef.current !== hasSelection) { hasCommittedSelectionRef.current = hasSelection; - setHasCommittedSelection(hasSelection); } if (hasSelection) { selectionPopupRef.current?.showSelection(selection, selectionAnchorRef.current ?? undefined); @@ -163,13 +178,35 @@ export function TerminalView({ onOutputWritten: scrollAnchor.handleOutputWritten, }); controllerReadOnlyRef.current = readOnly; - useEffect(() => { - sendInputRef.current = sendInput; + 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]); + useEffect(() => { + sendInputRef.current = handlePhysicalInput; + }, [handlePhysicalInput]); + useEffect(() => { + if (status === 'connected') return; + stickyCtrlModeRef.current = 'inactive'; + setStickyCtrlMode('inactive'); + }, [status]); const touchScrollRef = useTerminalTouchScroll({ enabled: isMobile, termRef, terminalRef, + fontSize: terminalFontSize, + onFontSizeChange: setTerminalFontSize, + cursorEnabled: status === 'connected' && !readOnly, + onCursorInput: sendInput, }); // Virtual keyboard handlers @@ -177,10 +214,6 @@ export function TerminalView({ sendInput(data); }, [sendInput]); - const handleVirtualInterrupt = useCallback(() => { - sendInput('\x03'); - }, [sendInput]); - const terminalClipboard = useTerminalClipboard({ terminalRef, sendInput, @@ -195,6 +228,7 @@ export function TerminalView({ useEffect(() => { if (!controllerRef && !onControllerChange) return; const controller: TerminalController = { + status, readOnly: controllerReadOnlyRef.current, attach: () => void connect(), detach: disconnect, @@ -232,14 +266,16 @@ export function TerminalView({ terminalRef, suspend, takeControl, + status, ]); useEffect(() => { const controller = controllerInstanceRef.current; - if (!controller || controller.readOnly === readOnly) return; + if (!controller || (controller.readOnly === readOnly && controller.status === status)) return; controller.readOnly = readOnly; + controller.status = status; onControllerChange?.(controller); - }, [onControllerChange, readOnly]); + }, [onControllerChange, readOnly, status]); useEffect(() => { const touchState = touchScrollRef.current; @@ -282,14 +318,15 @@ export function TerminalView({ isMobile={isMobile} status={status} readOnly={readOnly} - paneId={paneId} - hasSelection={hasCommittedSelection} selectionTextRef={selectionTextRef} selectionPopupRef={selectionPopupRef} onSelectionStart={handleSelectionStart} onSelectionCommit={handleSelectionCommit} onVirtualInput={handleVirtualInput} - onVirtualInterrupt={handleVirtualInterrupt} + stickyCtrlMode={stickyCtrlMode} + onStickyCtrlEvent={dispatchStickyCtrl} + onOpenHistory={() => setHistoryOpen(true)} + tmuxPrefix={tmuxPrefix} onCopySelection={terminalClipboard.copySelection} onCopyLastLines={terminalClipboard.copyLastLines} onCopyAll={terminalClipboard.copyAll} @@ -300,6 +337,11 @@ export function TerminalView({ onJumpToLive={() => scrollAnchor.jumpToLive(terminalRef.current)} search={searchControls} /> + setHistoryOpen(false)} + />
); } diff --git a/apps/dashboard/src/components/mobile/TerminalContextMenu.tsx b/apps/dashboard/src/components/mobile/TerminalContextMenu.tsx index 04a7ed22..5e047a69 100644 --- a/apps/dashboard/src/components/mobile/TerminalContextMenu.tsx +++ b/apps/dashboard/src/components/mobile/TerminalContextMenu.tsx @@ -103,6 +103,7 @@ export function TerminalContextMenu({ // Handle long press start const handleTouchStart = useCallback((e: TouchEvent) => { + if (e.touches.length !== 1) return; const touch = e.touches[0]; touchStartPosRef.current = { x: touch.clientX, y: touch.clientY }; @@ -149,12 +150,21 @@ export function TerminalContextMenu({ useEffect(() => { const container = containerRef.current; if (!container) return; + const handleCursorModeStart = () => { + if (longPressTimerRef.current) { + clearTimeout(longPressTimerRef.current); + longPressTimerRef.current = null; + } + touchStartPosRef.current = null; + hideMenu(); + }; container.addEventListener('touchstart', handleTouchStart, { passive: true }); container.addEventListener('touchmove', handleTouchMove, { passive: true }); container.addEventListener('touchend', handleTouchEnd); container.addEventListener('touchcancel', handleTouchEnd); container.addEventListener('contextmenu', handleContextMenu); + container.addEventListener('terminal-cursor-mode-start', handleCursorModeStart); return () => { container.removeEventListener('touchstart', handleTouchStart); @@ -162,12 +172,13 @@ export function TerminalContextMenu({ container.removeEventListener('touchend', handleTouchEnd); container.removeEventListener('touchcancel', handleTouchEnd); container.removeEventListener('contextmenu', handleContextMenu); + container.removeEventListener('terminal-cursor-mode-start', handleCursorModeStart); if (longPressTimerRef.current) { clearTimeout(longPressTimerRef.current); } }; - }, [containerRef, handleTouchStart, handleTouchMove, handleTouchEnd, handleContextMenu]); + }, [containerRef, handleTouchStart, handleTouchMove, handleTouchEnd, handleContextMenu, hideMenu]); // Hide when clicking outside useEffect(() => { diff --git a/apps/dashboard/src/components/mobile/TerminalKeyRail.tsx b/apps/dashboard/src/components/mobile/TerminalKeyRail.tsx new file mode 100644 index 00000000..0af12646 --- /dev/null +++ b/apps/dashboard/src/components/mobile/TerminalKeyRail.tsx @@ -0,0 +1,206 @@ +'use client'; + +import { useEffect, useMemo, useRef, useState, type PointerEvent } from 'react'; +import { cn } from '@/lib/utils'; +import { useSettingsStore } from '@/stores/settings'; +import { + MINIMAL_TERMINAL_RAIL_CONFIG, + isArrowRailKey, + resolveTerminalRailBinding, + type TerminalRailBinding, + type TerminalRailKey, +} from './terminalRailConfig'; +import type { StickyCtrlEvent, StickyCtrlMode } from './stickyCtrl'; +import { tmuxPrefixToSequence } from '@/lib/tmuxKeys'; + +interface TerminalKeyRailProps { + onInput: (data: string) => void; + onHistory: () => void; + ctrlMode: StickyCtrlMode; + onCtrlEvent: (event: StickyCtrlEvent) => void; + prefix?: string; +} + +type RailGesture = { + keyId: string; + startY: number; + swiped: boolean; + longPressed: boolean; +}; + +function hapticTick() { + navigator.vibrate?.(8); +} + +export function TerminalKeyRail({ + onInput, + onHistory, + ctrlMode, + onCtrlEvent, + prefix, +}: TerminalKeyRailProps) { + const configuredRail = useSettingsStore((state) => state.terminalRailConfig); + const config = configuredRail?.keys?.length ? configuredRail : MINIMAL_TERMINAL_RAIL_CONFIG; + const [navLayer, setNavLayer] = useState(false); + const gestureRef = useRef(null); + const longPressTimerRef = useRef(null); + const suppressClickRef = useRef(false); + const lastCtrlTapRef = useRef(0); + const ctrlActive = ctrlMode !== 'inactive'; + + useEffect(() => { + const virtualKeyboard = (navigator as Navigator & { + virtualKeyboard?: { overlaysContent: boolean }; + }).virtualKeyboard; + if (virtualKeyboard) virtualKeyboard.overlaysContent = true; + }, []); + + useEffect(() => () => { + if (longPressTimerRef.current !== null) window.clearTimeout(longPressTimerRef.current); + }, []); + + const visibleKeys = useMemo(() => config.keys.map((key) => { + if ((ctrlActive || navLayer) && isArrowRailKey(key) && key.popup) { + return { + ...key, + label: key.popup.label, + binding: key.popup as TerminalRailBinding, + }; + } + return key; + }), [config.keys, ctrlActive, navLayer]); + + const clearLongPress = () => { + if (longPressTimerRef.current !== null) { + window.clearTimeout(longPressTimerRef.current); + longPressTimerRef.current = null; + } + }; + + const executeBinding = (binding: TerminalRailBinding, key: TerminalRailKey) => { + const action = resolveTerminalRailBinding(binding, tmuxPrefixToSequence(prefix)); + hapticTick(); + if (action.type === 'input') onInput(action.data); + else if (action.type === 'history') onHistory(); + else return; + if (ctrlMode === 'one-shot') onCtrlEvent('consume'); + if (navLayer && isArrowRailKey(key)) setNavLayer(false); + }; + + const handleCtrlClick = () => { + const now = performance.now(); + if (now - lastCtrlTapRef.current <= 300) { + lastCtrlTapRef.current = 0; + onCtrlEvent('double-tap'); + } else { + lastCtrlTapRef.current = now; + onCtrlEvent('tap'); + } + hapticTick(); + }; + + const handlePointerDown = (event: PointerEvent, key: TerminalRailKey) => { + event.currentTarget.setPointerCapture(event.pointerId); + suppressClickRef.current = false; + gestureRef.current = { + keyId: key.id, + startY: event.clientY, + swiped: false, + longPressed: false, + }; + clearLongPress(); + + const isCtrl = key.binding.type === 'keysym' && key.binding.value === 'ctrl'; + if (isCtrl) { + longPressTimerRef.current = window.setTimeout(() => { + longPressTimerRef.current = null; + if (!gestureRef.current || gestureRef.current.keyId !== key.id) return; + gestureRef.current.longPressed = true; + suppressClickRef.current = true; + onCtrlEvent('hold-start'); + hapticTick(); + }, 450); + } else if (isArrowRailKey(key) && !ctrlActive) { + longPressTimerRef.current = window.setTimeout(() => { + longPressTimerRef.current = null; + if (!gestureRef.current || gestureRef.current.keyId !== key.id) return; + gestureRef.current.longPressed = true; + suppressClickRef.current = true; + setNavLayer(true); + hapticTick(); + }, 450); + } + }; + + const handlePointerMove = (event: PointerEvent, key: TerminalRailKey) => { + const gesture = gestureRef.current; + if (!gesture || gesture.keyId !== key.id || !key.popup || gesture.longPressed) return; + if (gesture.startY - event.clientY < 24) return; + gesture.swiped = true; + suppressClickRef.current = true; + clearLongPress(); + }; + + const finishPointer = (key: TerminalRailKey) => { + clearLongPress(); + const gesture = gestureRef.current; + gestureRef.current = null; + if (!gesture || gesture.keyId !== key.id) return; + if (gesture.longPressed && key.binding.type === 'keysym' && key.binding.value === 'ctrl') { + onCtrlEvent('hold-end'); + return; + } + if (gesture.swiped && key.popup) { + executeBinding(key.popup, key); + } + }; + + return ( +
+
+ {visibleKeys.map((key, index) => { + const sourceKey = config.keys[index] ?? key; + const isCtrl = sourceKey.binding.type === 'keysym' && sourceKey.binding.value === 'ctrl'; + return ( + + ); + })} +
+
+ ); +} diff --git a/apps/dashboard/src/components/mobile/VirtualKeyboard.tsx b/apps/dashboard/src/components/mobile/VirtualKeyboard.tsx index fba74aac..5d0252d5 100644 --- a/apps/dashboard/src/components/mobile/VirtualKeyboard.tsx +++ b/apps/dashboard/src/components/mobile/VirtualKeyboard.tsx @@ -120,13 +120,16 @@ export function VirtualKeyboard({ return; } } catch { - // Clipboard read failed (iOS Safari often blocks this) - setPasteError('Tap and hold to paste'); - setTimeout(() => setPasteError(null), 2000); + const text = window.prompt('Clipboard access is blocked. Paste text here:'); + if (text) onPaste?.(text); + else setPasteError('Clipboard access was blocked'); + setTimeout(() => setPasteError(null), 2500); } } else { - setPasteError('Tap and hold to paste'); - setTimeout(() => setPasteError(null), 2000); + const text = window.prompt('Clipboard API unavailable. Paste text here:'); + if (text) onPaste?.(text); + else setPasteError('No text pasted'); + setTimeout(() => setPasteError(null), 2500); } }, [onPaste]); diff --git a/apps/dashboard/src/components/mobile/stickyCtrl.test.ts b/apps/dashboard/src/components/mobile/stickyCtrl.test.ts new file mode 100644 index 00000000..77da74f7 --- /dev/null +++ b/apps/dashboard/src/components/mobile/stickyCtrl.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest'; +import { applyStickyCtrl, reduceStickyCtrl } from './stickyCtrl'; + +describe('sticky Ctrl state machine', () => { + it('uses a tap as a one-shot modifier and consumes the next keyboard letter', () => { + const armed = reduceStickyCtrl('inactive', 'tap'); + expect(armed).toBe('one-shot'); + expect(applyStickyCtrl(armed, 'c')).toEqual({ + data: '\x03', + mode: 'inactive', + consumed: true, + }); + }); + + it('keeps chained chords active while held', () => { + const held = reduceStickyCtrl('inactive', 'hold-start'); + expect(applyStickyCtrl(held, 'c').mode).toBe('held'); + expect(applyStickyCtrl(held, 'd').data).toBe('\x04'); + expect(reduceStickyCtrl(held, 'hold-end')).toBe('inactive'); + }); + + it('locks on double-tap and unlocks on the next tap', () => { + const locked = reduceStickyCtrl('one-shot', 'double-tap'); + expect(locked).toBe('locked'); + expect(applyStickyCtrl(locked, 'z')).toMatchObject({ data: '\x1a', mode: 'locked' }); + expect(reduceStickyCtrl(locked, 'tap')).toBe('inactive'); + }); + + it('waits for a letter instead of consuming navigation input', () => { + expect(applyStickyCtrl('one-shot', '\x1b[A')).toEqual({ + data: '\x1b[A', + mode: 'one-shot', + consumed: false, + }); + }); +}); diff --git a/apps/dashboard/src/components/mobile/stickyCtrl.ts b/apps/dashboard/src/components/mobile/stickyCtrl.ts new file mode 100644 index 00000000..9743c686 --- /dev/null +++ b/apps/dashboard/src/components/mobile/stickyCtrl.ts @@ -0,0 +1,32 @@ +export type StickyCtrlMode = 'inactive' | 'one-shot' | 'held' | 'locked'; +export type StickyCtrlEvent = 'tap' | 'hold-start' | 'hold-end' | 'double-tap' | 'consume'; + +export function reduceStickyCtrl(mode: StickyCtrlMode, event: StickyCtrlEvent): StickyCtrlMode { + switch (event) { + case 'tap': + return mode === 'locked' ? 'inactive' : 'one-shot'; + case 'hold-start': + return 'held'; + case 'hold-end': + return mode === 'held' ? 'inactive' : mode; + case 'double-tap': + return 'locked'; + case 'consume': + return mode === 'one-shot' ? 'inactive' : mode; + } +} + +export function applyStickyCtrl( + mode: StickyCtrlMode, + data: string +): { data: string; mode: StickyCtrlMode; consumed: boolean } { + if (mode === 'inactive' || data.length !== 1 || !/[A-Za-z@\[\\\]^_?]/.test(data)) { + return { data, mode, consumed: false }; + } + const normalized = data === '?' ? String.fromCharCode(127) : String.fromCharCode(data.toUpperCase().charCodeAt(0) & 31); + return { + data: normalized, + mode: reduceStickyCtrl(mode, 'consume'), + consumed: true, + }; +} diff --git a/apps/dashboard/src/components/mobile/terminalRailConfig.test.ts b/apps/dashboard/src/components/mobile/terminalRailConfig.test.ts new file mode 100644 index 00000000..ade4e472 --- /dev/null +++ b/apps/dashboard/src/components/mobile/terminalRailConfig.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest'; +import { + parseTerminalRailConfig, + resolveTerminalRailBinding, +} from './terminalRailConfig'; + +describe('terminal rail config engine', () => { + it('parses keysyms, chords, macros, and popup bindings', () => { + const config = parseTerminalRailConfig({ + version: 1, + keys: [ + { + id: 'up', + label: '↑', + binding: { type: 'keysym', value: 'arrow_up' }, + popup: { label: 'PgUp', type: 'keysym', value: 'page_up' }, + }, + { id: 'interrupt', label: 'C-c', binding: { type: 'chord', value: ['ctrl', 'c'] } }, + { id: 'approve', label: 'y↵', binding: { type: 'macro', value: 'y\r' } }, + ], + }); + + expect(config.keys).toHaveLength(3); + expect(resolveTerminalRailBinding(config.keys[0]!.binding)).toEqual({ + type: 'input', + data: '\x1b[A', + }); + expect(resolveTerminalRailBinding(config.keys[0]!.popup!)).toEqual({ + type: 'input', + data: '\x1b[5~', + }); + expect(resolveTerminalRailBinding(config.keys[1]!.binding)).toEqual({ + type: 'input', + data: '\x03', + }); + expect(resolveTerminalRailBinding(config.keys[2]!.binding)).toEqual({ + type: 'input', + data: 'y\r', + }); + }); + + it('resolves prefix keysyms and chords with the supplied host sequence', () => { + expect(resolveTerminalRailBinding({ type: 'keysym', value: 'prefix' }, '\x01')).toEqual({ + type: 'input', + data: '\x01', + }); + expect(resolveTerminalRailBinding({ type: 'chord', value: ['prefix', '['] }, '\x01')).toEqual({ + type: 'input', + data: '\x01[', + }); + }); + + it('rejects duplicate ids and invalid bindings', () => { + expect(() => parseTerminalRailConfig({ + version: 1, + keys: [ + { id: 'same', label: 'A', binding: { type: 'macro', value: 'a' } }, + { id: 'same', label: 'B', binding: { type: 'macro', value: 'b' } }, + ], + })).toThrow(/unique id/); + expect(() => parseTerminalRailConfig({ + version: 1, + keys: [{ id: 'bad', label: 'Bad', binding: { type: 'keysym', value: 'nope' } }], + })).toThrow(/valid binding/); + }); +}); diff --git a/apps/dashboard/src/components/mobile/terminalRailConfig.ts b/apps/dashboard/src/components/mobile/terminalRailConfig.ts new file mode 100644 index 00000000..8d6a63b5 --- /dev/null +++ b/apps/dashboard/src/components/mobile/terminalRailConfig.ts @@ -0,0 +1,203 @@ +import { DEFAULT_TMUX_PREFIX, tmuxPrefixToSequence } from '@/lib/tmuxKeys'; + +export const TERMINAL_RAIL_KEYSYMS = [ + 'ctrl', + 'esc', + 'tab', + 'enter', + 'arrow_up', + 'arrow_down', + 'arrow_left', + 'arrow_right', + 'home', + 'end', + 'page_up', + 'page_down', + 'prefix', + 'history', +] as const; + +export type TerminalRailKeysym = (typeof TERMINAL_RAIL_KEYSYMS)[number]; +export type TerminalRailBinding = + | { type: 'keysym'; value: TerminalRailKeysym } + | { type: 'chord'; value: string[] } + | { type: 'macro'; value: string }; + +export type TerminalRailPopup = TerminalRailBinding & { label: string }; + +export interface TerminalRailKey { + id: string; + label: string; + binding: TerminalRailBinding; + popup?: TerminalRailPopup; +} + +export interface TerminalRailConfig { + version: 1; + keys: TerminalRailKey[]; +} + +export type TerminalRailPreset = 'minimal' | 'expanded' | 'custom'; +export type TerminalRailAction = + | { type: 'input'; data: string } + | { type: 'modifier'; modifier: 'ctrl' } + | { type: 'history' }; + +const KEY_DATA: Partial> = { + esc: '\x1b', + tab: '\t', + enter: '\r', + arrow_up: '\x1b[A', + arrow_down: '\x1b[B', + arrow_left: '\x1b[D', + arrow_right: '\x1b[C', + home: '\x1b[H', + end: '\x1b[F', + page_up: '\x1b[5~', + page_down: '\x1b[6~', +}; + +export const MINIMAL_TERMINAL_RAIL_CONFIG: TerminalRailConfig = { + version: 1, + keys: [ + { id: 'esc', label: 'Esc', binding: { type: 'keysym', value: 'esc' } }, + { id: 'ctrl', label: 'Ctrl', binding: { type: 'keysym', value: 'ctrl' } }, + { + id: 'up', + label: '↑', + binding: { type: 'keysym', value: 'arrow_up' }, + popup: { label: 'PgUp', type: 'keysym', value: 'page_up' }, + }, + { + id: 'down', + label: '↓', + binding: { type: 'keysym', value: 'arrow_down' }, + popup: { label: 'PgDn', type: 'keysym', value: 'page_down' }, + }, + { + id: 'left', + label: '←', + binding: { type: 'keysym', value: 'arrow_left' }, + popup: { label: 'Home', type: 'keysym', value: 'home' }, + }, + { + id: 'right', + label: '→', + binding: { type: 'keysym', value: 'arrow_right' }, + popup: { label: 'End', type: 'keysym', value: 'end' }, + }, + ], +}; + +export const EXPANDED_TERMINAL_RAIL_CONFIG: TerminalRailConfig = { + version: 1, + keys: [ + ...MINIMAL_TERMINAL_RAIL_CONFIG.keys, + { id: 'tab', label: 'Tab', binding: { type: 'keysym', value: 'tab' } }, + { id: 'prefix', label: 'Prefix', binding: { type: 'keysym', value: 'prefix' } }, + { id: 'history', label: 'History', binding: { type: 'keysym', value: 'history' } }, + { id: 'approve', label: 'y↵', binding: { type: 'macro', value: 'y\r' } }, + { id: 'compact', label: '/compact', binding: { type: 'macro', value: '/compact' } }, + ], +}; + +export function cloneTerminalRailConfig(config: TerminalRailConfig): TerminalRailConfig { + return JSON.parse(JSON.stringify(config)) as TerminalRailConfig; +} + +export function terminalRailPresetConfig(preset: Exclude): TerminalRailConfig { + return cloneTerminalRailConfig( + preset === 'expanded' ? EXPANDED_TERMINAL_RAIL_CONFIG : MINIMAL_TERMINAL_RAIL_CONFIG + ); +} + +function isBinding(value: unknown): value is TerminalRailBinding { + if (!value || typeof value !== 'object') return false; + const binding = value as Record; + if (binding.type === 'keysym') { + return TERMINAL_RAIL_KEYSYMS.includes(binding.value as TerminalRailKeysym); + } + if (binding.type === 'chord') { + return Array.isArray(binding.value) + && binding.value.length >= 2 + && binding.value.every((part) => typeof part === 'string' && part.length > 0); + } + return binding.type === 'macro' && typeof binding.value === 'string'; +} + +export function parseTerminalRailConfig(value: unknown): TerminalRailConfig { + if (!value || typeof value !== 'object') throw new Error('Rail config must be a JSON object.'); + const config = value as Record; + if (config.version !== 1 || !Array.isArray(config.keys) || config.keys.length === 0) { + throw new Error('Rail config must use version 1 and include at least one key.'); + } + const ids = new Set(); + const keys = config.keys.map((value, index): TerminalRailKey => { + if (!value || typeof value !== 'object') throw new Error(`Key ${index + 1} must be an object.`); + const key = value as Record; + if (typeof key.id !== 'string' || !key.id.trim() || ids.has(key.id)) { + throw new Error(`Key ${index + 1} needs a unique id.`); + } + if (typeof key.label !== 'string' || !key.label.trim() || !isBinding(key.binding)) { + throw new Error(`Key ${key.id} needs a label and valid binding.`); + } + ids.add(key.id); + let popup: TerminalRailPopup | undefined; + if (key.popup !== undefined) { + if (!key.popup || typeof key.popup !== 'object') throw new Error(`Key ${key.id} popup is invalid.`); + const candidate = key.popup as Record; + if (typeof candidate.label !== 'string' || !candidate.label.trim() || !isBinding(candidate)) { + throw new Error(`Key ${key.id} popup needs a label and valid binding.`); + } + popup = candidate as unknown as TerminalRailPopup; + } + return { + id: key.id, + label: key.label, + binding: key.binding, + ...(popup ? { popup } : {}), + }; + }); + return { version: 1, keys }; +} + +function ctrlCharacter(value: string): string | null { + if (value.length !== 1) return null; + const upper = value.toUpperCase(); + const code = upper.charCodeAt(0); + if (code < 64 || code > 95) return null; + return String.fromCharCode(code & 31); +} + +export function resolveTerminalRailBinding( + binding: TerminalRailBinding, + prefix = tmuxPrefixToSequence(DEFAULT_TMUX_PREFIX) +): TerminalRailAction { + if (binding.type === 'macro') return { type: 'input', data: binding.value }; + if (binding.type === 'keysym') { + if (binding.value === 'ctrl') return { type: 'modifier', modifier: 'ctrl' }; + if (binding.value === 'history') return { type: 'history' }; + if (binding.value === 'prefix') return { type: 'input', data: prefix }; + return { type: 'input', data: KEY_DATA[binding.value] ?? '' }; + } + + const [modifier, ...parts] = binding.value; + const value = parts.join(''); + switch (modifier.toLowerCase()) { + case 'ctrl': { + const data = ctrlCharacter(value); + if (!data) throw new Error(`Unsupported Ctrl chord: ${binding.value.join('+')}`); + return { type: 'input', data }; + } + case 'alt': + return { type: 'input', data: `\x1b${value}` }; + case 'prefix': + return { type: 'input', data: `${prefix}${value}` }; + default: + throw new Error(`Unsupported chord modifier: ${modifier}`); + } +} + +export function isArrowRailKey(key: TerminalRailKey): boolean { + return key.binding.type === 'keysym' && key.binding.value.startsWith('arrow_'); +} diff --git a/apps/dashboard/src/components/session/SessionWorkbench.tsx b/apps/dashboard/src/components/session/SessionWorkbench.tsx index f3ba7397..d1e6ddde 100644 --- a/apps/dashboard/src/components/session/SessionWorkbench.tsx +++ b/apps/dashboard/src/components/session/SessionWorkbench.tsx @@ -31,6 +31,7 @@ interface SessionWorkbenchProps { className?: string; showDetails?: boolean; terminalCardClassName?: string; + fullBleedMobileTerminal?: boolean; autoAttachTerminal?: boolean; terminalControllerRef?: MutableRefObject; } @@ -47,6 +48,7 @@ export function SessionWorkbench({ className, showDetails = true, terminalCardClassName, + fullBleedMobileTerminal = false, autoAttachTerminal = false, terminalControllerRef, }: SessionWorkbenchProps) { @@ -131,17 +133,24 @@ export function SessionWorkbench({ : ''); return ( -
+
- +
{activeViewMode === 'console' ? 'Console' : 'Terminal'} @@ -190,6 +199,7 @@ export function SessionWorkbench({ diff --git a/apps/dashboard/src/components/settings/SessionDefaultsPanel.tsx b/apps/dashboard/src/components/settings/SessionDefaultsPanel.tsx index d8522f92..d276bc33 100644 --- a/apps/dashboard/src/components/settings/SessionDefaultsPanel.tsx +++ b/apps/dashboard/src/components/settings/SessionDefaultsPanel.tsx @@ -1,35 +1,38 @@ 'use client'; +import { useEffect, useState } from 'react'; import { Link as LinkIcon } from 'lucide-react'; +import { useQuery } from '@tanstack/react-query'; import { - DEFAULT_VIRTUAL_KEY_ORDER, + DEFAULT_TERMINAL_FONT_SIZE, + TERMINAL_FONT_SIZE_MAX, + TERMINAL_FONT_SIZE_MIN, type LinkType, type SessionNamingPattern, - type VirtualKeyboardKey, useSettingsStore, } from '@/stores/settings'; +import { + parseTerminalRailConfig, + type TerminalRailPreset, +} from '@/components/mobile/terminalRailConfig'; import { Button } from '@/components/ui/button'; import { Label } from '@/components/ui/label'; import { Switch } from '@/components/ui/switch'; - -const VIRTUAL_KEYS: Array<{ id: VirtualKeyboardKey; label: string }> = [ - { id: 'ctrl_c', label: 'Ctrl + C' }, - { id: 'esc', label: 'Escape' }, - { id: 'tab', label: 'Tab' }, - { id: 'shift_tab', label: 'Shift + Tab' }, - { id: 'arrow_up', label: 'Arrow Up' }, - { id: 'arrow_down', label: 'Arrow Down' }, - { id: 'arrow_left', label: 'Arrow Left' }, - { id: 'arrow_right', label: 'Arrow Right' }, - { id: 'enter', label: 'Enter' }, -]; +import { getHosts } from '@/lib/api'; +import { DEFAULT_TMUX_PREFIX, isValidTmuxPrefix } from '@/lib/tmuxKeys'; const selectClassName = 'h-11 w-full rounded-md border bg-background px-3 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'; export function SessionDefaultsPanel() { - const virtualKeyboardKeys = useSettingsStore((state) => state.virtualKeyboardKeys); - const setVirtualKeyboardKeys = useSettingsStore((state) => state.setVirtualKeyboardKeys); + const terminalFontSize = useSettingsStore((state) => state.terminalFontSize); + const setTerminalFontSize = useSettingsStore((state) => state.setTerminalFontSize); + const terminalRailPreset = useSettingsStore((state) => state.terminalRailPreset); + const setTerminalRailPreset = useSettingsStore((state) => state.setTerminalRailPreset); + const terminalRailConfig = useSettingsStore((state) => state.terminalRailConfig); + const setTerminalRailConfig = useSettingsStore((state) => state.setTerminalRailConfig); + const tmuxPrefixByHost = useSettingsStore((state) => state.tmuxPrefixByHost); + const setTmuxPrefixForHost = useSettingsStore((state) => state.setTmuxPrefixForHost); const sessionNamingPattern = useSettingsStore((state) => state.sessionNamingPattern); const setSessionNamingPattern = useSettingsStore((state) => state.setSessionNamingPattern); const autoCreateGroup = useSettingsStore((state) => state.autoCreateGroup); @@ -38,14 +41,26 @@ export function SessionDefaultsPanel() { const setAutoLinkSessions = useSettingsStore((state) => state.setAutoLinkSessions); const defaultLinkType = useSettingsStore((state) => state.defaultLinkType); const setDefaultLinkType = useSettingsStore((state) => state.setDefaultLinkType); - const effectiveKeys = - virtualKeyboardKeys.length > 0 ? virtualKeyboardKeys : DEFAULT_VIRTUAL_KEY_ORDER; + const [railJson, setRailJson] = useState(() => JSON.stringify(terminalRailConfig, null, 2)); + const [railJsonError, setRailJsonError] = useState(null); + const { data: hostsData, isLoading: hostsLoading, isError: hostsError } = useQuery({ + queryKey: ['hosts'], + queryFn: getHosts, + staleTime: 30_000, + }); - const toggleVirtualKey = (key: VirtualKeyboardKey, enabled: boolean) => { - const keySet = new Set(effectiveKeys); - if (enabled) keySet.add(key); - else keySet.delete(key); - setVirtualKeyboardKeys(DEFAULT_VIRTUAL_KEY_ORDER.filter((entry) => keySet.has(entry))); + useEffect(() => { + setRailJson(JSON.stringify(terminalRailConfig, null, 2)); + setRailJsonError(null); + }, [terminalRailConfig]); + + const applyRailJson = () => { + try { + setTerminalRailConfig(parseTerminalRailConfig(JSON.parse(railJson))); + setRailJsonError(null); + } catch (error) { + setRailJsonError(error instanceof Error ? error.message : 'Rail config is invalid.'); + } }; return ( @@ -110,32 +125,114 @@ export function SessionDefaultsPanel() {
+
+
+ + + {terminalFontSize}px + +
+ setTerminalFontSize(Number(event.target.value))} + className="h-11 w-full cursor-pointer accent-primary" + /> +
+ Pinch with two fingers on the terminal to adjust live. + +
+
+ +
+
-

Virtual keyboard

+

Terminal key rail

- Quick keys shown on the mobile keyboard row. + JSON-defined keysyms, chords, macros, and swipe-up popup bindings.

-
+
+ + +
+
+ +