Repository navigation
fix(focus): keep keyboard focus in the agent tab after chrome clicks - #132
Merged
Merged
Conversation
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
getKeybindingContextstopped 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.tsowns 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 markeddata-keep-keyboard-focuswhile 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.restoreAgentTabFocusAfterChromeClick(sidebar chrome) andrestoreAgentTabFocusAfterPanelBackgroundClick(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.detail, so Enter/Space on a focused control — which synthesises adetail-0 click — keeps its focus.onClickCaptureisrestoreAgentTabFocusAfterChromeClick— 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.activateWorktreeFromSidebarnow 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.hooks/use-agent-tab-focus-overlay-close.ts, mounted once inApp): 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.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.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.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:
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:
tabIndexfrom the sidebar listbox and rely on roving focus. Cleaner in principle, but thattabIndexis load-bearing forsidebar.focusWorktreeList,aria-activedescendantand the existing focus guards — it would rework keyboard navigation, ARIA wiring and focus guards in one change.preventDefault()the sidebar'spointerdownto 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.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.<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.focusTerminalTabSurfaceinstead 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.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'sonClickis 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 movesdocument.activeElementfrom 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):
worktree-jump-sleep-focus.spec.ts.workspace-activation-terminal-focus.test.ts, which covers the deferral's stop-waiting rules.The panel body's
onClickis covered by a render test ofRightSidebarPanelContent, 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 testas a whole does not complete in this environment — the stall is recorded inLOCAL-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 fromhooks/ipc-events/ephemeral-vm-reclaim-ipc-bridge.tsthat reproduce with this change stashed (checked file by file). Earlier runs under heavier machine load produced timeouts inlib/palette-match/palette-match-performance.test.ts(a perf budget) andcomponents/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 testwas attempted before the stall; its non-renderer failures were triaged:main/runtime/terminal-tail-redraw-wall-time.test.tsis a wall-time benchmark that passes in isolation, andmain/cli/packaged-cli-assets.test.tsis the documented pre-existingcd -P/var→/private/varfailure.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) plusworktree-jump-sleep-focus,golden-worktree-create-switch,file-explorer-ime-enterandterminal-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:5077e4570a: no must-fix, one should-fix — the new wiring had no test that failed if removed — fixed inf75754e789(handler tests, sidebar-chrome e2e).f75754e789: no must-fix, one should-fix — the panel body'sonClickwas still unguarded — fixed infda3dede9f(panel render test, e2e route).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 in244ac0868d(route paths plus contract assertions for them).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.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, viaclaude/opus), high reasoning, clean onaf206b68cb: 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
Notes
metaKey/ctrlKeyshortcut 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 isMouseEvent.detail, the same idiomcomponents/right-sidebar/local-port-row.tsxalready uses.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.closest/querySelectorAllcalls; the deferral keeps its existing per-frame retry and cancels on the first success.