Skip to content

fix(focus): keep keyboard focus in the agent tab after chrome clicks - #132

Merged
nplez1 merged 9 commits into
nplez1/mainfrom
nplez1/Keyboard-Focus-Fix
Oct 18, 2026
Merged

nplez1 merged 9 commits into
nplez1/mainfrom
nplez1/Keyboard-Focus-Fix

Conversation

@nplez1

@nplez1 nplez1 commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

ELI5

Orca is built for talking to an agent, so the keyboard should stay with the agent. Clicking things that do not need typing — a workspace in the sidebar, a panel tab on the right, a group header — used to take the keyboard away from it. The caret disappeared from the terminal and the next keystroke went to whatever chrome had just been clicked; shortcuts quietly changed meaning too, because Orca decides "which shortcuts apply" by looking at where focus is. Now a pointer click on that chrome hands the keyboard straight back to the agent you are watching. Only things that need typing, dialogs, another agent window (the floating workspace), and the keyboard-driven sidebar keep it — and anything you reach with the keyboard keeps the focus you navigated to.

What Changed

Before: clicking a workspace card in the sidebar activated the workspace but left keyboard focus on the sidebar's listbox; clicking a right-sidebar activity tab (Checks, Source Control, Files) left focus on that button; clicking a panel's empty background dropped focus to the page body; clicking a repo group header in the sidebar left focus on the header. In each case the terminal lost its caret and getKeybindingContext stopped reporting 'terminal'.

After: each of those pointer clicks puts keyboard focus back into the displayed agent tab — the active leaf of a split, or the chat composer when the tab shows a chat. A workspace whose terminal is not mounted yet (a sleeping workspace publishes its tab after the click) is covered by the existing deferral machinery, so focus lands when the terminal appears instead of being lost. And when a menu, dialog or popover closes, the caret comes back too: a pointer selection, a click outside, or Escape hands it to the agent tab instead of leaving it on the button that opened the popup. Tab/Enter/Space navigation keeps its own focus, so the sidebar and every popup stay operable without a mouse.

The mechanism is one policy module instead of a seventh special case per call site:

  • src/renderer/src/lib/agent-tab-focus-policy.ts owns the whole question.
    • isAgentTabFocusClaimed() is the single definition of "something else owns the keyboard": an editable, any terminal (the floating workspace is another agent context), a visible dialog/menu, the keyboard-navigating sidebar, or chrome marked data-keep-keyboard-focus while that chrome is on screen.
    • focusAgentTabSurface() restores through the mounted-tab registry. It realigns the manager to the stored split first and then decides chat-versus-terminal on the pane it aimed at, because a split can hold a chat in one leaf and a terminal in another; a leaf request only counts once focus actually landed, and a chat request only counts once a composer took it, so a caller that waits keeps waiting instead of stopping early. It refreshes the xterm IME input context on macOS.
    • Two React handlers carry the wiring: restoreAgentTabFocusAfterChromeClick (sidebar chrome) and restoreAgentTabFocusAfterPanelBackgroundClick (panel body). Both ignore a click inside a menu or dialog their surface portals out — React bubbles those to the owner, but the menu is not the chrome. The sidebar handler restores for a control inside a card but leaves a plain card click to the deferral path.
    • Two deferred primitives do the work one animation frame after the gesture, so a click that opens a dialog or autofocuses a field is judged after those effects commit. Both take the click's detail, so Enter/Space on a focused control — which synthesises a detail-0 click — keeps its focus.
  • Sidebar: the root's onClickCapture is restoreAgentTabFocusAfterChromeClick — capture, because a control inside a card stops the click from bubbling, and its focus must come back too. A plain click on a card is the card's own activation and uses the existing deferral helper instead (use-worktree-card-activation-actions.ts → queueWorkspaceActivationTerminalFocus), because its terminal may mount later; a card click that activates nothing (multi-select, a card being deleted) restores through the policy like any other chrome click.
  • Activation result: activateWorktreeFromSidebar now returns its activation result and no longer awaits the ephemeral-VM wake, so the sidebar's queued focus gets the result in the same gesture.
  • Overlay close (hooks/use-agent-tab-focus-overlay-close.ts, mounted once in App): a gesture records the overlays that were on screen when it happened, and when one of those leaves the DOM the agent tab takes the caret back — unless the gesture was Enter/Space on a control, which is the keyboard opening or activating what it opened. A pointer selection, a click outside, Escape, and Enter typed into the popup's own text field (a picker, a filter, a rename box) all return; a space typed into that field is just text; a close with no gesture behind it is left alone. A click outside that landed on something which took its own focus (a panel row) keeps that focus, matching the panel rule below.
  • Right sidebar: selectActivityTab (the funnel for both activity-bar layouts) and the panel content root restore focus. Picking a tab from the overflow menu restores through the overlay-close rule, not through the tab strip.
  • The deferral helper (workspace-activation-terminal-focus.ts) now focuses through the policy, names the store's active leaf, and uses the same claim definition when deciding to stop waiting — so Cmd+J, workspace creation and sidebar cards all reach chat-covered tabs and IME refreshes through one path.
  • Opt-out marker: the floating workspace panel is marked data-keep-keyboard-focus, declaring that it is an agent context of its own. A marked element that is no longer on screen (aria-hidden) stops claiming, so a closed floating panel cannot strand focus.

Two behaviours, deliberately:

  • Navigation chrome (the left sidebar's chrome, the activity tab strip, and anything its popups close back to) restores focus after a pointer gesture, because it has no use for the caret.
  • A panel body only restores focus when the click actually dropped focus to the page, so a click on a focusable row keeps the keyboard focus that row took. The Explorer's rows are buttons and its arrow-key navigation depends on that focus; this is what stops the change from breaking it.

Two cases keep the focus a keyboard user navigated to, by design: Tab/Enter/Space on a sidebar control, and Enter/Space on a menu item or dialog action. Everything else hands the caret back — including Enter typed into a popup's text field, which submits or picks a row. An overlay closed with no gesture at all (a save that finishes on its own) is not treated as a gesture and leaves focus where it is.

Audited and deliberately unchanged: the task page replaces the agent surface (activeView === 'tasks'), so its rows keep their own focus; the policy declines when no agent tab is displayed. The AiVault search request, the Source Control filter, comment composers, inline rename and every dialog are editables or overlays and claim focus exactly as before.

Why

Focus is the shortcut context in this app, so a click on chrome that has no use for typed input silently changes what the next keystroke means. The issue reproduced that in two places and asked for one policy rather than a third behaviour, so the claim rules live in one module and every call site asks it.

Alternatives considered and rejected:

  • Remove tabIndex from the sidebar listbox and rely on roving focus. Cleaner in principle, but that tabIndex is load-bearing for sidebar.focusWorktreeList, aria-activedescendant and the existing focus guards — it would rework keyboard navigation, ARIA wiring and focus guards in one change.
  • preventDefault() the sidebar's pointerdown to stop the browser focusing the listbox. It cannot distinguish a click from a drag-to-select, which is how people copy a branch name out of the sidebar.
  • Restore focus on every terminal focusout. It fights legitimate focus moves (dialogs, composers, inline rename) and produces a tug-of-war; claiming has to be explicit, which is what the predicate is for.
  • Set focus to <body> when no agent tab can take focus. That is the bug behind upstream [Bug]: Closing the Agents drawer drops keyboard focus to <body> instead of returning it to the opener stablyai/orca#25570; when nothing can take focus, focus is left alone.
  • Reuse focusTerminalTabSurface instead of the mounted-tab registry. It is DOM-selector based and defers two frames with no return value, and the deferral helper needs a synchronous answer about whether focus landed.
  • Prevent Radix's close-autofocus to claim the portaled-menu case. The repo does that elsewhere, but it changes where a menu returns focus for every menu on those surfaces; it is a follow-up of its own, not part of this policy.

Linked Issue

Fixes #59

Visual Proof

There is no visual delta on purpose — the change is about where the caret and the shortcut context are. Proof is DOM-observable, in both layers.

Discriminating — each was checked to fail with the relevant change reverted (the e2e ones by rebuilding from a tree without the fix, the unit ones by deleting the binding they cover):

  • tests/e2e/agent-tab-focus-retention.spec.ts — switching Checks → Source Control → Explorer keeps the terminal focused, in both activity-bar layouts (top and side).
  • tests/e2e/agent-tab-focus-retention.spec.ts — clicking a repo group header, and a control inside a workspace card (its unread toggle), keeps the terminal focused (fails when the root's handler is removed, and fails again if it is moved back to the bubbling phase).
  • tests/e2e/agent-tab-focus-retention.spec.ts — choosing "Copy Path" from a card's menu, and dismissing that menu with Escape, both return the caret to the agent tab (fails with the overlay-close hook removed).
  • use-agent-tab-focus-overlay-close.test.tsx — the close-intent rules: pointer selection, click outside, Escape and Enter-in-a-text-field restore; Enter/Space on a control, a space typed into a field, an IME Enter, an overlay the gesture never saw, a removal with no gesture and a non-overlay removal do not.
  • right-sidebar-panel-content.click.test.tsx — a click on the panel body reaches the policy (fails when the panel's onClick is removed).
  • agent-tab-focus-policy.test.ts — the policy itself: each claim condition, the split chat/terminal cases, the leaf-then-fallback restore, the overlay-swallowed leaf, the missing composer, both React handlers (portal guard, card exclusion, detail-0 gate), both deferred primitives.
  • config/scripts/pr-e2e-route-contracts.test.mjs — the route that keeps the focus spec running in CI whenever the policy, the sidebar root, or either activity-bar layout changes, and that does not fire on the policy's own unit test.
  • use-worktree-card-activation-actions.focus.test.tsx — a card click moves document.activeElement from the sidebar listbox to the terminal helper.
  • right-sidebar-tab-focus.test.tsx — a panel-tab pointer click returns focus to the helper, and a keyboard-activated tab keeps it.

Guards only (they pass with and without the change, and exist to catch regressions):

  • The card e2e: a mounted terminal re-grabs focus on its own in this build, so it asserts the end state rather than the bug; the sleeping-workspace case is worktree-jump-sleep-focus.spec.ts.
  • The AiVault e2e, which asserts a "needs typed input" contract that must not regress and never goes through changed code.
  • workspace-activation-terminal-focus.test.ts, which covers the deferral's stop-waiting rules.

The panel body's onClick is covered by a render test of RightSidebarPanelContent, not by an e2e: clicking a panel's empty background is not something an e2e can target reliably, so the wiring is asserted where it is bound.

Testing

pnpm test as a whole does not complete in this environment — the stall is recorded in LOCAL-PATCHES.md (the runner stops with no summary; it predates this change and is tracked as its own work). So gate 1's full run could not be produced here. What was produced, on the committed revision:

  • pnpm tc — exit 0 (node, web and cli projects).

  • pnpm lint — exit 0, every step including repo-wide oxlint and the ratchets.

  • pnpm run check:code-quality:changed — 0 findings.

  • pnpm test src/renderer/src — every changed file lives in the renderer project: 42,998 passing, 0 failing (4,880 files, 4 skipped), 2 expected failures, plus 27 unhandled rejections from hooks/ipc-events/ephemeral-vm-reclaim-ipc-bridge.ts that reproduce with this change stashed (checked file by file). Earlier runs under heavier machine load produced timeouts in lib/palette-match/palette-match-performance.test.ts (a perf budget) and components/terminal-pane/remote-snapshot-alt-screen-host-chain.test.ts (30s limits); both pass 12/12 in isolation in 6.9s, and neither is touched by this change.

  • A full pnpm test was attempted before the stall; its non-renderer failures were triaged: main/runtime/terminal-tail-redraw-wall-time.test.ts is a wall-time benchmark that passes in isolation, and main/cli/packaged-cli-assets.test.ts is the documented pre-existing cd -P /var → /private/var failure.

  • Playwright Electron (headless renderer): the six tests in agent-tab-focus-retention.spec.ts (both activity-bar layouts, sidebar chrome and a card control, menu close, the keyboard case) plus worktree-jump-sleep-focus, golden-worktree-create-switch, file-explorer-ime-enter and terminal-pane-title-focus-handoff — 21 tests green across the two runs.

  • Manual: macOS, local worktrees and a folder workspace — click a workspace card, a group header, each right-sidebar tab, a panel background, then type immediately.

  • Not exercised here: Windows, Linux, SSH-host workspaces, and the mobile/paired client. The policy resolves its target from the store and focuses through the mounted-tab registry, so it makes no platform assumptions, adds no shortcut handling, and changes no RPC params or published content.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Implemented with an AI coding agent (Claude) under Opus 5.5 review.

Review

Seven review passes by Opus 5.5 at high reasoning (claude/opus), each against the full diff of the then-current revision:

  1. First revision: two must-fix defects — keyboard activation lost focus, and the chat-versus-terminal decision used the manager's stale active pane. Both fixed, with tests.
  2. Second: no must-fix; four should-fix items (portaled clicks reading as chrome, two weak tests, PR-body claims) — all fixed.
  3. 5077e4570a: no must-fix, one should-fix — the new wiring had no test that failed if removed — fixed in f75754e789 (handler tests, sidebar-chrome e2e).
  4. f75754e789: no must-fix, one should-fix — the panel body's onClick was still unguarded — fixed in fda3dede9f (panel render test, e2e route).
  5. fda3dede9f: no must-fix, one should-fix — the E2E route omitted the top activity bar, which is the file the spec's panel-switch test actually clicks — fixed in 244ac0868d (route paths plus contract assertions for them).
  6. 244ac0868d: no must-fix, one should-fix — the route comment claimed both activity-bar layouts were covered while only the top one was — fixed by adding the side layout to the panel-switch test, so the claim is now true.
  7. 70ad211d18: clean on the behaviour as it then stood.

The popup-close rule (a pointer selection, a click outside, Escape, or Enter typed into the popup's own field returns the caret; Tab/Enter/Space navigation keeps it) was added afterwards on the fork owner's direction, together with the capture-phase sidebar listener and the card-control case. Its own review rounds tightened the intent model — Enter typed into a popup field counts as a selection, not navigation; the intent is bound to the overlays the gesture saw rather than a stopwatch; a dismissing click that took its own focus keeps it; and Tab disarms so a caret that moved on is never pulled back.

Verdict — Reviewed by Opus 5.5 (claude-opus-5-5, via claude/opus), high reasoning, clean on af206b68cb: no must-fix, no should-fix, no open nitpicks; ship-ready.

Gate 1 (a completed full pnpm test) remains unmet in this environment, as stated above.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Cross-platform: no metaKey/ctrlKey shortcut is added, and the policy adds no keyboard affordance. Platform-conditional code is limited to the existing macOS IME refresh helper; the pointer-versus-keyboard test is MouseEvent.detail, the same idiom components/right-sidebar/local-port-row.tsx already uses.
  • SSH / folder workspaces: the target is resolved from useAppStore.getState() at call time (never captured in render scope), so a folder workspace or a paired/SSH host resolves like a local worktree; the focus itself goes through the mounted-tab registry, which is host-agnostic.
  • Behaviour change worth a reviewer's eye: the deferral helper now names the active leaf (a split restores to the pane the user was in), reaches chat-covered tabs through the composer, and only reports success when focus landed — that last one fixed a regression the e2e caught, where a wake behind the closing palette stopped retrying.
  • Performance: the deferred decision runs one animation frame after a click and does a handful of closest/querySelectorAll calls; the deferral keeps its existing per-frame retry and cancels on the first success.

Focus position is the shortcut context: getKeybindingContext reports
'terminal' only while the xterm helper owns focus. Clicking a workspace
card or a right-sidebar activity tab moved focus onto chrome and silently
changed what the next keystroke meant.

One policy module now owns the question (lib/agent-tab-focus-policy.ts):
is something else claiming the keyboard (an editable, any terminal, a
live overlay, the keyboard-navigating sidebar, data-keep-keyboard-focus),
and if not, restore the displayed agent tab through the mounted-tab
registry — the aimed split leaf, or the chat composer when a chat covers
it. Gestures decide one frame after they commit, and a detail-0 click
(Enter/Space on a focusable control) is not a pointer gesture.

Wired into the sidebar root, the right-sidebar activity tabs and the
panel background. Workspace cards use the existing deferral helper
instead, because a sleeping workspace publishes its tab after the click;
that helper now focuses through the policy, names the active leaf, and
applies the same claim rule when deciding to stop waiting.

Refs #59
The sidebar's chrome click and the panel body's background click were only
reachable through inline JSX handlers, so removing either left the suite
green. Both handlers now live in the policy module, where the portal guard
(a menu the surface owns is not a click on its chrome), the workspace-card
exclusion and the detail-0 keyboard gate are tested directly.

Adds an e2e case for the wiring itself: clicking a repo section header in
the sidebar collapses the group and hands focus back to the agent tab,
which fails when the root `onClick` is removed.

Refs #59
Adds the render test that fails when the panel content's `onClick` is
removed, names a child element in the card click test so the real
`closest()` lookup runs, and routes the focus policy, its two roots and
the panel body to `agent-tab-focus-retention.spec.ts` so the bare JSX
bindings stay guarded in CI after this PR.

Refs #59
The panel-switch e2e clicks the top activity bar (the default position), so
the route has to name it and the button component that forwards the event;
without them, changing that binding to restore focus on a keyboard
activation would pass every check. The contract test also asserts the
policy's own unit test does not trigger the lane.

Refs #59
The activity bar docks either at the top of the panel or at its side, and
only the top layout was asserted — so the route comment claiming both were
covered was wrong. The panel-switch test now flips the dock to `side` and
clicks a side-layout tab, which makes the claim true rather than weakening
it.

Refs #59
A menu, dialog or popover takes the caret while it is open and then hands it
back to whatever opened it — the sidebar button, the card menu trigger, the
panel row — which is the same stranding a chrome click causes, only later.

`useAgentTabFocusOverlayClose` watches an overlay leave the DOM and restores
the agent tab when the closing gesture was a pointer selection, a click
outside, or Escape. Enter and Space are how the keyboard opens or activates
what it opened, so those keep the focus Radix returns to its trigger; a close
with no gesture behind it (a save finishing on its own) is left alone.

Also here: the sidebar root now listens in the capture phase, because a
control inside a card stops the click from bubbling and its focus has to come
back too; a card click that activates nothing (multi-select, deleting)
restores like any other chrome click; and the deferred primitive is renamed
`restoreAgentTabFocusAfterGesture` since it no longer serves chrome alone.

Refs #59
Enter typed into a popup's own text field submits it or picks the highlighted
row — the worktree parent picker, a cmdk list, a rename box — so it is a
selection, not navigation, and the caret has to come back to the agent tab.
Space typed into that field is just text and records nothing, and an Enter
the IME owns is ignored.

The intent is now bound to the overlays that were on screen when the gesture
happened rather than to a stopwatch, so a slow save that closes its dialog
minutes later still restores and an unrelated overlay cannot inherit the
intent. A dismissing click that landed on something which took its own focus
keeps it, and the observer is only connected while an intent is armed.

Refs #59
The outside-click rule asked whether the pointer target contained the focus,
which is backwards: the pointerdown target is the innermost element and the
caret lands on a focusable ancestor. It also ran when the overlay left the
DOM, before a synchronously closed popup had let the mousedown move focus, so
a click on a panel row still lost the caret to the agent tab.

The decision now runs in the queued task that already exists to beat Radix's
trigger refocus, and containment runs from the focused element down to the
target. Tab disarms (navigation moved the caret somewhere the user chose), and
Space on a control disarms like Enter does.

Refs #59
The retry those comments described is gone: there is one deferred check, in
the queued task that also beats Radix's trigger refocus.

Refs #59
@nplez1
nplez1 merged commit 12545ad into nplez1/main Oct 18, 2026
@nplez1
nplez1 deleted the nplez1/Keyboard-Focus-Fix branch October 24, 2026 03:23
@nplez1 nplez1 mentioned this pull request Nov 24, 2026
@lab-agent-np lab-agent-np Bot mentioned this pull request Nov 24, 2026
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.

[Feature]: Keep keyboard focus in the selected agent tab — workspace and right-panel interactions should not take focus

1 participant