Skip to content

fix(browser): focus foreground tabs opened from image links - #18834

Closed
hwantage wants to merge 10 commits into
stablyai:mainfrom
hwantage:fix/browser-target-blank-focus
Closed

hwantage wants to merge 10 commits into
stablyai:mainfrom
hwantage:fix/browser-target-blank-focus

Conversation

@hwantage

@hwantage hwantage commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Clicking a linked image opens a new tab, but Command+W can still close the original tab. This fixes the remaining image-click case after #31844.

Prepared update: dc4e0150b0, limited to 4 files. The current PR diff will be replaced after a maintainer reopens it.

Reproduction (macOS)

  1. Open a page with an image link that opens in a new tab.
  2. Click the image normally, without holding Command.
  3. Without clicking inside the new tab, press Command+W.

Actual on main: The original tab closes; the image tab stays open.
Expected / prepared update: Only the image tab closes; the original tab stays open.

What Changed

Call window.focus() before webview.focus() in the existing guest-focus adapter. Main's focus-request and attachment-wait handling stays in place.

Fixes #18832.

Visual Proof

Annotated screenshots from the original PR recordings; the tab strips are enlarged to show which tab closes.

Image-click reproduction: normal click, new tab, Command+W, actual and expected results

Original before/after recordings

Before: main adcc30be3b. After: earlier PR implementation. These are the original recordings, not new captures of today's main.

Before: original tab closes After: image tab closes
Before After

Testing

  • Manual macOS comparison using the steps above: main fails; the prepared update passes.
  • Focused unit tests, renderer typecheck, and image-link E2E passed. The E2E checks image readiness, DOM focus, and direct guest shortcut forwarding; native keyboard routing was checked manually.
  • Changed-file checks: 22/23 passed. The remaining failure is pre-existing flaky-test-rule findings in unchanged filesystem-watcher tests.
  • Current Windows/Linux native input and switching to another app during guest startup have not been revalidated.

AI Disclosure

Assisted by Claude Code and OpenAI Codex; this narrowed update was prepared and self-reviewed with Codex.

Agent skill upstream boundary

  • Not applicable; no upstream skill material is copied.

Opening a link in a new tab could leave keyboard focus on the opener, causing Cmd+W to close the parent tab instead of the newly opened tab.

- request focus for tabs opened through links and the context menu
- focus the embedder before handing focus to the attached webview
- avoid restoring opener focus when dismissing the link-opening menu
@coderabbitai

coderabbitai Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 36c4e76c-1403-4947-b533-5b4cdb86a8ed

📥 Commits

Reviewing files that changed from the base of the PR and between 56e2b68 and f2146f4.

📒 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: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

📝 Walkthrough

The change adds pending browser-focus inspection and adjusts request consumption until guest focus succeeds or a cancellation occurs. Webview attachment now checks getWebContentsId(), and guest focus activates the embedder window before the webview. New-tab link handling requests focus for activated destination pages. Guest readiness reissues pending webview requests. Unit and end-to-end tests cover delayed attachment, cancellation, StrictMode replay, and closing an image destination tab.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to f2146

The previously identified focus failures are addressed. No actionable merge-blocking risk remains after normal checks.

Architecture risk: 🔵 Low · up to f2146

The change affects 2 systems.

Changed systems: src, tests

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

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

Before / after behavior

  • observed — Modified behavior in src/renderer/src/components/browser-pane/assemble-chrome/browser-page-guest-focus.test.tsx: Added hook tests confirming attachment detection remains false when getWebContentsId throws and becomes true after it returns an ID, with mock cleanup after each test.
  • observed — Modified behavior in src/renderer/src/components/browser-pane/assemble-chrome/browser-page-guest-focus.test.tsx: Added a focus-order test verifying the embedder window is focused before the guest webview, focus succeeds, and the webview becomes the active element.
  • observed — Modified behavior in src/renderer/src/components/browser-pane/assemble-chrome/browser-page-guest-focus.ts: isAttached in useWebviewGuestFocus now returns (webviewRef.current?.getWebContentsId() ?? 0) > 0 wrapped in a try/catch that returns false on error, replacing the prior webviewRef.current !== null check so a destroyed/absent guest reports as unattached.
  • observed — Modified behavior in src/renderer/src/components/browser-pane/assemble-chrome/browser-page-guest-focus.ts: focus in useWebviewGuestFocus now calls window.focus() before webview.focus() so keyboard input does not remain on the opener guest.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.18% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 15 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 main change: focusing foreground browser tabs opened from image links.
Description check ✅ Passed The description follows the required template and includes the user impact, implementation details, rationale, linked issue, visual proof, testing results, validation limits, review notes, and checkli…
Linked Issues check ✅ Passed The changes satisfy the coding requirements for [#18832]. Foreground link creation requests focus for the new active page. The focus handler now waits for an attached guest and focuses the browser win…
Out of Scope Changes check ✅ Passed The changes stay within [#18832]. The source changes implement foreground-tab focus transfer and focus-request lifecycle handling. The unit tests, image fixture, and image-link E2E test provide regres…

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.

@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

  • Link-open IPC handler — browser-state-ipc-bridge.ts now queues requestBrowserFocus for the newly created tab's activePageId, so keyboard shortcuts route to the destination guest instead of the opener.
  • Link context menu — "Open Link In Orca Browser" dismisses the menu without the opener-refocus in closeMenu, then queues a focus request for the new page; other items keep closeMenu().
  • Shared webview focus adapter — isAttached() now checks getWebContentsId() before treating a guest as attachable, and focus() calls window.focus() before webview.focus().
  • Queued-request consumption — a new peekBrowserFocusRequest defers consume to the first animation-frame attempt, preserving the request across StrictMode effect replay while keeping immediate consumption for address-bar requests.
  • Tests — unit coverage for the focus adapter, queued-request behavior, the IPC path, and the context-menu path; the E2E generic-link case is extended with a native CmdOrCtrl+W step.

I verified the id semantics hold end-to-end (requestBrowserFocus({ pageId: newTab.activePageId }) keys the queue by page id, and useBrowserPageChromeFocus consumes with browserTabId = BrowserPage.id), and the StrictMode fix is correct: the deferred consume happens exactly once on the first frame attempt.

ℹ️ Native-focus verification only runs in foreground E2E

The step that actually proves the bug (that CmdOrCtrl+W closes the natively focused destination guest via webContents.getFocusedWebContents()) is skipped unless ORCA_E2E_FOREGROUND=1. The always-on assertion expect(destinationWebview).toBeFocused() checks DOM focus, not native webContents focus — it catches a regression in the webview.focus() half of the fix, but not in the window.focus() half that transfers OS keyboard focus, which is the part that was actually broken. In the default headless CI run that regression could return silently. This is a reasonable, disclosed limitation; noting it only so it's on the record that CI coverage here is DOM-level, not native.

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

@hwantage

hwantage commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

@pullfrog
Thanks for the thorough review and for flagging the native-focus coverage gap.

Added two @headful E2E cases covering target="_blank" links and context-menu link opening. They enable ORCA_E2E_FOREGROUND=1 through the fixture, verify the natively focused WebContents, and confirm that Cmd/Ctrl+W closes only the destination tab while preserving the opener.

Both pass locally on macOS. The existing changed-E2E workflow selects this spec for headful execution when it is included in the PR diff. Existing tests, the default headless suite, and production code are unchanged.

@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 critical issues — two test-reliability notes inline.

Reviewed changes

  • Native-focus E2E spec — added tests/e2e/browser-link-native-focus.spec.ts, a @headful + ORCA_E2E_FOREGROUND=1 spec that drives both link routes (target=_blank and context menu) and proves CmdOrCtrl+W closes the destination guest via webContents.getFocusedWebContents(), closing the loop on the prior note that native-focus verification was skipped in the standard CI lane.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (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.

Important

The new native-focus spec is only verified on macOS, but the changed-e2e lane and the scheduled full suite run it on Ubuntu under bare xvfb-run — no window manager, no dbus session. BrowserWindow.getFocusedWindow() has never been exercised in that environment, so if X input focus is not established there, expectBrowserGuestFocused polls for windowFocused: true until its 10s expect timeout and fails, turning this PR's lane red and polluting every scheduled main-branch run. Confirm the spec actually passes on Linux CI (or gate it) before relying on it.

Reviewed changes

  • Headful native-focus E2E spec — adds tests/e2e/browser-link-native-focus.spec.ts, a @headful spec that forces ORCA_E2E_FOREGROUND=1 through the fixture and asserts the destination guest owns native keyboard focus (webContents.getFocusedWebContents() + BrowserWindow.getFocusedWindow()) after both a target="_blank" click and the context-menu "Open Link In Orca Browser" path, then verifies CmdOrCtrl+W closes only the destination tab while preserving the opener.
Technical details
# Verify native-focus spec on Linux CI before relying on it

## Affected sites
- tests/e2e/browser-link-native-focus.spec.ts:19-26 — `expectBrowserGuestFocused` polls `BrowserWindow.getFocusedWindow() !== null`
- tests/e2e/browser-link-native-focus.spec.ts:32 — `ORCA_E2E_FOREGROUND=1` forced with no platform/WM guard

## Required outcome
- Confirm the spec passes on the Ubuntu `changed-e2e` lane (bare `xvfb-run`, no WM) — the environment it actually runs in — not just macOS.

## Suggested approach (optional)
- If focus is not reliably established under Xvfb, either gate the spec to a platform where native focus is exercised (as the IME specs do via `ORCA_E2E_NATIVE_*`), or run the lane with a WM/dbus session (compare the computer-e2e lane's `dbus-run-session`).

## Open questions for the human (optional)
- Does bare Xvfb without a window manager assign X input focus such that `getFocusedWindow()` is non-null?

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (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.

ℹ️ The retry refactor is clean and resolves the getWebContentsId concern from the prior review; no new issues. I'm holding approval because the native-focus-on-Linux-CI concern raised earlier — expectBrowserGuestFocused asserting BrowserWindow.getFocusedWindow() !== null under bare xvfb-run — is still unaddressed.

Reviewed changes

  • Guest-ID retry — expectBrowserGuestFocused now wraps the guest-ID read and the native-focus assertion in expect(...).toPass({ timeout: 10_000 }), re-reading getWebContentsId() on every attempt so a slow-attaching destination guest is awaited instead of throwing.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@hwantage

hwantage commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor Author

@pullfrog

Verified on Linux under bare xvfb-run — the spec passes

Ran the new spec on Linux in the same shape as the changed-e2e lane, twice: once with my desktop dbus session inherited, and once with the dbus session and every display variable stripped.

# 1) bare xvfb (no window manager), desktop dbus inherited
xvfb-run --auto-servernum env ORCA_E2E_FORWARD_APP_LOGS=1 \
  pnpm run test:e2e tests/e2e/browser-link-native-focus.spec.ts \
  --workers=1 --project=electron-headful
# -> 2 passed (50.2s)

# 2) same, with no dbus session and no inherited DISPLAY / WAYLAND_DISPLAY
env -u DBUS_SESSION_BUS_ADDRESS -u WAYLAND_DISPLAY -u DISPLAY \
  xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 \
  pnpm run test:e2e tests/e2e/browser-link-native-focus.spec.ts \
  --workers=1 --project=electron-headful
# -> 2 passed (30.0s)

Both runs:

✓ 1 [electron-headful] › browser-link-native-focus.spec.ts:40 › CmdOrCtrl+W closes only the target=_blank destination
✓ 2 [electron-headful] › browser-link-native-focus.spec.ts:40 › CmdOrCtrl+W closes only the context menu destination

So the open question — "Does bare Xvfb without a window manager assign X input focus such that getFocusedWindow() is non-null?" — answers yes. expectBrowserGuestFocused reaches { windowFocused: true, guestId } well inside its 10s budget in both link routes, so there is no timeout to gate against and no platform guard is needed.

Environment: Ubuntu 26.04 aarch64, Electron 43.4.1, at d182d68. Architecture and Ubuntu minor differ from ubuntu-latest, but X input focus assignment under Xvfb does not vary along those axes.

One correction

the changed-e2e lane and the scheduled full suite run it on Ubuntu under bare xvfb-run

The scheduled full suite does not run it. The e2e job (.github/workflows/e2e.yml:98) invokes pnpm run test:e2e, which is pinned to --project=electron-headless (package.json:102), and the headless project grepInverts /@headful/ (tests/playwright.config.ts:46). --project=electron-headful is appended only in the changed-e2e lane (.github/workflows/e2e.yml:241-242). changed-e2e is therefore the only lane that runs this spec, and there is no path for it to redden scheduled main-branch runs.

@pullfrog

pullfrog Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Thanks for running this — that closes the open question cleanly, and the correction is right.

Confirmed: package.json:104 pins test:e2e to --project=electron-headless, and the headless project grepInverts /@headful/ (tests/playwright.config.ts:46), so the scheduled e2e job (.github/workflows/e2e.yml:102, if: inputs.test_files == '') never matches this spec. Only changed-e2e appends --project=electron-headful (.github/workflows/e2e.yml:245-247) when a changed spec contains @headful. No path for it to redden a scheduled main-branch run.

One addition to my earlier note: both lanes actually run under a window manager, not bare Xvfb — e2e-with-window-manager.sh starts openbox and waits on _NET_SUPPORTING_WM_CHECK before running the specs. So my "no window manager" framing was also off, in the safe direction: the real CI environment is more permissive than the bare-Xvfb case verified here. Getting { windowFocused: true } even without a WM means the native-focus assertion holds in both environments.

No platform guard or timeout change needed — the native-focus concern on this spec is resolved.

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

Keep the background-tab behavior introduced by stablyai#18873 when resolving
the link context-menu and browser gesture test conflicts.
Apply focus when the new tab is ready so CmdOrCtrl+W closes it
and preserves the opener. Cancel pending focus when the user
switches tabs or splits.
@coderabbitai

coderabbitai Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@hwantage hwantage changed the title fix(browser): prevent Cmd+W from closing the opener tab fix(browser): focus foreground tabs opened from image links Sep 6, 2026
@hwantage

hwantage commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

Updated this PR after #18873 changed how background links are opened.

Cmd/Ctrl-click and Open Link In Orca Browser now open the destination in the background and keep the current tab active. I removed this PR's earlier foreground-focus handling and test expectations for those routes to preserve that behavior.

The remaining issue is reproducible on main with a plain click on a linked image:

Click an image link that opens a new foreground tab.

Without clicking inside the destination, press Cmd/Ctrl+W.

The parent tab closes instead of the newly activated image tab.

The follow-up uses the existing focus request mechanism for foreground opens. It waits until the guest can accept focus and cancels pending focus when the user switches tabs or splits, clicks elsewhere, or explicitly focuses the address bar. Background opens keep the behavior introduced in #18873.

Native image-click/close-shortcut checks passed on macOS and Linux. The PR description now includes the image-click Before/After GIFs, updated test coverage, and the Linux/E2E validation limits.

I merged main into this branch and added a follow-up commit, preserving the original three commits and keeping the discussion in this PR:

Main merge: d6c3829

Final fix: 3d2c14d

@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

  • Foreground-only focus routing — onOpenLinkInOrcaTab now requests focus only when activate is true, and the "Open Link In Orca Browser" context-menu change from the earlier version was reverted, matching #18873's background-open policy for modifier-clicks and the context-menu route.
  • Pending-request cancellation — a queued guest-focus request is now consumed when the pane becomes inactive, a split loses shortcut scope, the renderer receives a pointerdown, or the address bar is focused, so focus never lands in a tab the user has already left.
  • dom-ready retry — webview-registry's onRendererReady re-requests a still-pending guest focus, completing it when the guest attaches after the six-frame retry budget instead of dropping it.
  • DOM-level E2E replacement — the native-focus spec (the source of the prior Linux CI concern) was removed and replaced with browser-image-link-focus.spec.ts, which drives the image-click reproduction and asserts close-key routing at the DOM level, with native focus verified manually and documented.

I traced the id semantics (requestBrowserFocus({ pageId: newTab.activePageId }) keys by page id, consumed as browserTabId), the frame-loop / pointerdown / dom-ready interplay, and the StrictMode replay path, and confirmed the cancellation and retry paths cannot double-focus or drop a still-pending request.

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

…blank-focus

# Conflicts:
#	src/renderer/src/components/browser-pane/assemble-chrome/use-browser-page-chrome-focus.test.tsx

@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 (2)

🟠 Major · Reject event-driven webview focus in an inactive split. · use-browser-page-chrome-focus.ts:266

src/renderer/src/components/browser-pane/assemble-chrome/use-browser-page-chrome-focus.ts:266
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Reject event-driven webview focus in an inactive split.

isActive can be true while another split owns focus, as the new test models. The changed mount effect discards a webview request when chromeShortcutScope is inactive, but this listener still calls focusGuestNow() for a new request. If the guest is attached, that call steals focus from the other split. Apply the same scope check to event-delivered requests.

🟠 Major · Retain event-delivered webview requests until guest focus… · use-browser-page-chrome-focus.ts:255

src/renderer/src/components/browser-pane/assemble-chrome/use-browser-page-chrome-focus.ts:255
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Retain event-delivered webview requests until guest focus succeeds.

When modal return-focus targets an active page whose guest is reattaching, requestBrowserFocus dispatches synchronously. The listener consumes the request before focusGuestNow(), which can return false. The later dom-ready handler then finds no pending request and does not retry focus.

Peek at webview requests and consume them only after focusGuestNow() returns true.

Suggested fix
-      const focusTarget = consumeBrowserFocusRequest(browserTabId)
+      const focusTarget = peekBrowserFocusRequest(browserTabId)
       if (!focusTarget) {
         return
       }
       if (focusTarget === 'address-bar') {
+        consumeBrowserFocusRequest(browserTabId)
         // Why: palette-triggered focus fights the same re-grab as a new tab does, so it takes
         // the bar the same bounded way rather than latching on a single try.
         startAddressBarFocusGrab()
         return
       }
       cancelAddressBarFocusGrab()
-      focusGuestNow()
+      if (focusGuestNow()) {
+        consumeBrowserFocusRequest(browserTabId)
+      }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 4b2f48be-d176-4c02-aa8b-98fb9f932ad3

📥 Commits

Reviewing files that changed from the base of the PR and between 3d2c14d and 56e2b68.

📒 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; 9 remain 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

  • Merged upstream/main into the branch and adapted use-browser-page-chrome-focus.ts to the upstream shortcut-scoping refactor: the Cmd/Ctrl+L guard now calls browserChromeShortcutOwnsEvent, and the forwarded onFocusBrowserAddressBar IPC is scoped to its own pane via browserPageId === browserTabId.
  • Reworked the focus hook's tests onto upstream's shared paneChannel test rig, carrying upstream's split and floating-panel chord-scoping cases alongside the PR's queued-focus cases.

No behavioral change reaches the fix itself: the queued guest-focus request, its address-bar and pointerdown cancellation, the six-frame retry, and the dom-ready re-request are untouched by the merge; every other file in the PR is byte-identical to the prior reviewed commit. pnpm tc:web and the 61 focused unit tests pass on the merged head.

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

Ignore guest focus requests in inactive splits.
Keep requests pending until guest focus succeeds, and cancel them
when the user moves focus elsewhere.

Add regression tests for delayed attachment and cancellation.

@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

  • Retained event-delivered guest focus — the ORCA_BROWSER_FOCUS_REQUEST_EVENT listener now peeks instead of consuming, and consumes a 'webview' request only after focusGuestNow() succeeds, so a guest that attaches after the short frame budget still gets focus via the dom-ready re-request.
  • Rejected guest focus in inactive splits — the event listener consumes and drops a 'webview' request when chromeShortcutScope === 'inactive', matching the mount effect, so a request can no longer steal focus from the split that owns shortcuts.
  • Moved pointerdown cancellation — the capture pointerdown consumer was lifted out of the mount effect's focus-loop branch into the active-pane event effect, so a retained event-delivered request is cancelled by a click even when no retry loop is running.
  • Unit coverage — added cases for retention across a late guest reattach, inactive-split rejection, cancellation on pointer / address-bar / split / tab input, and no replay after the pane goes inactive.

I re-read both effects end-to-end and traced the retain → dom-ready retry → consume-on-success path, the cancellation paths (pointerdown, address-bar focus, isActive/scope change), and the StrictMode replay contract. The focusAddressBarNow consume was already present on 56e2b68 (added in 3d2c14d), so this delta only re-scopes and retains. Verified locally: 72 focused unit tests pass across the four changed test files and pnpm tc:web is clean. All prior Pullfrog threads remain resolved.

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

@hwantage

Copy link
Copy Markdown
Contributor Author

Caution

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

⚠️ Outside diff range comments (2)

🟠 Major · Reject event-driven webview focus in an inactive split. · use-browser-page-chrome-focus.ts:266

src/renderer/src/components/browser-pane/assemble-chrome/use-browser-page-chrome-focus.ts:266
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Reject event-driven webview focus in an inactive split.
isActive can be true while another split owns focus, as the new test models. The changed mount effect discards a webview request when chromeShortcutScope is inactive, but this listener still calls focusGuestNow() for a new request. If the guest is attached, that call steals focus from the other split. Apply the same scope check to event-delivered requests.

🟠 Major · Retain event-delivered webview requests until guest focus… · use-browser-page-chrome-focus.ts:255

src/renderer/src/components/browser-pane/assemble-chrome/use-browser-page-chrome-focus.ts:255
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Retain event-delivered webview requests until guest focus succeeds.
When modal return-focus targets an active page whose guest is reattaching, requestBrowserFocus dispatches synchronously. The listener consumes the request before focusGuestNow(), which can return false. The later dom-ready handler then finds no pending request and does not retry focus.
Peek at webview requests and consume them only after focusGuestNow() returns true.

Suggested fix

-      const focusTarget = consumeBrowserFocusRequest(browserTabId)
+      const focusTarget = peekBrowserFocusRequest(browserTabId)
       if (!focusTarget) {
         return
       }
       if (focusTarget === 'address-bar') {
+        consumeBrowserFocusRequest(browserTabId)
         // Why: palette-triggered focus fights the same re-grab as a new tab does, so it takes
         // the bar the same bounded way rather than latching on a single try.
         startAddressBarFocusGrab()
         return
       }
       cancelAddressBarFocusGrab()
-      focusGuestNow()
+      if (focusGuestNow()) {
+        consumeBrowserFocusRequest(browserTabId)
+      }

ℹ️ Review info

@coderabbitai review

Both findings were addressed in f2146f4:

  • Reject event-driven guest focus in inactive splits.
  • Retain pending requests until guest focus succeeds, with cancellation when the user moves focus elsewhere.

Regression tests were added. Please verify both findings against the latest commit

@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Preserve source tab placement and execution host inheritance while retaining foreground guest focus requests.

@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 (21f8e0f) into the branch — the range-diff vs the prior reviewed head touches only browser-state-ipc-bridge.ts; upstream's resolveBrowserSourceUnifiedTab refactor now lives there.
  • Merge adaptation preserves the fix — the PR overlay is unchanged: const newTab = createBrowserTab(...) plus requestBrowserFocus({ pageId: newTab.activePageId, target: 'webview' }) for foreground opens.
  • No focus-handling gap from the new host route — the focus request is consumed through useBrowserPageChromeFocus, which every pane variant mounts.

Verified browser-state-open-link-profile.test.ts and browser-workspace-source-resolution.test.ts pass (10 tests) on the merged head. All prior Pullfrog threads remain resolved.

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

Keep the foreground browser focus request alongside main's updated runtime ownership lookup. Validated with 116 focused tests, tc:web, and lint/format checks on the conflict resolution.
Reuse main's shared tab-opening and guest-attachment flow while retaining pending focus until readiness or cancellation. Validated 119 passing tests plus one existing expected failure and targeted lint/format checks. Web typecheck remains blocked by main's Jira type imports.
@nwparker

Copy link
Copy Markdown
Contributor

Thanks @hwantage for digging into why focus never reached the new tab! This is already fixed on main by #31844 (291e2e8): a foreground tab opened from a page (target=_blank, window.open) now queues a webview focus request, and the pane's focus retry waits up to 120 frames for the new guest to attach before starting its budget, giving up if the user moves focus meanwhile, so Cmd/Ctrl+W closes the new tab rather than its opener. Background opens (activate: false, Cmd+click, middle-click) still leave focus where it was. If you can still reproduce the opener closing after clicking a linked image on the latest build, please comment or reopen.

@nwparker nwparker closed this Oct 26, 2026
@hwantage

Copy link
Copy Markdown
Contributor Author

@nwparker, could you reopen this PR? GitHub does not allow me to reopen it. The plain image-click case still reproduces on main after #31844 (macOS):

  1. Click a linked image normally to open it in a new tab.
  2. Do not click inside the new tab.
  3. Press Command+W.

Actual: The original tab closes; the image tab remains.
Expected: Only the image tab closes.

The same manual steps fail on main and pass with the prepared fix: window.focus() before webview.focus(). I will replace the PR diff with this narrowed update once it is reopened.

This screenshot explains the steps using the original PR recordings:

Image-click reproduction and expected result

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] Cmd+W closes the opener instead of a newly opened link tab

2 participants