Skip to content

fix(browser): prevent window.close guest crashes - #11910

Merged
nwparker merged 3 commits into
stablyai:mainfrom
nwparker:nwparker/bug-main-process-sigsegv-after-window.close-in-a
Aug 1, 2026
Merged

nwparker merged 3 commits into
stablyai:mainfrom
nwparker:nwparker/bug-main-process-sigsegv-after-window.close-in-a

Conversation

@nwparker

@nwparker nwparker commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Guard ordinary embedded browser guests against window.close() during document creation and after dom-ready.
  • Clear both forward and reverse guest/tab registrations when a guest is destroyed.
  • Preserve explicit CLI-created tab self-close behavior and add Electron regression coverage for the target=_blank flow.

ELI5

An embedded browser tab is like a small browser window inside Orca. A link-created tab ran window.close(), and although the close was supposed to be blocked, Orca kept a pointer to the guest after Chromium had destroyed it. Clicking another tab made Orca use that dead pointer and crash. The fix blocks window.close() early for normal embedded tabs and removes stale pointers when guests are destroyed. CLI-created tabs intentionally keep their existing self-close behavior.

Fixes #11763

Validation

  • 268 targeted Vitest tests passed.
  • Workspace-schema tests passed.
  • pnpm run typecheck passed.
  • pnpm exec electron-vite build --mode e2e passed.
  • SKIP_BUILD=1 pnpm exec playwright test tests/e2e/browser-tab.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --grep 'blocked window.close' passed.
  • Changed-file native/type-aware lint passed.

Full lint still reports two unrelated pre-existing duplicate-import warnings in tests/tools/benchmarks/terminal-cold-park-resource-bench.mjs and tests/tools/benchmarks/terminal-cold-park-reveal-bench.mjs.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@nwparker, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 2 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9ff6835f-e25b-462f-9ef4-556c1a3c38ad

📥 Commits

Reviewing files that changed from the base of the PR and between 0011a27 and df84d50.

📒 Files selected for processing (11)
  • electron.vite.config.ts
  • src/main/browser/browser-manager.test.ts
  • src/main/browser/browser-manager.ts
  • src/main/window/createMainWindow.test.ts
  • src/main/window/createMainWindow.ts
  • src/preload/browser-window-close-installation.ts
  • src/preload/browser-window-close.test.ts
  • src/preload/browser-window-close.ts
  • src/renderer/src/components/browser-pane/BrowserPane.webview-preferences.test.ts
  • src/shared/browser-window-close-policy.ts
  • tests/e2e/browser-tab.spec.ts
📝 Walkthrough

Walkthrough

The change adds an optional allowWindowClose field to browser pages and session data. Renderer state, restoration, IPC tab creation, and webview creation propagate this field. An approved preload identifies guests that may retain native window-close behavior. Other primary guests receive a protected window.close guard during policy injection. Cleanup removes the guard listener and both guest-to-tab mappings. Tests cover the guard, policy propagation, guest cleanup, and link-created tabs.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the fix and validation, but it omits the required Screenshots, AI Review Report, Security Audit, and Notes sections. Add the missing template sections and document screenshots status, AI review scope and findings, security risks, and platform-specific notes.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address issue #11763 by guarding link-opened guests, cleaning guest mappings, preserving CLI self-close behavior, and adding regression tests.
Out of Scope Changes check ✅ Passed The implementation and tests remain within the linked issue scope for window.close crash prevention and guest lifecycle cleanup.
Title check ✅ Passed The title clearly identifies the browser fix that prevents window.close guest crashes.

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.

@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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6176e7ea-dee8-4cae-8e73-3a67275a301f

📥 Commits

Reviewing files that changed from the base of the PR and between edb5607 and 0011a27.

📒 Files selected for processing (16)
  • src/main/browser/browser-manager.test.ts
  • src/main/browser/browser-manager.ts
  • src/main/browser/browser-window-close-guard.test.ts
  • src/main/browser/browser-window-close-guard.ts
  • src/main/window/createMainWindow.test.ts
  • src/main/window/createMainWindow.ts
  • src/renderer/src/components/browser-pane/BrowserPane.tsx
  • src/renderer/src/components/browser-pane/BrowserPane.webview-preferences.test.ts
  • src/renderer/src/components/browser-pane/browser-page-webview.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/store/slices/browser.ts
  • src/shared/browser-window-close-policy.ts
  • src/shared/types.ts
  • src/shared/workspace-session-schema.ts
  • tests/e2e/browser-tab.spec.ts

Comment thread src/main/browser/browser-manager.ts Outdated
Comment on lines +646 to +663
const shouldGuardWindowClose =
inheritedOwnerContext === null &&
guest.getType() === 'webview' &&
options.allowWindowClose !== true
const disposeAntiDetection = this.injectAntiDetection(
guest,
shouldGuardWindowClose ? BROWSER_WINDOW_CLOSE_GUARD_SCRIPT : ''
)
const installWindowCloseGuard = (): void => {
if (!shouldGuardWindowClose || guest.isDestroyed()) {
return
}
try {
void guest.executeJavaScript(BROWSER_WINDOW_CLOSE_GUARD_SCRIPT).catch(() => {})
} catch {
// Guest may detach between dom-ready and script evaluation.
}
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Electron 43 WebContents debugger Page.addScriptToEvaluateOnNewDocument behavior when registration occurs after a navigation has started

💡 Result:

In Electron (including version 43), the Chrome DevTools Protocol (CDP) method Page.addScriptToEvaluateOnNewDocument is designed to evaluate a script in every frame upon creation, specifically before any of the frame's other scripts are loaded [1][2][3]. Regarding behavior when registration occurs after a navigation has started: 1. Standard Behavior: Page.addScriptToEvaluateOnNewDocument registers a script that persists across navigations for the lifetime of the DevTools session (or until removed via Page.removeScriptToEvaluateOnNewDocument) [4]. When you register this script after a navigation has already initiated (e.g., after the browser has begun loading a new URL), the script will typically not apply to the current, ongoing navigation if the frame creation event has already passed [1][2][3]. It will, however, apply to subsequent navigations or new frames created after the registration is successfully processed [1][2][3]. 2. The runImmediately Parameter: The CDP documentation includes an optional runImmediately parameter [3][5]. If runImmediately is set to true, the script will run immediately on existing execution contexts or worlds [2][3]. If you need the script to execute even if registered mid-navigation, enabling this parameter (if available in your specific environment's protocol version) may allow the script to take effect on the current document [3]. 3. Electron-Specific Context: Electron's webContents.debugger attaches to the WebContents and manages CDP sessions [6]. If you are experiencing issues with scripts not being applied, ensure that Page.enable has been called on the debugger session; without it, many Page domain events and commands may not function as expected [7]. Additionally, be aware that Electron internally manages RenderFrameHost lifecycle, and in recent versions (including those around 43), internal re-attachments of the debugger session during navigation can occasionally lead to dropped messages or protocol state resets if not handled carefully [8][9]. To ensure consistent behavior, it is best practice to: - Call Page.enable immediately after attaching the debugger [7]. - Register your Page.addScriptToEvaluateOnNewDocument scripts as early as possible, ideally before initiating any navigation (e.g., before calling webContents.loadURL). - If you must register dynamically, consider using the runImmediately: true flag if the protocol version supports it [3].

Citations:


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "Repository files matching browser-manager:"
fd -a 'browser-manager\.ts$' . || true

file="$(fd 'browser-manager\.ts$' . | head -n 1 || true)"
if [ -n "$file" ]; then
  echo "---- outline ----"
  ast-grep outline "$file" --match injectAntiDetection --view expanded || true
  ast-grep outline "$file" --match attachGuestPolicies --view expanded || true
  echo "---- relevant sections ----"
  sed -n '1,120p' "$file" | cat -n
  sed -n '260,320p' "$file" | cat -n
  sed -n '620,710p' "$file" | cat -n
  echo "---- definitions ----"
  rg -n "BROWSER_WINDOW_CLOSE_GUARD_SCRIPT|injectAntiDetection|attachGuestPolicies|addScriptToEvaluateOnNewDocument|debugger|dom-ready|window\.close" "$file"
fi

echo "---- package electron version ----"
if [ -f package.json ]; then jq -r '.dependencies.electron, .devDependencies.electron' package.json 2>/dev/null || true; fi
if [ -f package-lock.json ]; then rg -n '"electron"' package-lock.json | head -n 20 || true; fi

Repository: stablyai/orca

Length of output: 14512


🌐 Web query:

Electron debugger WebContents debugger Page.addScriptToEvaluateOnNewDocument runImmediately API availability

💡 Result:

The Page.addScriptToEvaluateOnNewDocument method is a part of the Chrome DevTools Protocol (CDP), not a native method of the Electron WebContents API [1][2]. In Electron, you access this functionality by using the webContents.debugger API, which allows you to send raw CDP commands [2][3]. Regarding the runImmediately parameter: 1. Availability: The runImmediately boolean parameter is defined in the Chrome DevTools Protocol specification for the Page.addScriptToEvaluateOnNewDocument method [1]. It is officially marked as experimental in the protocol documentation [1]. 2. Functionality: When set to true, this parameter causes the script to run immediately on existing execution contexts or worlds, rather than waiting for new navigations [1][4]. The default value is false [1][4]. 3. Electron Context: Because Electron's webContents.debugger.sendCommand method is a generic transport for CDP commands, it supports any command defined in the protocol version used by the underlying Chromium engine [2][3]. Therefore, if the version of Chromium bundled with your specific Electron release includes support for this experimental Page.addScriptToEvaluateOnNewDocument parameter in its CDP implementation, you can use it by passing it in the commandParams object [1][2]. To use it in Electron, you would typically structure your code as follows: const { BrowserWindow } = require('electron'); const win = new BrowserWindow; // Attach the debugger win.webContents.debugger.attach('1.3'); // Ensure a compatible protocol version // Send the command with the experimental parameter win.webContents.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: 'console.log("Hello from debugger");', runImmediately: true // Experimental parameter }).then((params) => { console.log('Script added with ID:', params.identifier); }).catch((err) => { console.error('Failed to add script:', err); }); Because runImmediately is considered experimental, it may be subject to changes or removal in future Chromium updates, and its availability depends entirely on the specific version of Chromium embedded in your Electron version [1].

Citations:


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

file="src/main/browser/browser-manager.ts"
echo "---- attachGuestPolicies call sites and surrounding code ----"
sed -n '620,760p' "$file" | cat -n
echo "---- attachGuestPolicies cleanup and later calls ----"
sed -n '880,1150p' "$file" | cat -n
echo "---- AntiDetection script and Guard script contents ----"
fd -a 'anti-detection\.ts$|anti-detection\.js$' . | while read -r f; do echo "---- $f ----"; wc -l "$f"; sed -n '1,220p' "$f" | cat -n; done
fd -a 'browser-window-close-guard\.ts$|browser-window-close-guard\.js$' . | while read -r f; do echo "---- $f ----"; wc -l "$f"; sed -n '1,220p' "$f" | cat -n; done
echo "---- guest creation/registration references ----"
rg -n "attachGuestPolicies\\(|shouldGuardWindowClose|load\\(|loadURL|navigate|dom-ready|addCommandMessageHandler|executeJavaScriptInIsolatedWorld" "$file" | sed -n '1,220p'

Repository: stablyai/orca

Length of output: 28870


🌐 Web query:

Electron 43 WebContents WebContentsDebugger sendCommand Page.addScriptToEvaluateOnNewDocument debugger attached before navigation

💡 Result:

In Electron, using the Chrome DevTools Protocol (CDP) to call Page.addScriptToEvaluateOnNewDocument allows you to inject JavaScript into every frame upon creation, guaranteeing that it executes before any of the frame's own scripts load [1][2]. To use this successfully, especially in scenarios involving navigation or frame creation, follow these critical technical practices: 1. Enable the Page Domain: You must call Page.enable before invoking Page.addScriptToEvaluateOnNewDocument [2][3]. If you do not explicitly enable the domain, the command may fail or have no effect [3]. 2. Handling Navigation and Race Conditions: - Persistence: Page.addScriptToEvaluateOnNewDocument persists across navigations and page reloads [4]. You generally only need to register the script once per debugging session [2]. - Timing Issues: While the protocol guarantees the script runs "upon creation (before loading frame's scripts)," relying on this for critical initialization can still lead to race conditions if other commands (like Runtime.evaluate or navigation triggers) occur simultaneously [5][6]. - Synchronization: If you are attaching to new targets (such as iframes or popups) that may pause at startup (e.g., using Target.setAutoAttach with waitForDebuggerOnStart), you must ensure your initialization commands—including Page.enable and Page.addScriptToEvaluateOnNewDocument—are sent and acknowledged before you issue the Runtime.runIfWaitingForDebugger command to resume the target [6]. 3. Implementation Example: javascript const dbg = win.webContents.debugger; dbg.attach("1.3"); // Enable domains before sending other commands await dbg.sendCommand("Page.enable"); await dbg.sendCommand("Runtime.enable"); // Register the script await dbg.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source: `console.log('Injected before navigation/frame load');` }); // Now safe to navigate win.webContents.loadURL("https://example.com"); If you encounter issues where the script does not seem to run, verify that you have attached to the correct target (especially if dealing with out-of-process iframes) and that the Page domain is enabled specifically for that session ID [2][3].

Citations:


🌐 Web query:

Electron 43 webContents debugger on navigate detach Page.addScriptToEvaluateOnNewDocument

💡 Result:

In Electron, the webContents debugger's attach/detach behavior and the usage of Page.addScriptToEvaluateOnNewDocument are governed by Chromium's DevTools Protocol and Electron's internal debugger implementation [1][2]. 1. Debugger Detach on Navigation: By design, the Electron webContents.debugger does not automatically detach simply because a navigation occurred [2]. Electron's debugger implementation (see shell/browser/api/electron_api_debugger.cc) is designed to maintain the debugging session across primary main-frame navigations by following the RenderFrameHost swaps [2]. Explicit detachment only occurs when debugger.detach() is called, the webContents is destroyed, or DevTools is opened for the same webContents (which forces the previous debugger instance to detach) [1][3]. 2. Page.addScriptToEvaluateOnNewDocument: This command registers a script to be injected into every new document created within the target frame [4]. When using this via the webContents.debugger, the script registration persists as long as the debugging session (the CDPSession) remains active [4]. If the debugger is detached, any registered scripts are cleared by the browser because the session that owned them has been terminated [5]. 3. Practical Considerations: If you experience a "Session closed" or "Target detached" error after navigation, it often implies the debugging session was interrupted or lost [5]. While standard navigation does not trigger a detach, certain lifecycle events—or errors in handling RenderFrameHost changes—could theoretically interrupt the session [2][6]. Ensure that Page.enable is called before sending other commands, as missing domain enablement is a common cause for protocol-related failures [7]. If you need scripts to persist regardless of debugger state, consider Electron's webContents.preload scripts or the did-create-window / did-frame-finish-load events instead.

Citations:


🌐 Web query:

Chromium WebContents navigation attach debugger Page.addScriptToEvaluateOnNewDocument initial script drops CDP command before first commit

💡 Result:

The Chromium Page.addScriptToEvaluateOnNewDocument command is designed to inject scripts into every frame upon creation, specifically before the frame's own scripts load [1]. When issues arise—such as scripts failing to execute, being dropped, or racing against other commands during early navigation stages—they typically stem from the timing of execution context creation [2][3]. Key Technical Context: 1. Context Timing and Races: Because Page.addScriptToEvaluateOnNewDocument registers a "preload" script, it relies on the browser creating a new execution context to trigger the evaluation [2][3]. If a navigation commit occurs or a frame is created and another command (like Runtime.evaluate) is issued simultaneously, the script may not have been evaluated yet, leading to race conditions where subsequent commands execute before the preload script [4]. 2. Frame/Navigation Edge Cases: Historically, Chromium had issues where certain navigation events (e.g., iframe creation or cancellations via document.open) failed to trigger the required isolated world or execution context creation [2][3]. This prevented the preload script from being evaluated [2][3]. Patches have been implemented to ensure these worlds are created whenever the main execution context is established [2]. 3. Debugger Attachment and "First Commit": If you are attaching a debugger, the browser may be in an initial empty document state. There is a distinction between the "initial" state and the "real" document state. Chromium developers have noted that forcing context evaluation in initial empty documents can sometimes conflict with other components (like GuestView), which historically caused some commands to be skipped or fail in those early stages [3][5]. 4. Mitigation/Workarounds: - Ensure the debugger has fully enabled the necessary domains (e.g., Runtime.enable, Page.enable) before initiating navigation [6]. - If you need to ensure a script runs in contexts that might already exist or are being created during a transition, you can use the runImmediately parameter (if supported by your target version) to attempt evaluation in existing contexts [7]. - If you encounter hangs or drops, ensure your automation framework properly awaits navigation events (e.g., waiting for the load event or specific navigation lifecycle milestones) before attempting to interact with the page via Runtime commands, as this guarantees the Page.addScriptToEvaluateOnNewDocument script has had the opportunity to run [4][6]. If you are experiencing specific command drops, it is recommended to verify if you are hitting an edge case related to iframe lifecycle or if your automation is simply racing the browser's context initialization [4][5]. Checking if the issue persists when using runImmediately for existing contexts is a common troubleshooting step [7].

Citations:


🌐 Web query:

Electron 43 webContents debugger sendCommand returns Promise if debugger not attached Page.addScriptToEvaluateOnNewDocument

💡 Result:

In Electron 43, the webContents.debugger.sendCommand method always returns a Promise that resolves with the command's response or rejects if the command fails [1][2]. If the debugger is not attached, the call will fail and the returned Promise will be rejected with an error (e.g., "No target available" or a similar error indicating the debugger is not active) [3]. The sendCommand method requires that the debugger be successfully attached to the target via webContents.debugger.attach() before any commands are executed [1][4]. Regarding Page.addScriptToEvaluateOnNewDocument: This is a method of the Chrome DevTools Protocol (CDP), not a direct method on the Electron debugger object [1][5]. To use it, you must send it as a command via webContents.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', params) [1][3]. Important considerations when using Page.addScriptToEvaluateOnNewDocument in Electron: 1. Prerequisite: You must first enable the Page domain by calling Page.enable before you can successfully use Page.addScriptToEvaluateOnNewDocument [6]. 2. Functionality: This command instructs the browser to evaluate the provided script in every frame upon creation, before any other scripts are loaded [5]. 3. Limitations: If the debugger is not attached, the sendCommand call will fail as described above [3]. Additionally, note that this CDP method may not consistently apply to iframes created via certain dynamic methods (like srcdoc or document.open) depending on the underlying Chromium version's behavior [7][8]. Top results: [1][3][5][6]

Citations:


🌐 Web query:

site:github.com/electron/electron Page.addScriptToEvaluateOnNewDocument debugger runs immediately existing pages

💡 Result:

The Chrome DevTools Protocol (CDP) method Page.addScriptToEvaluateOnNewDocument is designed to register a script that will be automatically evaluated in any new document or frame upon creation, specifically before any other scripts are executed in that document [1][2][3]. Crucially, this method does not affect pages that are already loaded or currently active when the command is sent [1][4][5]. It only applies to future navigations or new document creations occurring after the script has been registered [2][6]. If you need to execute JavaScript in a page that is already loaded, you should use Runtime.evaluate via the DevTools debugger session or, in the context of Electron, methods like webContents.executeJavaScript [7][8][9][10]. Because executeJavaScript also runs asynchronously and waits for the page content to be ready if it has not yet loaded, it is typically the correct approach for existing environments [7][8]. If you are using this specifically for debugging purposes and require the debugger to break on the very first line of a page's script, ensure you register the script using Page.addScriptToEvaluateOnNewDocument before initiating the navigation [1]. If the page is already loaded, reloading the page after calling Page.addScriptToEvaluateOnNewDocument will trigger the evaluation of the registered script during the new page load [2][11].

Citations:


🌐 Web query:

Electron debuggers debugger on navigate detach sendCommand Page.addScriptToEvaluateOnNewDocument

💡 Result:

In Electron, when using the webContents.debugger API, navigation events can impact the debugger session [1][2]. Historically, Electron's internal implementation would automatically disconnect and reconnect the debugger whenever the RenderFrameHost changed (which occurs upon navigation), causing the loss of queued protocol messages and resetting the session state [1][2]. Regarding the specific interaction with Page.addScriptToEvaluateOnNewDocument: 1. Persistence Across Navigation: Commands sent via debugger.sendCommand are generally bound to the current DevTools session. If a session is disconnected and reconnected during navigation, settings such as Page.addScriptToEvaluateOnNewDocument may be cleared because the target environment has effectively reset [1][2]. 2. Debugger Stability: Recent improvements in Electron (specifically addressing issues where DevTools network events were dropped during navigation) have moved away from unconditionally disconnecting/reconnecting on every RenderFrameHost change [2]. This should improve the stability of commands like Page.addScriptToEvaluateOnNewDocument across navigations, provided the debugger session remains active [2]. 3. Implementation Detail: Page.addScriptToEvaluateOnNewDocument is a Chrome DevTools Protocol (CDP) method [3]. When you call it via debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: '...' }), the script is registered with the browser. If the debugger session is explicitly detached or lost, that registration is typically lost. If you encounter issues where scripts fail to execute after navigation, ensure your debugger session is not being implicitly detached. You can monitor this by listening for the detach event on your debugger instance [4][5]: win.webContents.debugger.on('detach', (event, reason) => { console.log('Debugger detached:', reason); }); If the debugger is detaching during navigation, you may need to re-issue your Page.addScriptToEvaluateOnNewDocument command after the navigation completes or after re-attaching the debugger [4][5].

Citations:


🌐 Web query:

Electron WebContents debugger sendCommand returns Promise if debugger attaching command not yet attached

💡 Result:

The Electron debugger.sendCommand method returns a Promise regardless of whether the debugger is attached [1][2]. However, if you attempt to use sendCommand while the debugger is not attached, the promise will be rejected [1][2]. According to the official Electron documentation, sendCommand returns a promise that resolves with the command's response or is rejected if the command fails [1][2]. Sending a command without first calling debugger.attach() is considered a failure, resulting in a rejected promise. To correctly use the debugger, you must ensure the debugger is attached to the target webContents before invoking sendCommand [3]. You can verify the attachment status using debugger.isAttached() [3]. Example of correct usage: const { BrowserWindow } = require('electron'); const win = new BrowserWindow; const { debugger: dbg } = win.webContents; async function runDebuggerCommand { try { // 1. Attach the debugger await dbg.attach('1.3'); // 2. Send commands const response = await dbg.sendCommand('Network.enable'); console.log('Command successful', response); // 3. Detach when finished await dbg.detach; } catch (err) { console.error('Debugger operation failed:', err); } } runDebuggerCommand; If you attempt to call sendCommand without attach, or if the attachment fails (for instance, because another debugger or DevTools instance is already attached), the promise returned by sendCommand will reject, and you should handle this error using standard try/catch or .catch() blocks [1][3][2].

Citations:


Register the guard before the first guest navigation.

injectAntiDetection() queues Page.addScriptToEvaluateOnNewDocument after attach(), so it does not wait for the script registration to complete. If the initial URL contains inline window.close(), it can execute before the guard is installed. The dom-ready fallback runs after inline scripts and does not cover that case.

Defer or block initial navigation until the guard registration succeeds. Add an Electron regression page that calls window.close() in its initial inline script.

Comment thread tests/e2e/browser-tab.spec.ts Resolved
@greptile-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a crash caused by a stale webContents pointer surviving guest destruction: link-created tabs that called window.close() were not removed from the reverse webContentsIdByTabId map, so clicking another tab resolved the dead ID and crashed. The fix has two complementary layers.

  • Stale-map cleanup: cleanupGuestPolicyAttachment now deletes the reverse map entry webContentsIdByTabId[tabId] on guest destroyed, guarded by an identity check (=== guestWebContentsId) so a live replacement guest after a renderer-process swap is never evicted.
  • Preload-based window.close guard: A new sandboxed preload (browser-window-close-preload.js) calls contextBridge.executeInMainWorld to install window.close as a non-configurable, non-writable no-op in the page's main world before any inline script runs. Ordinary embedded guests always receive this preload; CLI-created guests signal their intent by stamping a synthetic sentinel file:// URL as the webview preload attribute, which will-attach-webview consumes and removes, allowing native close to pass through.
  • allowWindowClose flag: propagated through createBrowserTab/createBrowserPage option chains, persisted to the workspace session schema, and restored on session hydration so CLI tabs retain their behavior across restarts.

Confidence Score: 5/5

Safe to merge — both the stale-map bug and the premature window.close race are addressed at the correct layers, with no regressions to the existing guest lifecycle.

The two root causes of the crash are directly fixed: the reverse map is now cleaned up on guest destruction with a safe identity guard, and the window.close no-op is installed in the page's main world before any inline script can execute. The allowWindowClose flag is correctly threaded through creation, state, schema, and session restore. The changes are tightly scoped, well-commented, and backed by targeted unit tests and a new Playwright regression covering the exact reported crash scenario.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/main/browser/browser-manager.ts Fixes stale-pointer crash: cleanupGuestPolicyAttachment now removes both forward (tabIdByWebContentsId) and reverse (webContentsIdByTabId) map entries, guarded so a live replacement guest is never evicted; retireStaleGuestWebContents removes the now-redundant duplicate delete.
src/main/window/createMainWindow.ts will-attach-webview now inspects params.preload and webPreferences.preload for the sentinel marker; injects guard preload for ordinary guests, strips marker and allows native close for CLI-allowed guests.
src/preload/browser-window-close-installation.ts Installs window.close as a non-configurable, non-writable no-op via Object.defineProperty with a writable-assignment fallback; silently swallows failures for the already-locked case.
src/preload/browser-window-close.ts Standalone sandboxed preload entry point that calls contextBridge.executeInMainWorld to install the window.close guard in the page's main world before any inline script runs.
src/shared/browser-window-close-policy.ts Defines the synthetic sentinel file:// URL used as a one-time marker to signal CLI-allowed window.close across the renderer→main will-attach-webview boundary.
src/renderer/src/components/browser-pane/browser-page-webview.ts Stamps the sentinel preload URL on the webview element before attach when allowWindowClose is true, consumed and removed by createMainWindow in will-attach-webview.
src/renderer/src/store/slices/browser.ts Propagates allowWindowClose through createBrowserTab/createBrowserPage option chains and through session restore paths for both first and subsequent pages.
src/shared/workspace-session-schema.ts Adds optional allowWindowClose boolean to the browser page Zod schema so CLI tabs restore with their intended close policy across sessions.
tests/e2e/browser-tab.spec.ts Adds two Playwright e2e tests: one proves that a link-created tab calling window.close() does not crash tab switching; the other proves explicitly-allowed tabs can still replace window.close.
electron.vite.config.ts Registers browser-window-close-preload as a separate build entry so the sandboxed preload is emitted as a standalone CJS file without Rollup helper chunks.

Reviews (2): Last reviewed commit: "fix(browser): preserve explicit window c..." | Re-trigger Greptile

Comment thread src/main/window/createMainWindow.ts Resolved
@AmethystLiang

Copy link
Copy Markdown
Contributor

looking into it

@AmethystLiang

Copy link
Copy Markdown
Contributor

thanks for reporting. looking into it

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(browser): prevent window.close guest crashes

* fix(browser): guard close before inline scripts

* fix(browser): preserve explicit window close policy
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]: Main-process SIGSEGV after window.close() in a link-opened embedded browser tab

2 participants