From 186a71702b6d3b0bf522515e52b23198fb4c9561 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 00:00:22 -0400 Subject: [PATCH 01/12] =?UTF-8?q?fix(db):=20grant=20agent=5Fconsole=20acce?= =?UTF-8?q?ss=20to=20user=5Fsettings=5Flegacy=5Fsubjects=20(migration=2003?= =?UTF-8?q?9;=20applied=20to=20prod)=20=E2=80=94=20settings=20cloud=20sync?= =?UTF-8?q?=20was=20failing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5 --- migrations/039_grant_legacy_settings_access.sql | 6 ++++++ tasks/frontend-ux-log.md | 1 + 2 files changed, 7 insertions(+) create mode 100644 migrations/039_grant_legacy_settings_access.sql diff --git a/migrations/039_grant_legacy_settings_access.sql b/migrations/039_grant_legacy_settings_access.sql new file mode 100644 index 00000000..16ab7b2d --- /dev/null +++ b/migrations/039_grant_legacy_settings_access.sql @@ -0,0 +1,6 @@ +-- The 0.4.x settings-claim path reads/writes user_settings_legacy_subjects. +-- That table was created by a superuser-run migration without granting the +-- application role, causing production PUT /v1/settings to 500 +-- ("permission denied") and the dashboard to fall back to local-only settings. +-- Idempotent re-grant; applied manually to production 2026-07-21. +GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE user_settings_legacy_subjects TO agent_console; diff --git a/tasks/frontend-ux-log.md b/tasks/frontend-ux-log.md index 706b877c..fff107c4 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -52,3 +52,4 @@ - ~08:50Z Batch-2 adversarial review: SHIP-WITH-NOTES. HIGH: allow-passthrough set at server scope (-s) where it's a pane option — OSC-133 command marks were silently inert; fixed to -p with scope-asserting test. MED gesture-timer collision (450/500ms) fixed via cursor-armed cancellation; pointercancel activation guard; per-frame query parse cached (then made test-safe after a red test slipped one commit — grep-masked exit code, lesson noted). LOWs backlogged. CLOSING GATE GREEN. WAVE 6 COMPLETE — PR next; owner device checklist (docs/device-checklist.md) is the final acceptance item post-deploy. - ~03:40Z (07-21) WAVE 6 MERGED (e8b9ce7, PR #91 — which turned out to be the never-merged close-out PR reused by gh; retitled) + DEPLOYED (SOURCE_COMMIT verified, agents:2). Tagged v0.4.1. agentd v0.4.1 binaries built on BOTH machines, staged for owner swap (policy). Remaining: owner binary swap + device checklist = program truly closed. - ~03:47Z agentd v0.4.1 ROLLED OUT fleet-wide (homelinux via owner ! command; heavisidelinux completed by AI Lead after the wrapped-line mv failure — swap succeeded, reconnected). Both hosts on the Wave-6 binary. ONLY REMAINING ITEM: owner device checklist (docs/device-checklist.md). +- ~04:20Z DEVICE-CHECKLIST FINDINGS (owner, S25 Ultra): (1) terminal attach/detach loop — letterbox dims were in the terminal identity key, fed by live topology that our own agentd pin/release mutates; fixed (key = session+pane, dims frozen per attachment), hotfix PR #92 merged + DEPLOYED (fbac2dd). (2) "settings saved locally" — production PUT /v1/settings 500: user_settings_legacy_subjects owned by postgres with no grant to agent_console (superuser-run migration gap); GRANT applied to prod + migration 039 recorded. Lesson: migrations run as superuser MUST include app-role GRANTs; device testing catches what emulation structurally cannot (both bugs required a real desktop-attached/production-DB environment). From d49682e671058c430ec9f2aade74fb905e08e552 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 00:06:14 -0400 Subject: [PATCH 02/12] docs(program): FW6-FOCUS punch-list brief (single-pane focus + instant in-session switching) Co-Authored-By: Claude Fable 5 --- tasks/2026-07-21-fw6-focus-brief.md | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 tasks/2026-07-21-fw6-focus-brief.md diff --git a/tasks/2026-07-21-fw6-focus-brief.md b/tasks/2026-07-21-fw6-focus-brief.md new file mode 100644 index 00000000..34802348 --- /dev/null +++ b/tasks/2026-07-21-fw6-focus-brief.md @@ -0,0 +1,30 @@ +# FW6-FOCUS — Single-pane focus + instant in-session switching (Wave 6 punch-list) + +Lane: FW6-FOCUS · Machine: homelinux · Worktree: `~/dev/wt/ac-fw6-focus` · Branch: `refactor/fw6-focus` (off `refactor/frontend-command-center`; local, do NOT push) +Owner device findings (S25 Ultra, production): (1) selecting a pane shows ALL panes of the window — unusable compression on mobile; single-pane focus is "a big deal". (2) Window switching via the strip "takes a while to connect" — every switch is a full detach/reattach round-trip. + +## Design (locked by AI Lead from the findings) + +The per-viewer grouped session IS an independent tmux client: it has its own current-window/current-pane. In-session navigation must happen INSIDE the live PTY (viewer-session `select-window`/`select-pane`/zoom) with the WebSocket and descriptor kept stable; only cross-tmux-session switches reattach. Single-pane focus = tmux zoom of the selected pane (shared window property — the desktop view zooms too; acceptable single-user trade-off, must be visible/predictable, and ALWAYS unzoomed on detach/switch-away). + +## Work items + +1. **agentd: viewer-scoped navigation ops.** New channel-scoped terminal messages (client→CP→agent alongside `terminal.input`/`resize`): `terminal.navigate` with `{op: 'select_window', window_index}` | `{op: 'select_pane', pane_id}` | `{op: 'zoom', on: boolean}` — executed against the VIEWER grouped session (`select-window -t :` etc.), NOT the origin session, so the desktop's active window/pane is never yanked by phone navigation. Zoom uses `resize-pane -Z` on the viewer's current pane (window-shared by tmux semantics — document it). Additive protocol + fixture + Go tests on private sockets. +2. **CP: relay** the new terminal message type channel-scoped (same pattern as `terminal.input`); additive schema; tests. +3. **Dashboard: in-session switching.** When the window strip (or Prev/Next, quick-switch, spatial pane nav) targets a window/pane in the SAME tmux session as the attached pane: keep the descriptor/WS untouched, send `terminal.navigate`, optimistically update the strip/URL (session_id still updates for state, but WITHOUT remounting the terminal — the descriptor key must stay stable across same-session retargets; extend the key/store contract accordingly). Cross-session targets keep today's reattach. Result: window switches feel instant. +4. **Dashboard: Focus mode.** Mobile status row gets a Focus toggle (maximize icon). Behavior: attaching a MULTI-pane window on mobile auto-enables Focus (zoom on the selected pane) — setting `autoFocusPane` default ON, toggleable; switching pane/window while focused re-zooms the new target; leaving the terminal, detaching, or toggling off unzooms. Desktop unaffected by default (no auto-zoom ≥1024px). The zoomed state must reflect tmux truth (topology `zoomed` flag) not just local state. +5. **Unzoom safety.** agentd unzooms the viewer's window on channel detach/supersede/sweep if the channel applied the zoom (track per-channel), so a dropped phone connection never leaves the desktop zoomed. +6. **Tests.** Go: viewer-scoped ops + unzoom-on-detach on private sockets. TS: same-session switch keeps the terminal instance (no remount — extend the existing same-instance test), focus toggle state machine, navigate-message emission. Journey: window-strip switch with no reconnect (assert no new terminal WS) + focus zoom round-trip. All suites green. + +## Ownership firewall + +You may edit: `agents/agentd/**`, `packages/ac-schema/**` (additive), `services/control-plane/**` (additive relay), `apps/dashboard/src/(components/(terminal|tmux|mobile)|hooks|stores|lib)/**`, `tests/fixtures/protocol/` (NEW files), `tests/journeys/**` (additive spec), related tests. You may NOT edit: `deploy/**`, launch/orchestrator/layout components, the letterbox freeze logic from the attach-loop hotfix (extend, don't rewrite — the descriptor-key contract note in `terminalHostStore.ts` explains why). + +## Gates + +Full chain: `pnpm lint && pnpm typecheck && pnpm test:ci && pnpm test:smoke:dashboard && pnpm test:journeys && pnpm build` + Go build/vet/test. Playwright from a tmux TTY. Commit per work item, prefix `feat(focus):`. ≤3 attempts per failure then hold. + +## Done + +Handoff `tasks/frontend-ux-handoffs/fw6-focus.md`, committed, then print exactly: +`FW6-FOCUS FROZEN ` From b29aab04084b862d9772af2a9ed4c85bfb221a93 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 00:15:21 -0400 Subject: [PATCH 03/12] feat(focus): add viewer-scoped terminal navigation --- agents/agentd/cmd/agentd/main.go | 39 +++++ .../agentd/cmd/agentd/main_terminal_test.go | 42 +++++ agents/agentd/internal/protocol/messages.go | 1 + agents/agentd/internal/protocol/terminal.go | 8 + .../agentd/internal/tmux/pty_bridge_test.go | 153 ++++++++++++++++++ agents/agentd/internal/tmux/terminal.go | 54 +++++++ agents/agentd/internal/tmux/viewer_pty.go | 101 ++++++++++++ .../internal/ws/protocol_fixtures_test.go | 3 + .../fixtures/protocol/terminal-navigate.json | 10 ++ 9 files changed, 411 insertions(+) create mode 100644 tests/fixtures/protocol/terminal-navigate.json diff --git a/agents/agentd/cmd/agentd/main.go b/agents/agentd/cmd/agentd/main.go index eb99dae6..2bd00e6a 100644 --- a/agents/agentd/cmd/agentd/main.go +++ b/agents/agentd/cmd/agentd/main.go @@ -1914,6 +1914,8 @@ func (a *Agent) handleMessage(msgType string, payload json.RawMessage) { a.handleTerminalInput(payload) case "terminal.resize": a.handleTerminalResize(payload) + case "terminal.navigate": + a.handleTerminalNavigate(payload) case "terminal.control": a.handleTerminalControl(payload) case "terminal.detach": @@ -5480,6 +5482,43 @@ func (a *Agent) handleTerminalResize(payload json.RawMessage) { } } +func (a *Agent) handleTerminalNavigate(payload json.RawMessage) { + var req protocol.TerminalNavigatePayload + if err := json.Unmarshal(payload, &req); err != nil { + log.Printf("Failed to parse terminal.navigate: %v", err) + return + } + + navigation := tmux.TerminalNavigation{Op: tmux.TerminalNavigationOp(req.Op)} + switch navigation.Op { + case tmux.NavigateSelectWindow: + if req.WindowIndex == nil { + log.Printf("Failed to parse terminal.navigate: select_window requires window_index") + return + } + navigation.WindowIndex = *req.WindowIndex + case tmux.NavigateSelectPane: + if strings.TrimSpace(req.PaneID) == "" { + log.Printf("Failed to parse terminal.navigate: select_pane requires pane_id") + return + } + navigation.PaneID = req.PaneID + case tmux.NavigateZoom: + if req.On == nil { + log.Printf("Failed to parse terminal.navigate: zoom requires on") + return + } + navigation.On = *req.On + default: + log.Printf("Failed to parse terminal.navigate: unsupported op %q", req.Op) + return + } + + if err := a.terminalManager.Navigate(req.ChannelID, navigation); err != nil { + log.Printf("Failed to navigate terminal: %v", err) + } +} + func (a *Agent) handleTerminalControl(payload json.RawMessage) { var req protocol.TerminalChannelPayload if err := json.Unmarshal(payload, &req); err != nil { diff --git a/agents/agentd/cmd/agentd/main_terminal_test.go b/agents/agentd/cmd/agentd/main_terminal_test.go index e78b044a..7f56eba5 100644 --- a/agents/agentd/cmd/agentd/main_terminal_test.go +++ b/agents/agentd/cmd/agentd/main_terminal_test.go @@ -67,6 +67,48 @@ func TestTerminalAuditHandlerEmitsAdditiveAuditEvent(t *testing.T) { } } +func TestHandleTerminalNavigateRoutesToGroupedViewerOnPrivateSocket(t *testing.T) { + tmuxClient := newPrivateCommandTmux(t) + panes, err := tmuxClient.ListPanes() + if err != nil || len(panes) != 1 { + t.Fatalf("initial panes=%+v err=%v", panes, err) + } + if _, err := tmuxClient.NewWindow("command-test", "second", ""); err != nil { + t.Fatalf("create second window: %v", err) + } + if err := tmuxClient.SelectWindow("command-test:0"); err != nil { + t.Fatalf("restore origin window: %v", err) + } + + manager := tmux.NewTerminalManager(tmuxClient, t.TempDir()) + manager.SetPerViewerPTY(true) + defer manager.Close() + if _, err := manager.AttachWithOptions("navigate-channel", panes[0].PaneID, tmux.AttachOptions{SessionID: "session-1"}); err != nil { + t.Fatalf("attach viewer: %v", err) + } + agent := &Agent{terminalManager: manager} + windowIndex := 1 + payload, err := json.Marshal(protocol.TerminalNavigatePayload{ + ChannelID: "navigate-channel", + Op: "select_window", + WindowIndex: &windowIndex, + }) + if err != nil { + t.Fatal(err) + } + agent.handleMessage(protocol.TypeTerminalNavigate, payload) + + panes, err = tmuxClient.ListPanes() + if err != nil { + t.Fatal(err) + } + for _, pane := range panes { + if pane.SessionName == "command-test" && pane.WindowIndex == 0 && !pane.WindowActive { + t.Fatal("terminal.navigate changed the origin session's current window") + } + } +} + func TestTerminalAttachSupersedesStaleChannelAfterControlPlaneReconnect(t *testing.T) { tmuxClient := newPrivateCommandTmux(t) panes, err := tmuxClient.ListPanes() diff --git a/agents/agentd/internal/protocol/messages.go b/agents/agentd/internal/protocol/messages.go index b557f6b8..80f50b4c 100644 --- a/agents/agentd/internal/protocol/messages.go +++ b/agents/agentd/internal/protocol/messages.go @@ -32,6 +32,7 @@ const ( TypeTerminalAttach = "terminal.attach" TypeTerminalInput = "terminal.input" TypeTerminalResize = "terminal.resize" + TypeTerminalNavigate = "terminal.navigate" TypeTerminalDetach = "terminal.detach" TypeTerminalControl = "terminal.control" TypeTerminalOutput = "terminal.output" diff --git a/agents/agentd/internal/protocol/terminal.go b/agents/agentd/internal/protocol/terminal.go index 9f9387d7..612c1d66 100644 --- a/agents/agentd/internal/protocol/terminal.go +++ b/agents/agentd/internal/protocol/terminal.go @@ -21,6 +21,14 @@ type TerminalResizePayload struct { Rows int `json:"rows"` } +type TerminalNavigatePayload struct { + ChannelID string `json:"channel_id"` + Op string `json:"op"` + WindowIndex *int `json:"window_index,omitempty"` + PaneID string `json:"pane_id,omitempty"` + On *bool `json:"on,omitempty"` +} + type TerminalChannelPayload struct { ChannelID string `json:"channel_id"` } diff --git a/agents/agentd/internal/tmux/pty_bridge_test.go b/agents/agentd/internal/tmux/pty_bridge_test.go index fdfb1328..4935383e 100644 --- a/agents/agentd/internal/tmux/pty_bridge_test.go +++ b/agents/agentd/internal/tmux/pty_bridge_test.go @@ -72,6 +72,37 @@ func TestViewerPTYBridgePinsAndReleasesLetterboxedWindow(t *testing.T) { } } +func TestViewerPTYBridgeMovesLetterboxPinWhenSelectingWindow(t *testing.T) { + runner := newFakeTmuxRunner() + runner.outputs["display-message -p -t %7 #{session_name}\t#{window_index}\t#{pane_index}"] = []byte("agents\t2\t1\n") + bridge, err := newViewerPTYBridge(runner, viewerPTYOptions{ + ChannelID: "channel-1", + PaneID: "%7", + Cols: 160, + Rows: 50, + Letterbox: true, + ResumeToken: "resume-1", + }) + if err != nil { + t.Fatalf("newViewerPTYBridge: %v", err) + } + defer bridge.close(false) + + if err := bridge.SelectWindow(3); err != nil { + t.Fatalf("select letterboxed viewer window: %v", err) + } + for _, want := range [][]string{ + {"set-option", "-w", "-t", "ac-view-channel-1:2", "window-size", "latest"}, + {"select-window", "-t", "ac-view-channel-1:3"}, + {"set-option", "-w", "-t", "ac-view-channel-1:3", "window-size", "manual"}, + {"resize-window", "-t", "ac-view-channel-1:3", "-x", "160", "-y", "50"}, + } { + if !runner.hasRun(want) { + t.Fatalf("missing letterbox navigation command %v; runs=%v", want, runner.runs) + } + } +} + func TestViewerPTYBridgeLetterboxUsesPrivateTmuxSocket(t *testing.T) { client, _ := newPrivateTmuxClient(t) panes, err := client.ListPanes() @@ -113,6 +144,128 @@ func TestViewerPTYBridgeLetterboxUsesPrivateTmuxSocket(t *testing.T) { } } +func TestTerminalNavigateSelectWindowUsesViewerSessionOnPrivateTmuxSocket(t *testing.T) { + client, _ := newPrivateTmuxClient(t) + panes, err := client.ListPanes() + if err != nil || len(panes) != 1 { + t.Fatalf("initial private panes=%+v err=%v", panes, err) + } + if _, err := client.NewWindow("hook-test", "second", ""); err != nil { + t.Fatalf("create second private window: %v", err) + } + if err := client.SelectWindow("hook-test:0"); err != nil { + t.Fatalf("restore origin window: %v", err) + } + + runner := newExecTmuxRunner(client) + manager := newTerminalManagerWithRunner(client, runner, t.TempDir()) + defer manager.Close() + if _, err := manager.AttachWithOptions("navigate-integration", panes[0].PaneID, AttachOptions{ + SessionID: "session-1", + Cols: 120, + Rows: 40, + }); err != nil { + t.Fatalf("attach viewer: %v", err) + } + + if err := manager.Navigate("navigate-integration", TerminalNavigation{Op: NavigateSelectWindow, WindowIndex: 1}); err != nil { + t.Fatalf("navigate viewer window: %v", err) + } + + if output, err := runner.Output("display-message", "-p", "-t", "hook-test", "#{window_index}"); err != nil { + t.Fatalf("read origin current window: %v", err) + } else if got := strings.TrimSpace(string(output)); got != "0" { + t.Fatalf("origin current window=%q, want 0", got) + } + if output, err := runner.Output("display-message", "-p", "-t", viewerSessionName("navigate-integration"), "#{window_index}"); err != nil { + t.Fatalf("read viewer current window: %v", err) + } else if got := strings.TrimSpace(string(output)); got != "1" { + t.Fatalf("viewer current window=%q, want 1", got) + } +} + +func TestTerminalNavigateSelectPaneUsesViewerSessionOnPrivateTmuxSocket(t *testing.T) { + client, _ := newPrivateTmuxClient(t) + panes, err := client.ListPanes() + if err != nil || len(panes) != 1 { + t.Fatalf("initial private panes=%+v err=%v", panes, err) + } + originPaneID := panes[0].PaneID + target, err := client.SplitPaneWithOptions(originPaneID, "horizontal", nil, "") + if err != nil { + t.Fatalf("split private pane: %v", err) + } + if err := client.SelectPane(originPaneID); err != nil { + t.Fatalf("restore origin pane: %v", err) + } + + runner := newExecTmuxRunner(client) + manager := newTerminalManagerWithRunner(client, runner, t.TempDir()) + defer manager.Close() + if _, err := manager.AttachWithOptions("pane-navigation", originPaneID, AttachOptions{SessionID: "session-1"}); err != nil { + t.Fatalf("attach viewer: %v", err) + } + if err := manager.Navigate("pane-navigation", TerminalNavigation{Op: NavigateSelectPane, PaneID: target.PaneID}); err != nil { + t.Fatalf("navigate viewer pane: %v", err) + } + + if output, err := runner.Output("display-message", "-p", "-t", "hook-test", "#{window_index}"); err != nil { + t.Fatalf("read origin current window: %v", err) + } else if got := strings.TrimSpace(string(output)); got != "0" { + t.Fatalf("origin current window=%q, want 0", got) + } + if output, err := runner.Output("display-message", "-p", "-t", viewerSessionName("pane-navigation"), "#{pane_id}"); err != nil { + t.Fatalf("read viewer current pane: %v", err) + } else if got := strings.TrimSpace(string(output)); got != target.PaneID { + t.Fatalf("viewer current pane=%q, want %q", got, target.PaneID) + } +} + +func TestTerminalNavigateZoomSetsRequestedStateOnPrivateTmuxSocket(t *testing.T) { + client, _ := newPrivateTmuxClient(t) + panes, err := client.ListPanes() + if err != nil || len(panes) != 1 { + t.Fatalf("initial private panes=%+v err=%v", panes, err) + } + if _, err := client.SplitPaneWithOptions(panes[0].PaneID, "horizontal", nil, ""); err != nil { + t.Fatalf("split private pane: %v", err) + } + + manager := newTerminalManagerWithRunner(client, newExecTmuxRunner(client), t.TempDir()) + defer manager.Close() + if _, err := manager.AttachWithOptions("zoom-navigation", panes[0].PaneID, AttachOptions{SessionID: "session-1"}); err != nil { + t.Fatalf("attach viewer: %v", err) + } + if err := manager.Navigate("zoom-navigation", TerminalNavigation{Op: NavigateZoom, On: true}); err != nil { + t.Fatalf("enable viewer zoom: %v", err) + } + assertWindowZoomed(t, client, true) + + // The operation is a state setter, not resize-pane's raw toggle. + if err := manager.Navigate("zoom-navigation", TerminalNavigation{Op: NavigateZoom, On: true}); err != nil { + t.Fatalf("keep viewer zoom enabled: %v", err) + } + assertWindowZoomed(t, client, true) + + if err := manager.Navigate("zoom-navigation", TerminalNavigation{Op: NavigateZoom, On: false}); err != nil { + t.Fatalf("disable viewer zoom: %v", err) + } + assertWindowZoomed(t, client, false) +} + +func assertWindowZoomed(t *testing.T, client *Client, want bool) { + t.Helper() + panes, err := client.ListPanes() + if err != nil { + t.Fatalf("list panes for zoom state: %v", err) + } + for _, pane := range panes { + if pane.WindowZoomed != want { + t.Fatalf("pane %s zoomed=%v, want %v", pane.PaneID, pane.WindowZoomed, want) + } + } +} + func TestViewerSessionNameAvoidsSanitizationCollisions(t *testing.T) { first := viewerSessionName("channel/one") second := viewerSessionName("channel:one") diff --git a/agents/agentd/internal/tmux/terminal.go b/agents/agentd/internal/tmux/terminal.go index b4b61eb3..266a47e8 100644 --- a/agents/agentd/internal/tmux/terminal.go +++ b/agents/agentd/internal/tmux/terminal.go @@ -88,6 +88,23 @@ type terminalViewer struct { staleAt time.Time } +type TerminalNavigationOp string + +const ( + NavigateSelectWindow TerminalNavigationOp = "select_window" + NavigateSelectPane TerminalNavigationOp = "select_pane" + NavigateZoom TerminalNavigationOp = "zoom" +) + +// TerminalNavigation describes an operation against a channel's grouped tmux +// session. It never targets the origin session directly. +type TerminalNavigation struct { + Op TerminalNavigationOp + WindowIndex int + PaneID string + On bool +} + // AttachOptions contains additive terminal.attach fields. type AttachOptions struct { SessionID string @@ -723,6 +740,43 @@ func (m *TerminalManager) SendInput(channelID string, data string) error { return m.client.SendKeysRaw(paneID, data) } +// Navigate changes the current target of a grouped viewer without replacing +// its PTY bridge. The origin tmux session keeps its own current window. +func (m *TerminalManager) Navigate(channelID string, navigation TerminalNavigation) error { + m.mu.RLock() + _, exists := m.channelToPane[channelID] + viewer := m.viewerByChannel[channelID] + var bridge *viewerPTYBridge + if viewer != nil { + bridge = viewer.bridge + } + m.mu.RUnlock() + + if !exists { + return fmt.Errorf("channel %s not found", channelID) + } + if bridge == nil { + return fmt.Errorf("channel %s does not use a grouped viewer session", channelID) + } + + switch navigation.Op { + case NavigateSelectWindow: + if navigation.WindowIndex < 0 { + return fmt.Errorf("window index must be non-negative") + } + return bridge.SelectWindow(navigation.WindowIndex) + case NavigateSelectPane: + if strings.TrimSpace(navigation.PaneID) == "" { + return fmt.Errorf("pane id is required") + } + return bridge.SelectPane(navigation.PaneID) + case NavigateZoom: + return bridge.SetZoom(navigation.On) + default: + return fmt.Errorf("unsupported terminal navigation op %q", navigation.Op) + } +} + // TakeControl promotes the given channel to controller for its pane. func (m *TerminalManager) TakeControl(channelID string) error { m.mu.Lock() diff --git a/agents/agentd/internal/tmux/viewer_pty.go b/agents/agentd/internal/tmux/viewer_pty.go index a8882b2d..0986393e 100644 --- a/agents/agentd/internal/tmux/viewer_pty.go +++ b/agents/agentd/internal/tmux/viewer_pty.go @@ -7,6 +7,7 @@ import ( "io" "os" "os/exec" + "strconv" "strings" "sync" "time" @@ -279,6 +280,106 @@ func (b *viewerPTYBridge) Size() TerminalSize { return b.size } +func (b *viewerPTYBridge) SelectWindow(windowIndex int) error { + b.mu.Lock() + defer b.mu.Unlock() + select { + case <-b.closed: + return fmt.Errorf("viewer PTY is closed") + default: + } + + target := b.viewSession + ":" + strconv.Itoa(windowIndex) + return b.selectWindowLocked(target) +} + +func (b *viewerPTYBridge) SelectPane(paneID string) error { + b.mu.Lock() + defer b.mu.Unlock() + select { + case <-b.closed: + return fmt.Errorf("viewer PTY is closed") + default: + } + + described, err := b.runner.Output("display-message", "-p", "-t", paneID, "#{window_index}\t#{pane_index}") + if err != nil { + return fmt.Errorf("describe viewer pane %s: %w", paneID, err) + } + parts := strings.Split(strings.TrimSpace(string(described)), "\t") + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return fmt.Errorf("unexpected tmux pane target %q for %s", strings.TrimSpace(string(described)), paneID) + } + + windowTarget := b.viewSession + ":" + parts[0] + paneTarget := windowTarget + "." + parts[1] + resolved, err := b.runner.Output("display-message", "-p", "-t", paneTarget, "#{pane_id}") + if err != nil || strings.TrimSpace(string(resolved)) != paneID { + return fmt.Errorf("pane %s is not in grouped viewer session", paneID) + } + if err := b.selectWindowLocked(windowTarget); err != nil { + return fmt.Errorf("select viewer pane window: %w", err) + } + if err := b.runner.Run("select-pane", "-t", paneTarget); err != nil { + return fmt.Errorf("select viewer pane: %w", err) + } + return nil +} + +func (b *viewerPTYBridge) selectWindowLocked(target string) error { + previous := b.windowTarget + if b.letterbox && previous != target { + if err := b.runner.Run("set-option", "-w", "-t", previous, "window-size", "latest"); err != nil { + return fmt.Errorf("release previous viewer window sizing: %w", err) + } + } + if err := b.runner.Run("select-window", "-t", target); err != nil { + return fmt.Errorf("select viewer window: %w", err) + } + if b.letterbox && previous != target { + if err := b.runner.Run("set-option", "-w", "-t", target, "window-size", "manual"); err != nil { + _ = b.runner.Run("set-option", "-w", "-t", target, "window-size", "latest") + return fmt.Errorf("pin selected viewer window sizing: %w", err) + } + if err := b.runner.Run( + "resize-window", + "-t", target, + "-x", fmt.Sprintf("%d", b.size.Cols), + "-y", fmt.Sprintf("%d", b.size.Rows), + ); err != nil { + _ = b.runner.Run("set-option", "-w", "-t", target, "window-size", "latest") + return fmt.Errorf("size selected viewer window: %w", err) + } + } + b.windowTarget = target + return nil +} + +func (b *viewerPTYBridge) SetZoom(on bool) error { + b.mu.Lock() + defer b.mu.Unlock() + select { + case <-b.closed: + return fmt.Errorf("viewer PTY is closed") + default: + } + + zoomed, err := b.runner.Output("display-message", "-p", "-t", b.viewSession, "#{window_zoomed_flag}") + if err != nil { + return fmt.Errorf("read viewer zoom state: %w", err) + } + isZoomed := strings.TrimSpace(string(zoomed)) == "1" + if isZoomed == on { + return nil + } + // Zoom is a window-shared tmux property even though navigation targets the + // grouped viewer. Callers must surface that shared effect predictably. + if err := b.runner.Run("resize-pane", "-Z", "-t", b.viewSession+":"); err != nil { + return fmt.Errorf("set viewer zoom state: %w", err) + } + return nil +} + func (b *viewerPTYBridge) DetachChannel(channelID string) { if b.fanout != nil { b.fanout.Detach(channelID) diff --git a/agents/agentd/internal/ws/protocol_fixtures_test.go b/agents/agentd/internal/ws/protocol_fixtures_test.go index 063881f0..2f372508 100644 --- a/agents/agentd/internal/ws/protocol_fixtures_test.go +++ b/agents/agentd/internal/ws/protocol_fixtures_test.go @@ -71,6 +71,7 @@ func TestProtocolFixtureMatrixRoundTripsProductionTypes(t *testing.T) { protocol.TypeMCPGetProjectConfig, protocol.TypeMCPUpdateProject, protocol.TypeMCPServers, protocol.TypeMCPConfig, protocol.TypeMCPProjectConfig, protocol.TypeMCPUpdateResult, protocol.TypeTerminalAttach, protocol.TypeTerminalInput, protocol.TypeTerminalResize, + protocol.TypeTerminalNavigate, protocol.TypeTerminalDetach, protocol.TypeTerminalControl, protocol.TypeTerminalOutput, protocol.TypeTerminalAttached, protocol.TypeTerminalDetached, protocol.TypeTerminalError, protocol.TypeTerminalReadOnly, protocol.TypeTerminalLag, protocol.TypeTerminalAudit, @@ -151,6 +152,8 @@ func fixtureMessageTarget(t *testing.T, messageType string, agentMessage bool) a return &protocol.ServerMessage[protocol.TerminalInputPayload]{} case protocol.TypeTerminalResize: return &protocol.ServerMessage[protocol.TerminalResizePayload]{} + case protocol.TypeTerminalNavigate: + return &protocol.ServerMessage[protocol.TerminalNavigatePayload]{} case protocol.TypeTerminalDetach: return &protocol.ServerMessage[protocol.TerminalChannelPayload]{} case protocol.TypeTerminalOutput: diff --git a/tests/fixtures/protocol/terminal-navigate.json b/tests/fixtures/protocol/terminal-navigate.json new file mode 100644 index 00000000..cd03d5b8 --- /dev/null +++ b/tests/fixtures/protocol/terminal-navigate.json @@ -0,0 +1,10 @@ +{ + "v": 1, + "type": "terminal.navigate", + "ts": "2026-07-21T15:00:00.000Z", + "payload": { + "channel_id": "33333333-3333-4333-8333-333333333333", + "op": "select_window", + "window_index": 2 + } +} From 8c2428661fa1913c13075b52d55b45dff8f7a6b7 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 00:19:57 -0400 Subject: [PATCH 04/12] feat(focus): relay channel navigation messages --- packages/ac-schema/src/message.ts | 26 +++++++++++++++ packages/ac-schema/src/terminal.ts | 21 +++++++++++- .../ac-schema/tests/protocol-fixtures.test.ts | 1 + packages/ac-schema/tests/terminal.test.ts | 27 ++++++++++++++++ services/control-plane/src/routes/terminal.ts | 16 ++++++++++ .../control-plane/tests/terminalRoute.test.ts | 32 +++++++++++++++++++ 6 files changed, 122 insertions(+), 1 deletion(-) diff --git a/packages/ac-schema/src/message.ts b/packages/ac-schema/src/message.ts index dd26a049..80475583 100644 --- a/packages/ac-schema/src/message.ts +++ b/packages/ac-schema/src/message.ts @@ -336,6 +336,31 @@ export const TerminalResizeMessageSchema = ServerMessageEnvelopeSchema.extend({ }); export type TerminalResizeMessage = z.infer; +export const TerminalNavigatePayloadSchema = z.discriminatedUnion('op', [ + z.object({ + channel_id: z.string().uuid(), + op: z.literal('select_window'), + window_index: z.number().int().nonnegative(), + }), + z.object({ + channel_id: z.string().uuid(), + op: z.literal('select_pane'), + pane_id: z.string().min(1), + }), + z.object({ + channel_id: z.string().uuid(), + op: z.literal('zoom'), + on: z.boolean(), + }), +]); +export type TerminalNavigatePayload = z.infer; + +export const TerminalNavigateMessageSchema = ServerMessageEnvelopeSchema.extend({ + type: z.literal('terminal.navigate'), + payload: TerminalNavigatePayloadSchema, +}); +export type TerminalNavigateMessage = z.infer; + export const TerminalDetachMessageSchema = ServerMessageEnvelopeSchema.extend({ type: z.literal('terminal.detach'), payload: z.object({ @@ -366,6 +391,7 @@ export const ServerToAgentMessageSchema = z.discriminatedUnion('type', [ TerminalAttachMessageSchema, TerminalInputMessageSchema, TerminalResizeMessageSchema, + TerminalNavigateMessageSchema, TerminalDetachMessageSchema, TerminalControlMessageSchema, ApprovalsDecisionMessageSchema, diff --git a/packages/ac-schema/src/terminal.ts b/packages/ac-schema/src/terminal.ts index 4793fe56..1ea63365 100644 --- a/packages/ac-schema/src/terminal.ts +++ b/packages/ac-schema/src/terminal.ts @@ -26,12 +26,31 @@ export const BrowserTerminalDetachMessageSchema = z.object({ type: z.literal('detach'), }); -export const BrowserTerminalClientMessageSchema = z.discriminatedUnion('type', [ +export const BrowserTerminalNavigateMessageSchema = z.discriminatedUnion('op', [ + z.object({ + type: z.literal('navigate'), + op: z.literal('select_window'), + window_index: z.number().int().nonnegative(), + }), + z.object({ + type: z.literal('navigate'), + op: z.literal('select_pane'), + pane_id: z.string().min(1), + }), + z.object({ + type: z.literal('navigate'), + op: z.literal('zoom'), + on: z.boolean(), + }), +]); + +export const BrowserTerminalClientMessageSchema = z.union([ BrowserTerminalHelloMessageSchema, BrowserTerminalInputMessageSchema, BrowserTerminalResizeMessageSchema, BrowserTerminalControlMessageSchema, BrowserTerminalDetachMessageSchema, + BrowserTerminalNavigateMessageSchema, ]); export type BrowserTerminalClientMessage = z.infer; diff --git a/packages/ac-schema/tests/protocol-fixtures.test.ts b/packages/ac-schema/tests/protocol-fixtures.test.ts index 9b83392b..a7e7a564 100644 --- a/packages/ac-schema/tests/protocol-fixtures.test.ts +++ b/packages/ac-schema/tests/protocol-fixtures.test.ts @@ -44,6 +44,7 @@ describe('protocol fixtures', () => { 'terminal-attach.json', 'terminal-attach-letterbox.json', 'terminal-input.json', + 'terminal-navigate.json', 'commands-dispatch-send-input.json', ])('validates server-to-agent message fixture %s', (name) => { expect(ServerToAgentMessageSchema.safeParse(readFixture(name)).success).toBe(true); diff --git a/packages/ac-schema/tests/terminal.test.ts b/packages/ac-schema/tests/terminal.test.ts index b80cd61a..0e05178c 100644 --- a/packages/ac-schema/tests/terminal.test.ts +++ b/packages/ac-schema/tests/terminal.test.ts @@ -8,6 +8,33 @@ import { } from '../src/index.js'; describe('terminal protocol', () => { + it('accepts only complete viewer navigation operations from browsers', () => { + expect(BrowserTerminalClientMessageSchema.parse({ + type: 'navigate', + op: 'select_window', + window_index: 2, + })).toMatchObject({ op: 'select_window', window_index: 2 }); + expect(BrowserTerminalClientMessageSchema.parse({ + type: 'navigate', + op: 'select_pane', + pane_id: '%7', + })).toMatchObject({ op: 'select_pane', pane_id: '%7' }); + expect(BrowserTerminalClientMessageSchema.parse({ + type: 'navigate', + op: 'zoom', + on: true, + })).toMatchObject({ op: 'zoom', on: true }); + + expect(BrowserTerminalClientMessageSchema.safeParse({ + type: 'navigate', + op: 'select_window', + }).success).toBe(false); + expect(BrowserTerminalClientMessageSchema.safeParse({ + type: 'navigate', + op: 'zoom', + }).success).toBe(false); + }); + it('accepts the additive binary, resume, sizing, idle, and lag messages', () => { expect(BrowserTerminalClientMessageSchema.parse({ type: 'hello', binary: true })).toEqual({ type: 'hello', diff --git a/services/control-plane/src/routes/terminal.ts b/services/control-plane/src/routes/terminal.ts index 29e03c03..82048067 100644 --- a/services/control-plane/src/routes/terminal.ts +++ b/services/control-plane/src/routes/terminal.ts @@ -383,6 +383,22 @@ export function registerTerminalRoutes(app: FastifyInstance): void { }); break; + case 'navigate': { + if (!canControlTerminal(channel.user)) { + socket.close(4008, 'Terminal navigation requires operator role'); + return; + } + const { type: _type, ...navigation } = message; + pubsub.sendToAgent(channel.hostId, { + v: 1, + type: 'terminal.navigate', + ts: new Date().toISOString(), + payload: { channel_id: activeChannelId, ...navigation }, + }); + resetIdleTimeout(activeChannelId); + break; + } + case 'detach': detachChannel(activeChannelId, 'client_request'); break; diff --git a/services/control-plane/tests/terminalRoute.test.ts b/services/control-plane/tests/terminalRoute.test.ts index de641969..2edd7b60 100644 --- a/services/control-plane/tests/terminalRoute.test.ts +++ b/services/control-plane/tests/terminalRoute.test.ts @@ -497,6 +497,38 @@ describe('terminal websocket route', () => { await app.close(); }); + it('relays viewer navigation operations on the attached terminal channel', async () => { + const { app, baseWsUrl, agentSend } = await buildServer(); + const token = await sign('operator'); + const socket = browserWebSocket(`${baseWsUrl}/v1/ui/terminal/${sessionId}?token=${token}`); + + await waitForOpen(socket); + await eventually(() => { + expect(agentSend).toHaveBeenCalledWith(expect.stringContaining('terminal.attach')); + }); + const attach = agentSend.mock.calls + .map(([raw]) => JSON.parse(String(raw)) as { type: string; payload: { channel_id: string } }) + .find((message) => message.type === 'terminal.attach'); + + socket.send(JSON.stringify({ type: 'navigate', op: 'select_window', window_index: 2 })); + socket.send(JSON.stringify({ type: 'navigate', op: 'select_pane', pane_id: '%7' })); + socket.send(JSON.stringify({ type: 'navigate', op: 'zoom', on: true })); + + await eventually(() => { + const navigations = agentSend.mock.calls + .map(([raw]) => JSON.parse(String(raw)) as { type: string; payload: Record }) + .filter((message) => message.type === 'terminal.navigate'); + expect(navigations.map((message) => message.payload)).toEqual([ + { channel_id: attach?.payload.channel_id, op: 'select_window', window_index: 2 }, + { channel_id: attach?.payload.channel_id, op: 'select_pane', pane_id: '%7' }, + { channel_id: attach?.payload.channel_id, op: 'zoom', on: true }, + ]); + }); + + socket.close(); + await app.close(); + }); + it('allows multiple browser viewers for the same session without evicting the first viewer', async () => { const { app, baseWsUrl, agentSend } = await buildServer(); const token = await sign('operator'); From 6fb43c2071886e68dae458a74361764d2b735ee3 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 00:31:04 -0400 Subject: [PATCH 05/12] feat(focus): switch tmux panes without reconnecting --- .../dashboard/src/components/TerminalView.tsx | 3 + .../terminal/PersistentTerminalHost.tsx | 22 ++-- .../src/components/terminal/protocol.test.ts | 31 ++++- .../src/components/terminal/protocol.ts | 10 ++ .../terminal/terminalHostStore.test.ts | 116 ++++++++++++++++++ .../components/terminal/terminalHostStore.ts | 55 +++++++-- .../src/components/terminal/types.ts | 3 + .../src/components/tmux/TmuxActionSheet.tsx | 10 +- .../src/components/tmux/TmuxMobileShell.tsx | 1 + .../src/components/tmux/TmuxPaneControls.tsx | 21 ++-- .../components/tmux/TmuxTerminalWorkspace.tsx | Bin 10101 -> 10018 bytes .../src/components/tmux/TmuxWindowStrip.tsx | 12 +- .../src/hooks/tmuxNavigation.test.ts | 17 +++ apps/dashboard/src/hooks/tmuxNavigation.ts | 30 +++++ .../src/hooks/useTerminalConnection.ts | 7 ++ apps/dashboard/src/hooks/useTmuxRosterData.ts | 12 ++ packages/ac-schema/src/terminal.ts | 1 + 17 files changed, 320 insertions(+), 31 deletions(-) diff --git a/apps/dashboard/src/components/TerminalView.tsx b/apps/dashboard/src/components/TerminalView.tsx index 59857933..b8568c55 100644 --- a/apps/dashboard/src/components/TerminalView.tsx +++ b/apps/dashboard/src/components/TerminalView.tsx @@ -191,6 +191,7 @@ export function TerminalView({ disconnect, suspend, takeControl, + navigate, sendInput, } = useTerminalConnection({ sessionId, @@ -268,6 +269,7 @@ export function TerminalView({ detach: disconnect, suspend, takeControl, + navigate, focus: () => terminalRef.current?.focus(), copySelection, copyLastLines: (lines = 50) => copyLastLines(lines), @@ -296,6 +298,7 @@ export function TerminalView({ copySelection, disconnect, onControllerChange, + navigate, paste, terminalRef, suspend, diff --git a/apps/dashboard/src/components/terminal/PersistentTerminalHost.tsx b/apps/dashboard/src/components/terminal/PersistentTerminalHost.tsx index dc84d58a..ed9360ac 100644 --- a/apps/dashboard/src/components/terminal/PersistentTerminalHost.tsx +++ b/apps/dashboard/src/components/terminal/PersistentTerminalHost.tsx @@ -41,6 +41,7 @@ export function PersistentTerminalSlot({ sessionId, hostId, paneId, + tmuxSessionKey, autoAttach, letterbox, className, @@ -55,7 +56,7 @@ export function PersistentTerminalSlot({ const unregister = terminalHostStore.registerSurface({ id, - descriptor: { sessionId, hostId, paneId, autoAttach, letterbox }, + descriptor: { sessionId, hostId, paneId, tmuxSessionKey, autoAttach, letterbox }, target, visible: isSurfaceVisible(target), controllerRef, @@ -69,7 +70,7 @@ export function PersistentTerminalSlot({ resizeObserver.disconnect(); unregister(); }; - }, [autoAttach, controllerRef, hostId, id, letterbox, paneId, sessionId]); + }, [autoAttach, controllerRef, hostId, id, letterbox, paneId, sessionId, tmuxSessionKey]); return (
state.terminalWarmTimeoutMinutes ?? DEFAULT_TERMINAL_WARM_TIMEOUT_MINUTES ); - const terminalContext = snapshot.descriptor + const attachmentDescriptor = snapshot.attachmentDescriptor ?? snapshot.descriptor; + const terminalContext = attachmentDescriptor ? { descriptorKey: snapshot.descriptorKey!, - letterbox: snapshot.descriptor.letterbox, - warmKey: getTerminalWarmKey(snapshot.descriptor), + letterbox: attachmentDescriptor.letterbox, + warmKey: getTerminalWarmKey(attachmentDescriptor), } : undefined; @@ -165,14 +167,14 @@ export function PersistentTerminalHost() { return ( <> - {session && } + {session && ( + + )}