Skip to content

fix(mobile): single-pane Focus mode + instant in-session window switching (FW6-FOCUS) - #93

Merged
cvsloane merged 13 commits into
mainfrom
refactor/frontend-command-center
Jul 21, 2026
Merged

cvsloane merged 13 commits into
mainfrom
refactor/frontend-command-center

Conversation

@cvsloane

@cvsloane cvsloane commented Jul 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fixes the two remaining owner device-checklist findings (S25 Ultra, production):

  1. Selecting a pane showed the whole multi-pane window — unusably compressed on a phone. Mobile now gets a Focus mode: attaching a multi-pane window auto-zooms the selected pane full-screen (persisted autoFocusPane setting, default on), with a visible maximize toggle in the status row whose pressed state mirrors tmux topology truth. tmux zoom is window-shared, so the desktop view of that window zooms too (accepted single-user trade-off); agentd tracks channel-owned zoom and force-unzooms on every teardown path (detach, supersede, stale connection, TTL sweep, manager close) so a dropped phone can never leave the desktop stuck zoomed.
  2. Window switching "takes a while to connect" — every switch was a full detach/reattach. New channel-scoped terminal.navigate protocol (select_window / select_pane / zoom) executes against the per-viewer grouped session, so same-session switches keep the WebSocket, descriptor, and xterm instance — instant — and phone navigation no longer yanks the desktop's active window (grouped sessions have independent current-window). Cross-session targets keep the reattach path. The letterbox window-size pin migrates release→select→pin→resize across viewer window switches.

Review chain

  • Lane FW6-FOCUS frozen at a62bef5 (green full gate, attempt 2); AI Lead firewall audit + diff review: SHIP with one integration fix (attachment-key NUL separator was a literal byte, making TmuxTerminalWorkspace.tsx binary to git — respelled as escape).
  • Integration gate green: lint, typecheck, 508 unit tests, 21/21 smoke, 28 journeys, production build, Go build/vet/test incl. real-tmux private-socket coverage of viewer navigation and unzoom-on-detach.
  • Journey net strengthened: window-strip switch now asserts no new terminal WebSocket and that the legacy select_window command path is unused.

Deploy notes

  • agentd changed → fleet binary rollout required after merge (both hosts).
  • Schema change is additive (terminal.navigate union member); CP relay is operator-gated like input.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Navigate terminal windows and panes without reconnecting or losing the active terminal session.
    • Added mobile Focus controls with automatic zooming for multi-pane terminals.
    • Added configurable automatic pane focus behavior.
    • Terminal zoom state now remains synchronized during switching, detaching, and reconnecting.
  • Bug Fixes

    • Improved letterbox sizing when changing terminal windows.
    • Resolved a settings persistence permission issue.

@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR introduces a terminal.navigate protocol message (select_window, select_pane, zoom) spanning ac-schema, agentd, and control-plane, plus tmux zoom-lifecycle tracking. The dashboard gains same-session navigation retargeting, a mobile Focus toggle, an autoFocusPane setting, tests, docs, and a DB grant migration.

Changes

Terminal Navigate Protocol and Focus Feature

Layer / File(s) Summary
Protocol schema and fixtures
packages/ac-schema/src/message.ts, packages/ac-schema/src/terminal.ts, packages/ac-schema/tests/*, tests/fixtures/protocol/terminal-navigate.json, agents/agentd/internal/protocol/messages.go, agents/agentd/internal/protocol/terminal.go
Adds terminal.navigate discriminated schemas (select_window/select_pane/zoom) for server-to-agent and browser client messages, a Go TerminalNavigatePayload/TypeTerminalNavigate, and a fixture with round-trip tests.
agentd navigate handling and tmux zoom logic
agents/agentd/cmd/agentd/main.go, agents/agentd/internal/tmux/terminal.go, agents/agentd/internal/tmux/viewer_pty.go, *_test.go
Routes terminal.navigate to a new handler that validates and calls TerminalManager.Navigate; adds zoomApplied tracking with cleanup on sweep/detach/supersede/close, and SelectWindow/SelectPane/SetZoom on the viewer PTY bridge, with extensive unit/integration tests.
Control-plane relay
services/control-plane/src/routes/terminal.ts, tests/terminalRoute.test.ts
Relays browser navigate messages to the agent as terminal.navigate after an operator permission check.
Dashboard send path and controller wiring
apps/dashboard/src/components/terminal/protocol.ts, types.ts, TerminalView.tsx, apps/dashboard/src/hooks/useTerminalConnection.ts, apps/dashboard/src/hooks/tmuxNavigation.ts, *.test.ts
Adds sendTerminalNavigation, a navigate method on TerminalController/useTerminalConnection, and helpers getTmuxViewerSessionKey/getTmuxViewerNavigation.
Host store attachment retargeting
apps/dashboard/src/components/terminal/terminalHostStore.ts, PersistentTerminalHost.tsx, *.test.ts
Adds attachmentDescriptor and navigateWithinAttachment to preserve the live terminal instance during same-session navigation.
Tmux workspace controls wiring
apps/dashboard/src/components/tmux/TmuxActionSheet.tsx, TmuxPaneControls.tsx, TmuxWindowStrip.tsx, TmuxTerminalWorkspace.tsx
Wires onSelectSession through pane/window controls and action sheet, and fixes the letterbox attachment key separator.
Mobile Focus toggle and zoom state machine
apps/dashboard/src/components/tmux/mobileFocus.ts, TmuxMobileShell.tsx, apps/dashboard/src/stores/settings.ts, *.test.ts
Adds getMobileFocusNavigation, autoFocusPane setting, and a mobile Focus toggle that auto-zooms/unzooms based on topology and visibility.
Journey tests and docs
tests/journeys/*, tasks/*
Updates journey specs and mocks to assert terminal.navigate messages and adds an FW6-FOCUS mobile Focus journey, task brief, handoff doc, and log entries.
Legacy settings DB grant
migrations/039_grant_legacy_settings_access.sql
Grants agent_console role access to user_settings_legacy_subjects.

Estimated code review effort: 4 (Complex) | ~75 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Dashboard
  participant ControlPlane
  participant Agentd
  participant TerminalManager
  participant tmux

  Dashboard->>ControlPlane: navigate {op, window_index/pane_id/on}
  ControlPlane->>ControlPlane: check operator permission
  ControlPlane->>Agentd: terminal.navigate {channel_id, op, ...}
  Agentd->>TerminalManager: Navigate(channelID, navigation)
  TerminalManager->>TerminalManager: unzoomViewerLocked(viewer)
  TerminalManager->>tmux: SelectWindow/SelectPane/SetZoom
  tmux-->>TerminalManager: result
  TerminalManager-->>Agentd: error/nil
  Agentd-->>ControlPlane: (ack via idle timeout reset)
Loading
sequenceDiagram
  participant TmuxMobileShell
  participant SettingsStore
  participant TerminalController
  participant TerminalHostStore

  TmuxMobileShell->>SettingsStore: read autoFocusPane
  TmuxMobileShell->>TmuxMobileShell: getMobileFocusNavigation(topology, focusRequested)
  TmuxMobileShell->>TerminalController: navigate({op:'zoom', on})
  TerminalController->>TerminalHostStore: navigateWithinAttachment(...)
  TerminalHostStore-->>TerminalController: true/false
  TerminalController-->>TmuxMobileShell: sent(boolean)
Loading

Possibly related PRs

  • cvsloane/agent-commander#90: Updates the same journey/control-plane mocks to record terminal.navigate op payloads (select_window/select_pane), directly overlapping the test infrastructure changes here.
  • cvsloane/agent-commander#92: Overlaps with the TmuxTerminalWorkspace letterbox-dimension freeze/attachment-key change to prevent attach/detach remount loops.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly captures the two main changes: mobile Focus mode and instant in-session window switching.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/frontend-command-center

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@cvsloane
cvsloane merged commit 7b21b26 into main Jul 21, 2026
4 of 5 checks passed

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
tests/journeys/controlPlaneMock.ts (1)

413-421: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Clean up closed WebSockets from the topology broadcast set.

To prevent potential errors when broadcasting topology updates to stale connections, consider removing the socket from the topologySockets set when it closes.

♻️ Proposed refactor
   await page.routeWebSocket(/\/v1\/ui\/stream\?ticket=/, (socket) => {
     topologySockets.add(socket);
+    socket.onClose(() => topologySockets.delete(socket));
     let topologySent = false;
     socket.onMessage(() => {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/journeys/controlPlaneMock.ts` around lines 413 - 421, Update the
WebSocket setup in the topology route handler to remove each socket from
topologySockets when it closes. Keep the existing onMessage behavior unchanged
and attach the cleanup to the socket’s close lifecycle event.
tests/journeys/command-center.journey.spec.ts (1)

96-96: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider using a synchronous assertion for unchanged values.

Using expect.poll to assert that a value has not changed will pass instantly, as the initial condition is already met, which bypasses the intent of polling. Since the test already awaits the navigate message and the visibility of the new terminal, a standard synchronous assertion is sufficient and clearer.

♻️ Proposed refactor
-    await expect.poll(() => recorder.terminalWebSocketUrls.length).toBe(terminalWebSocketCount);
+    expect(recorder.terminalWebSocketUrls).toHaveLength(terminalWebSocketCount);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/journeys/command-center.journey.spec.ts` at line 96, Replace the
expect.poll assertion on recorder.terminalWebSocketUrls.length with a
synchronous expect assertion, preserving the terminalWebSocketCount comparison
after the navigate message and new-terminal visibility checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@agents/agentd/cmd/agentd/main.go`:
- Around line 5485-5521: Update handleTerminalNavigate so the validated
a.terminalManager.Navigate call is dispatched in a goroutine, keeping the
synchronous tmux operation out of the WebSocket read loop. Preserve the existing
channel ID, navigation payload, and error logging within the asynchronous
operation, similar to handleTerminalAttach.

In `@agents/agentd/internal/tmux/terminal.go`:
- Around line 749-811: Refactor TerminalManager.Navigate and the zoom-cleanup
flow so synchronous tmux calls never run while m.mu is held. Capture the
required viewer/bridge state, release the lock before SelectWindow, SelectPane,
or SetZoom, and briefly reacquire it only to update zoomApplied safely; adjust
unzoomViewerLocked and callers such as Sweep, MarkChannelsStale, Detach, and
Close to clear state under lock and defer collected SetZoom(false) calls until
after unlocking.

In `@agents/agentd/internal/tmux/viewer_pty.go`:
- Around line 329-356: Update selectWindowLocked so b.windowTarget is assigned
to target immediately after select-window succeeds, before any letterbox pinning
or resizing steps. Preserve the existing rollback attempts and error returns for
set-option and resize-window failures while ensuring subsequent calls observe
the actual selected window.

---

Nitpick comments:
In `@tests/journeys/command-center.journey.spec.ts`:
- Line 96: Replace the expect.poll assertion on
recorder.terminalWebSocketUrls.length with a synchronous expect assertion,
preserving the terminalWebSocketCount comparison after the navigate message and
new-terminal visibility checks.

In `@tests/journeys/controlPlaneMock.ts`:
- Around line 413-421: Update the WebSocket setup in the topology route handler
to remove each socket from topologySockets when it closes. Keep the existing
onMessage behavior unchanged and attach the cleanup to the socket’s close
lifecycle event.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 713f3521-b3fb-468e-9b45-c51f438ab73d

📥 Commits

Reviewing files that changed from the base of the PR and between fbac2dd and cc6a32d.

📒 Files selected for processing (42)
  • agents/agentd/cmd/agentd/main.go
  • agents/agentd/cmd/agentd/main_terminal_test.go
  • agents/agentd/internal/protocol/messages.go
  • agents/agentd/internal/protocol/terminal.go
  • agents/agentd/internal/tmux/pty_bridge_test.go
  • agents/agentd/internal/tmux/terminal.go
  • agents/agentd/internal/tmux/viewer_pty.go
  • agents/agentd/internal/ws/protocol_fixtures_test.go
  • apps/dashboard/src/components/TerminalView.tsx
  • apps/dashboard/src/components/terminal/PersistentTerminalHost.tsx
  • apps/dashboard/src/components/terminal/protocol.test.ts
  • apps/dashboard/src/components/terminal/protocol.ts
  • apps/dashboard/src/components/terminal/terminalHostStore.test.ts
  • apps/dashboard/src/components/terminal/terminalHostStore.ts
  • apps/dashboard/src/components/terminal/types.ts
  • apps/dashboard/src/components/tmux/TmuxActionSheet.tsx
  • apps/dashboard/src/components/tmux/TmuxMobileShell.tsx
  • apps/dashboard/src/components/tmux/TmuxPaneControls.tsx
  • apps/dashboard/src/components/tmux/TmuxTerminalWorkspace.tsx
  • apps/dashboard/src/components/tmux/TmuxWindowStrip.tsx
  • apps/dashboard/src/components/tmux/mobileFocus.test.ts
  • apps/dashboard/src/components/tmux/mobileFocus.ts
  • apps/dashboard/src/hooks/tmuxNavigation.test.ts
  • apps/dashboard/src/hooks/tmuxNavigation.ts
  • apps/dashboard/src/hooks/useTerminalConnection.ts
  • apps/dashboard/src/hooks/useTmuxRosterData.ts
  • apps/dashboard/src/stores/settings.test.ts
  • apps/dashboard/src/stores/settings.ts
  • migrations/039_grant_legacy_settings_access.sql
  • packages/ac-schema/src/message.ts
  • packages/ac-schema/src/terminal.ts
  • packages/ac-schema/tests/protocol-fixtures.test.ts
  • packages/ac-schema/tests/terminal.test.ts
  • services/control-plane/src/routes/terminal.ts
  • services/control-plane/tests/terminalRoute.test.ts
  • tasks/2026-07-21-fw6-focus-brief.md
  • tasks/frontend-ux-handoffs/fw6-focus.md
  • tasks/frontend-ux-log.md
  • tests/fixtures/protocol/terminal-navigate.json
  • tests/journeys/command-center.journey.spec.ts
  • tests/journeys/controlPlaneMock.ts
  • tests/journeys/fw6-focus.journey.spec.ts

Comment on lines +5485 to +5521
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)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Run terminal navigation in a goroutine to prevent stalling the WebSocket read loop.

a.terminalManager.Navigate executes synchronous tmux shell-outs (blocking I/O). Calling it directly inside handleTerminalNavigate blocks the agent's sequential readPump, which delays the processing of all other incoming protocol messages.

Please dispatch the navigation call in a goroutine (similar to handleTerminalAttach).

⚡ Proposed fix
-	if err := a.terminalManager.Navigate(req.ChannelID, navigation); err != nil {
-		log.Printf("Failed to navigate terminal: %v", err)
-	}
+	go func() {
+		if err := a.terminalManager.Navigate(req.ChannelID, navigation); err != nil {
+			log.Printf("Failed to navigate terminal: %v", err)
+		}
+	}()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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) 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
}
go func() {
if err := a.terminalManager.Navigate(req.ChannelID, navigation); err != nil {
log.Printf("Failed to navigate terminal: %v", err)
}
}()
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agents/agentd/cmd/agentd/main.go` around lines 5485 - 5521, Update
handleTerminalNavigate so the validated a.terminalManager.Navigate call is
dispatched in a goroutine, keeping the synchronous tmux operation out of the
WebSocket read loop. Preserve the existing channel ID, navigation payload, and
error logging within the asynchronous operation, similar to
handleTerminalAttach.

Comment on lines +749 to +811
// 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.Lock()
defer m.mu.Unlock()
_, exists := m.channelToPane[channelID]
viewer := m.viewerByChannel[channelID]
var bridge *viewerPTYBridge
if viewer != nil {
bridge = viewer.bridge
}
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")
}
if err := m.unzoomViewerLocked(viewer, "window switch"); err != nil {
return err
}
return bridge.SelectWindow(navigation.WindowIndex)
case NavigateSelectPane:
if strings.TrimSpace(navigation.PaneID) == "" {
return fmt.Errorf("pane id is required")
}
if err := m.unzoomViewerLocked(viewer, "pane switch"); err != nil {
return err
}
return bridge.SelectPane(navigation.PaneID)
case NavigateZoom:
if err := bridge.SetZoom(navigation.On); err != nil {
return err
}
viewer.zoomApplied = navigation.On
return nil
default:
return fmt.Errorf("unsupported terminal navigation op %q", navigation.Op)
}
}

func (m *TerminalManager) unzoomViewerLocked(viewer *terminalViewer, reason string) error {
if viewer == nil || !viewer.zoomApplied || viewer.bridge == nil {
return nil
}
if err := viewer.bridge.SetZoom(false); err != nil {
return fmt.Errorf("unzoom viewer during %s: %w", reason, err)
}
viewer.zoomApplied = false
return nil
}

func (m *TerminalManager) cleanupViewerZoomLocked(viewer *terminalViewer, reason string) {
if err := m.unzoomViewerLocked(viewer, reason); err != nil {
log.Printf("Failed to %v", err)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Avoid holding the global TerminalManager lock during synchronous tmux I/O.

Navigate, unzoomViewerLocked, and cleanupViewerZoomLocked execute blocking shell-outs (e.g., bridge.SelectWindow, bridge.SetZoom) via the tmux runner. Because m.mu.Lock() is held here, and cleanupViewerZoomLocked is actively called by Sweep, MarkChannelsStale, Detach, and Close with the lock already held, this design stalls all terminal operations across the agent.

Please defer the blocking tmux commands until after m.mu is released:

  • For Navigate: look up the bridge and state, explicitly release the lock, and then invoke the navigation command. (You may need to re-acquire the lock briefly for NavigateZoom to update viewer.zoomApplied).
  • For zoom cleanup: clear viewer.zoomApplied inside the lock, but collect the affected bridge references to invoke SetZoom(false) after the lock is released by the callers.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agents/agentd/internal/tmux/terminal.go` around lines 749 - 811, Refactor
TerminalManager.Navigate and the zoom-cleanup flow so synchronous tmux calls
never run while m.mu is held. Capture the required viewer/bridge state, release
the lock before SelectWindow, SelectPane, or SetZoom, and briefly reacquire it
only to update zoomApplied safely; adjust unzoomViewerLocked and callers such as
Sweep, MarkChannelsStale, Detach, and Close to clear state under lock and defer
collected SetZoom(false) calls until after unlocking.

Comment on lines +329 to +356
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
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

b.windowTarget goes stale if the letterbox pin/resize steps fail after select-window already succeeded.

select-window mutates the real tmux active window immediately, but b.windowTarget is only updated at the very end of the function. If the subsequent set-option ... manual or resize-window call fails, the function returns early: the previous window's pinning was already released to "latest" and is never restored, yet b.windowTarget still reports the old previous value. Future SelectWindow/SelectPane calls then compute previous from this stale value, causing further pin/release mismanagement (leaked un-pinned windows, no-op releases against a window that's no longer current).

🐛 Proposed fix: update windowTarget right after select-window succeeds
 	if err := b.runner.Run("select-window", "-t", target); err != nil {
 		return fmt.Errorf("select viewer window: %w", err)
 	}
+	b.windowTarget = target
 	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
 }

None of the current tests exercise a failing Run() mid-pin, which is why this wasn't caught.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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) 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)
}
b.windowTarget = target
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)
}
}
return nil
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agents/agentd/internal/tmux/viewer_pty.go` around lines 329 - 356, Update
selectWindowLocked so b.windowTarget is assigned to target immediately after
select-window succeeds, before any letterbox pinning or resizing steps. Preserve
the existing rollback attempts and error returns for set-option and
resize-window failures while ensuring subsequent calls observe the actual
selected window.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant