Skip to content

fix(browser-pane): focus the page when a browser tab is activated - #20892

Closed
mmarabel wants to merge 5 commits into
stablyai:mainfrom
mmarabel:mmarabel/20533-browser-tab-focus
Closed

mmarabel wants to merge 5 commits into
stablyai:mainfrom
mmarabel:mmarabel/20533-browser-tab-focus

Conversation

@mmarabel

Copy link
Copy Markdown
Contributor

ELI5

Switching tabs with the mouse or the keyboard handed the keyboard to a terminal tab, but not to a browser tab. Clicking a browser tab switched what you were looking at, yet your typing still went to whatever had focus before — usually the terminal you came from — so the page only became usable after clicking inside it. Activating a browser tab now hands it the keyboard the same way activating a terminal tab does.

What Changed

Browser tab activation now requests page focus on all three activation routes:

  • src/renderer/src/lib/browser-workspace-tab-activation.ts — new requestBrowserWorkspaceTabPageFocus(worktreeId, workspaceId). It resolves the workspace tab's current activePageId from the store and issues the existing queued request requestBrowserFocus({ pageId, target: 'webview' }) from components/browser-pane/host-guest/browser-focus.ts.
  • src/renderer/src/components/tab-group/useTabGroupActivationCommands.ts — activateBrowser (tab-strip click) calls it after activating.
  • src/renderer/src/lib/tab-number-shortcuts.ts — activateTabNumberShortcut browser branch (Cmd/Ctrl+number) calls it.
  • src/renderer/src/hooks/ipc-tab-switch.ts — activateCyclableTab browser branch (Ctrl+Tab cycling, Ctrl+Shift+[ / ], recent-tab switcher) calls it.

The three call sites are one line each; no other behavior changed.

Why

activateTerminal ends by calling focusTerminalTabSurface(...), but every browser activation path only wrote store state. The local pane and the streamed remote pane had no isActive → guest focus effect at all; only the client-hosted pane did (use-client-hosted-guest-activation-focus.ts), which is the asymmetry the issue reports.

Routing through the shared focus request rather than adding a pane-level effect:

  • All three pane flavors already claim focus from use-browser-page-chrome-focus.ts (local <webview>, client-hosted <webview>, streamed element guest), so one request reaches whichever pane renders the page.
  • The request queue is durable for 30s and claimed on mount, so activation still lands when the pane mounts a frame later.
  • The command palette path already worked this way (tab-bar/open-tab-selection-routing.ts), so this makes tab activation consistent with it instead of introducing a second mechanism.
  • The client-hosted pane's isActive effect is deliberately kept: it also covers activation routes that never enqueue a request (e.g. worktree switches), and its drag gate is what protects tab-drag previews.

Tab-drag preview activation (tab-drag-preview-activation.ts) writes store state directly and never goes through these commands, so no focus request fires mid-drag. Creating a new blank tab goes through the store's pendingAddressBarFocusByPageId path, not these commands, so a new tab still lands in the address bar.

Linked Issue

Fixes #20533

Visual Proof

N/A — no visual change. The fix only moves keyboard focus into the page on activation; rendered pixels are identical before and after. The behavior is covered by the unit tests below rather than screenshots.

Testing

Automated (Linux, headless):

  • pnpm tc → exit 0.
  • pnpm test src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.focus.test.ts src/renderer/src/lib/tab-number-shortcuts.test.ts src/renderer/src/hooks/ipc-tab-switch.test.ts src/renderer/src/components/browser-pane/assemble-chrome/use-browser-page-chrome-focus.test.tsx → 4 files, 60 tests passed. The last file is the existing negative control: a pane still takes page focus only from a queued/announced request.
  • pnpm test src/renderer/src/components/browser-pane/ src/renderer/src/components/tab-bar/ → 167 files, 1340 tests passed.
  • ORCA_CODE_QUALITY_BASE=60d793956af91d16070d852567d7d82718aaf0db pnpm run check:code-quality:changed → pass, 0 findings in all six scanners.

Regression tests added (one per activation route):

  • useTabGroupWorkspaceModel.focus.test.ts — tab activation queues a webview focus request for the tab's active page.
  • tab-number-shortcuts.test.ts — the number shortcut does the same.
  • ipc-tab-switch.test.ts — the existing browser-cycle test now also asserts the focus request.

All three tests were confirmed to fail with the source change stashed and pass with it applied.

Not tested: no macOS/Windows device run. The report is macOS-specific; the unit proof is platform-independent, but a smoke check on macOS of tab-strip click, Ctrl+Tab and Cmd+number into an already-open browser tab is worthwhile before merge.

AI Disclosure

AI-assisted: opencode-go / deepseek-flash (Pi coding agent, reasoning effort max). The change, tests and results were reviewed and run locally by the contributor before submission.

Review

  • Cross-platform: no platform-specific code; no metaKey/accelerator additions. The shortcuts keep using the existing keybinding layer, so Mac and non-Mac chords are unaffected.
  • Local / SSH / remote: focus is keyed by browser page id and travels through the existing store → pane path. No new IPC, process spawning, shell, or path handling. Remote-owned pages consume the same request through the shared chrome-focus hook (which the streamed and client-hosted panes use), so remote workspaces gain the fix rather than regressing.
  • Agents / integrations / git providers: untouched.
  • Performance: one lookup over the active worktree's browser tabs plus the existing queued request per activation. No new polling or timers; the queue's TTL cleanup already existed.
  • UI quality: no visual or layout change; the address bar keeps its focus grab on new blank tabs, and a tab that activates mid-drag is untouched.
  • Security: no change to navigation, permissions, credentials, session partitions, or IPC trust boundaries.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Scope is limited to browser tab activation routes; worktree switching and the CDP tab switch --focus bridge were left as they are.
  • If the worktree's browser tab record is missing (hydration race), no request is queued and behavior falls back to today's — the page stays unfocused until clicked, rather than erroring.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred) — ran pnpm tc, the targeted vitest suites above and check:code-quality:changed locally; the full suites/build are left to CI.

Terminal activation hands the keyboard to xterm before returning, but every
browser tab activation path only updated store state, so an already-mounted
guest kept whatever focus it had until the user clicked the page.

Request page focus from the three activation routes (tab strip, tab cycle,
tab-number shortcut) through the shared focus request that all browser pane
flavors already claim on activation.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ Minor suggestion only — one blank-page rough edge. The fix is otherwise well-targeted and well-tested.

Reviewed changes

  • New requestBrowserWorkspaceTabPageFocus in src/renderer/src/lib/browser-workspace-tab-activation.ts: resolves the workspace's activePageId from browserTabsByWorktree and issues the durable requestBrowserFocus({ pageId, target: 'webview' }) queue entry.
  • Tab-strip click (useTabGroupActivationCommands.ts activateBrowser) calls it after activating.
  • Cmd/Ctrl+number (tab-number-shortcuts.ts activateTabNumberShortcut browser branch) calls it.
  • Ctrl+Tab cycling / recent-tab switcher (ipc-tab-switch.ts activateCyclableTab browser branch, shared by handleSwitchTab, handleSwitchTabAcrossAllTypes, handleSwitchRecentTab) calls it.
  • Tests: three routes each assert the queued request (consumeBrowserFocusRequest → 'webview', or mocked requestBrowserFocus args). I traced each assertion against the behavior it pins — all three would fail with the source change reverted.

I verified the mechanics end to end: all three pane flavors call useBrowserPageChromeFocus, which consumes the pageId-keyed queue on mount/isActive change and on the live ORCA_BROWSER_FOCUS_REQUEST_EVENT, so one request reaches whichever pane renders the page; next.id/target.entityId are the browser workspace entity id in every route; and the 30s TTL covers a pane that mounts a frame later. No correctness, security, or cross-platform concerns.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Warning

Review limit reached

Next included review available in 46 seconds.

Check out review usage here.

View limit details

Limit details: You’ve used all 10 included reviews currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 606dd8c0-1176-4325-8fed-37b370878853

📥 Commits

Reviewing files that changed from the base of the PR and between 86c97ea and 233e7fc.

📒 Files selected for processing (2)
  • src/renderer/src/components/browser-pane/assemble-chrome/use-browser-page-chrome-focus.test.tsx
  • src/renderer/src/components/browser-pane/assemble-chrome/use-browser-page-chrome-focus.ts
📝 Walkthrough

Walkthrough

The change adds browser page focus requests to direct browser activation, browser tab cycling, and number-shortcut activation. The helper targets the address bar for blank pages and the webview for other pages. Guest-focus requests retry while the guest is unavailable, and cancellation stops retries when focus changes or the pane deactivates. Tests cover activation focus requests and guest-focus retries.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to 86c97

In a narrow timing window, the page can take keyboard focus back after the user focuses the address bar. Cancel that retry before merging.

Architecture Summary

Architecture risk: 🔵 Low · up to 86c97

The change affects 1 system.

Changed systems: src

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — src (service) was modified; 9 changed files map to changed impact.

Before / after behavior

  • observed — Modified behavior in src/renderer/src/lib/browser-workspace-tab-activation.ts: Added the requestBrowserFocus and isBlankBrowserUrl imports used to queue page focus and to decide the focus target.
  • observed — Modified behavior in src/renderer/src/lib/browser-workspace-tab-activation.ts: Added requestBrowserWorkspaceTabPageFocus, which finds the workspace tab and reads its activePageId; when no active page exists it returns without requesting focus, otherwise it queues focus targeting the address bar for a blank URL or the webview otherwise. This replaces the earlier behavior of always targeting the webview.
  • observed — Modified behavior in src/renderer/src/lib/tab-number-shortcuts.test.ts: Test setup imports vi, activateTabNumberShortcut, and consumeBrowserFocusRequest, and adds hoisted mocks: useAppStore.getState returns storeBox.state, getRuntimeEnvironmentIdForWorktree returns null, and the web runtime session stubs activateWebRuntimeSessionTab and returns false from isWebRuntimeSessionActive.
  • observed — Modified behavior in src/renderer/src/lib/tab-number-shortcuts.test.ts: The browserTabsByWorktree fixture entry for browser-1 in the new describe block gains a url field set to https://example.com, matching the expected browser tab shape.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: focusing the browser page when its tab is activated.
Description check ✅ Passed The description follows the required template and explains the user impact, implementation, rationale, linked issue, visual proof, testing, review considerations, and checklist status. It also clearly…
Linked Issues check ✅ Passed The PR meets the coding requirements in [#20533]. Tab-strip activation, tab cycling, and number shortcuts call requestBrowserWorkspaceTabPageFocus after browser-tab activation. The request targets t…
Out of Scope Changes check ✅ Passed The changes stay within [#20533]. The source changes add focus requests to the reported browser-tab activation paths and make those requests reliable during guest attachment. The tests verify the page…

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.

…vation

A blank page has nothing to receive keys, so re-activating one now requests
address-bar focus, matching the palette path (isBlankBrowserUrl -> New Tab) and
the new-tab address-bar grab. Non-blank tabs still hand focus to the page.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Blank tabs now land in the address bar — requestBrowserWorkspaceTabPageFocus reads the workspace's mirrored url and picks target: 'address-bar' via isBlankBrowserUrl, falling back to webview for real URLs. This resolves the prior review's one inline suggestion and aligns re-activation with activateBrowserPagePaletteResult and the new-tab pendingAddressBarFocusByPageId path.
  • Regression test for the blank case — useTabGroupWorkspaceModel.focus.test.ts adds a blank-tab case asserting requestBrowserFocus({ pageId, target: 'address-bar' }); it would fail with the old hardcoded 'webview'. Fixtures in the same file and in ipc-tab-switch.test.ts / tab-number-shortcuts.test.ts gained the url field the helper now reads.

I verified the new branch against the panes that consume the request: the queue is keyed by page id and only useBrowserPageChromeFocus consumes it, so local, client-hosted and streamed URL pages get the address bar / guest they expect. A workspace-doc page also carries a blank url by design, but it renders WorkspaceDocPagePane, which registers no chrome-focus consumer — the request is a no-op there exactly as before, so no regression.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Merged upstream main and adapted the branch to its new setActiveTabType(type, worktreeId) signature — the three browser activation routes now pass worktreeId (the hook's worktree, target.worktreeId, and store.activeWorktreeId respectively) instead of the old one-arg call, and the three test assertions were updated to match. Each passes the correct worktree, and upstream's contract (set the global activeTabType only for the active worktree, always record activeTabTypeByWorktree) holds at all three sites.
  • Upstream test rename carried in by the merge in useTabGroupWorkspaceModel.focus.test.ts (closes the durable native owner… → routes durable native owner close through the unified tab action) — unrelated to this PR's behavior.

The prior blank-page focus-target suggestion remains resolved and its regression test is intact. I re-ran the three changed renderer suites (40 tests) and pnpm run typecheck:web — both green — and confirmed the merge left no conflict markers. No new correctness, security, or cross-platform concerns.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Retry the webview focus request until the guest… · browser-workspace-tab-activation.ts:80-83

src/renderer/src/lib/browser-workspace-tab-activation.ts:80-83
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Retry the webview focus request until the guest attaches.

When browser-workspace-tab-activation.ts activates an already-mounted page, its focus hook consumes the webview request immediately. If the guest is not attached, focusGuestNow() returns false, but the live event handler does not retry. Guest attachment does not re-emit or re-consume the request, so the page can remain unfocused. Use the same bounded retry handoff as the mount path.

Suggested fix
-      cancelAddressBarFocusGrab()
-      focusGuestNow()
+      cancelAddressBarFocusGrab()
+      let attempts = 0
+      const runFocus = (): void => {
+        attempts += 1
+        if (!focusGuestNow() && attempts < ADDRESS_BAR_FOCUS_FRAMES) {
+          window.requestAnimationFrame(runFocus)
+        }
+      }
+      window.requestAnimationFrame(runFocus)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 20b944e8-25f1-453e-945b-c5ce9e95199e

📥 Commits

Reviewing files that changed from the base of the PR and between 29a031e and 8efaee9.

📒 Files selected for processing (5)
  • src/renderer/src/components/tab-group/useTabGroupActivationCommands.ts
  • src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.focus.test.ts
  • src/renderer/src/hooks/ipc-tab-switch.test.ts
  • src/renderer/src/hooks/ipc-tab-switch.ts
  • src/renderer/src/lib/tab-number-shortcuts.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

…till attaching

A focus request consumed by an already-active page's live listener tried the guest once, so a guest still attaching lost it. Share the mount path's bounded frame retry, cancelled on deactivation or when a newer request takes over.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: c74fe062-b8c6-40c7-b7d9-fadecc31a12e

📥 Commits

Reviewing files that changed from the base of the PR and between 8efaee9 and 86c97ea.

📒 Files selected for processing (2)
  • src/renderer/src/components/browser-pane/assemble-chrome/use-browser-page-chrome-focus.test.tsx
  • src/renderer/src/components/browser-pane/assemble-chrome/use-browser-page-chrome-focus.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Guest-attach retry for an already-active page — the live ORCA_BROWSER_FOCUS_REQUEST_EVENT handler previously made a single focusGuestNow() attempt, so a webview request consumed while the guest was still attaching was lost. The mount-path retry is now extracted into a shared startGuestFocusRetry(deferFirstAttempt) and called from both that handler (false, immediate first try) and the mount/isActive queue-claim path (true, deferred a frame), retrying up to ADDRESS_BAR_FOCUS_FRAMES. This resolves CodeRabbit's outside-diff suggestion.
  • Mutual grab cancellation — startGuestFocusRetry now cancels any in-flight address-bar grab and startAddressBarFocusGrab cancels an in-flight guest retry, so neither spends its remaining frames pulling focus off the surface the other just aimed at. The retry canceller is parked in guestFocusRetryRef, so the listener effect's cleanup drops an in-flight retry when the pane goes inactive.
  • Regression tests — use-browser-page-chrome-focus.test.tsx adds a case where an already-active pane's guest attaches a frame after the request (fails without the retry) and a case where an in-flight retry is dropped on deactivation. I confirmed the latter fails when the cleanup's cancelGuestFocusRetry() is removed, so it exercises the cancellation rather than passing vacuously. Re-ran the suite: 26 tests green.

The retry is render-stable: guestFocus is memoized on refs in all three panes, so startGuestFocusRetry/startAddressBarFocusGrab don't change identity per render and the effect doesn't tear down a retry mid-flight. No new correctness, security, or cross-platform concerns.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • The address bar now beats a pending guest retry — focusAddressBarNow calls cancelGuestFocusRetry() before blurring the guest and focusing the input, and startAddressBarFocusGrab cancels a guest retry on entry. Previously a webview request consumed while the guest was still attaching scheduled a retry that pulled focus back to the guest the moment it attached, even after Cmd/Ctrl+L or the forwarded IPC had taken the bar.
  • Guest retry extracted into startGuestFocusRetry(deferFirstAttempt) — the mount/queue-claim path passes true (deferred a frame) and the live ORCA_BROWSER_FOCUS_REQUEST_EVENT handler passes false (immediate first try); the canceller is parked in guestFocusRetryRef, so the listener-effect cleanup still drops an in-flight retry when the pane goes inactive.
  • Regression test for both bar paths — use-browser-page-chrome-focus.test.tsx adds an it.each over the chord and IPC that holds the bar against a guest attaching a frame later. I confirmed both cases fail with cancelGuestFocusRetry() removed from focusAddressBarNow (2 failed / 26 passed) and pass with it restored (28 passed).

I verified the new cancellation is symmetric with the existing grab cancellation, so neither retry can outlive the surface the other just aimed at, and re-ran pnpm run typecheck:web (green). Prior feedback remains addressed; no correctness, security, or cross-platform concerns.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker

Copy link
Copy Markdown
Contributor

Thanks for digging into the activation asymmetry, @mmarabel! This is already fixed on main by #31859 (1b0e56e), which also closed #20533. The once-per-activation guest focus that only the client-hosted pane used to have now lives in the shared useBrowserPageChromeFocus hook. Local, client-hosted and streamed pages all take keyboard focus when their tab becomes active, whether that happens from a tab click, Cmd/Ctrl+number or Ctrl+Tab. A new blank tab still goes to the address bar, and focus never jumps across splits.

If switching to a browser tab still leaves your typing in the previous terminal on the latest build, please comment or reopen and we'll take another look.

@nwparker nwparker closed this Oct 26, 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.

[Bug]: [Browser] Keyboard focus is lost when switching between a terminal tab and a browser tab

2 participants