Skip to content

fix(browser): remove unsafe window close bypass - #12040

Merged
nwparker merged 2 commits into
mainfrom
nwparker/browser-close-policy-hardening
Aug 2, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/browser-close-policy-hardening

Conversation

@nwparker

@nwparker nwparker commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Keep the guest lifecycle cleanup and early window.close() guard from fix(browser): prevent window.close guest crashes #11910.
  • Remove the CLI-only guard bypass, its synthetic preload marker, and persisted allowWindowClose state.
  • Apply the guard uniformly to every embedded browser webview and retain focused coverage for link-created and directly created tabs.

ELI5

The first fix installed a child lock so web pages could not accidentally destroy their little browser window inside Orca. It also gave CLI-created tabs a secret key to bypass that lock. Adversarial testing showed the key did not cleanly close the Orca tab: it killed the browser engine underneath while leaving a dead-looking tab behind. That dead tab stayed on screen but every later operation failed with Invalid guestInstanceId.

This PR takes away the unsafe secret key. Every embedded browser tab gets the same child lock. We keep the important part of #11910 that throws away stale pointers when a guest really dies, so the original #11763 crash remains fixed. Removing the synthetic file-URL key also removes the path mechanism that caused the Windows black screen fixed in #12038.

Screenshots

No visual change.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • Electron production bundle (pnpm exec electron-vite build --mode e2e)
  • Added or updated high-quality tests that would catch regressions
  • 283 focused Vitest tests
  • 2 focused Electron E2E tests covering link-created and directly created window.close() attempts
  • Changed-code quality gate
  • 61 reliability-gate manifest checks
  • max-lines ratchet

AI Review Report

The review split #11910 into its independent lifecycle-cleanup and close-policy layers, traced all creation/restoration paths, and tested the claimed CLI self-close behavior instead of relying on the existing replaceability test. Calling native window.close() on a bypassed tab resolved, destroyed its Electron guest, left the <webview> connected, and made the next guest call fail with Invalid guestInstanceId. The bypass was therefore removed while the identity-guarded forward/reverse map cleanup was retained.

Cross-platform review covered macOS, Linux, and Windows Electron preload handling and file-URL semantics. The resulting implementation has no platform-specific marker or path conversion.

Security Audit

The renderer can no longer use a synthetic preload value to opt a guest out of the main-process close policy. will-attach-webview strips any renderer-requested preload and always replaces it with the standalone sandboxed guard after validating the URL and registered partition. Node integration remains disabled, context isolation and sandboxing remain enabled, and no auth, secrets, dependencies, shell commands, or external input formats changed.

Notes

This is a targeted partial revert of #11910, not a full revert. A full revert would reintroduce #11763's stale guest pointer and main-process crash.

@coderabbitai

coderabbitai Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change removes configurable allowWindowClose state from browser tab creation, webview initialization, session restoration, and related tests. Webview attachment now removes renderer-supplied preload values and assigns browser-window-close-preload. Tests verify preload sanitization, guest policy application, omitted close options, legacy-state cleanup, and blocked window.close() behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

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.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the main change: removing the unsafe browser window-close bypass.
Description check ✅ Passed The description includes all required sections and provides clear summaries of behavior, testing, review, security, and platform considerations.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

Caution

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

⚠️ Outside diff range comments (1)
src/renderer/src/store/slices/browser.ts (1)

339-360: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Remove the legacy field during session hydration.

hydrateBrowserSession spreads each persisted page at Lines 1647-1654. A session saved before this change can still contain allowWindowClose, so restoration keeps that field in live browser-page state. Strip the field during hydration and add a legacy-session migration test.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 65593c98-d863-40fa-b744-386bb11a70dd

📥 Commits

Reviewing files that changed from the base of the PR and between 742024b and aa0c07d.

📒 Files selected for processing (12)
  • 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
💤 Files with no reviewable changes (7)
  • src/shared/types.ts
  • src/shared/workspace-session-schema.ts
  • src/shared/browser-window-close-policy.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/components/browser-pane/browser-page-webview.ts
  • src/renderer/src/components/browser-pane/BrowserPane.tsx
  • src/renderer/src/components/browser-pane/BrowserPane.webview-preferences.test.ts

@greptile-apps

greptile-apps Bot commented Aug 2, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR removes the unsafe CLI-only bypass that allowed embedded browser tabs to opt out of the window.close() guard. The uniform guard — applied via a sandboxed preload using Object.defineProperty with writable: false — now covers every webview without exception, eliminating both the Invalid guestInstanceId crash path and the Windows black-screen side effect caused by the synthetic file-URL marker.

  • Bypass removed end-to-end: The synthetic BROWSER_WINDOW_CLOSE_ALLOWED_PRELOAD constant, its file-URL marker, the allowWindowClose option on createBrowserTab/Page, and the matching BrowserPage type field and Zod schema field are all deleted.
  • Legacy session migration: The in-memory hydration path explicitly destructures and discards allowWindowClose from persisted pages, covering the case where schema-level stripping is bypassed by in-memory callers.
  • Test coverage: A new unit test verifies that hydrating a legacy session strips the field; two E2E tests cover link-created and directly-created tabs, both now expecting window.close() to be blocked and the tab to remain fully usable.

Confidence Score: 5/5

Safe to merge — the change tightens security uniformly with no new code paths, and the legacy-migration guard handles pre-existing persisted state cleanly.

Every embedded webview now receives the same close guard unconditionally. The old bypass path has been deleted across the renderer type system, store slice, IPC handler, schema, and shared constant. Legacy persisted sessions are handled by explicit destructuring during hydration. Both the link-created and direct-creation E2E paths are covered by focused tests that verify the guard cannot be overridden by page scripts.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/main/window/createMainWindow.ts Removes the bypass-marker check and unconditionally installs browser-window-close-preload.js on every webview; fileURLToPath import is also removed cleanly.
src/shared/browser-window-close-policy.ts File deleted — the synthetic C:/orca_window_close_allowed file-URL marker is entirely removed, eliminating both the bypass and its Windows path-conversion issue.
src/renderer/src/components/browser-pane/browser-page-webview.ts Removes allowWindowClose option and the conditional preload attribute injection; webview creation is now uniform for all tabs.
src/renderer/src/store/slices/browser.ts Strips allowWindowClose from type definitions, buildBrowserPage, createBrowserTab/Page options, and adds explicit legacy-field destructuring in the in-memory hydration path to strip pre-existing persisted values.
src/shared/workspace-session-schema.ts Removes allowWindowClose from the Zod schema; sessions persisted with this field will have it stripped at the schema-parse boundary.
tests/e2e/browser-tab.spec.ts Replaces the allowed CLI tab test with a directly created tab blocks window.close test; both link-created and direct creation paths are now covered.
src/renderer/src/store/slices/store-session-cascades.test.ts Adds a regression test that hydrating a legacy session with allowWindowClose: true strips the field from the resulting in-memory state.
src/renderer/src/hooks/useIpcEvents.ts Removes allowWindowClose: true from the CLI/automation tab-create path; all tabs now get the same security posture.
src/renderer/src/components/browser-pane/BrowserPane.tsx Removes allowWindowClose forwarding to ensureBrowserPageWebview; one-line change with no other effects.
src/shared/types.ts Removes allowWindowClose?: boolean from BrowserPage; no other type changes.

Reviews (2): Last reviewed commit: "test(browser): strip legacy close policy..." | Re-trigger Greptile

@nwparker

nwparker commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the legacy hydration finding in d79eaa0: hydration now strips allowWindowClose even when callers pass pre-migration in-memory objects that bypass schema parsing, with a focused regression test.

@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: Pro Plus

Run ID: 339c7cec-061c-420a-9440-5da89ced97c2

📥 Commits

Reviewing files that changed from the base of the PR and between aa0c07d and d79eaa0.

📒 Files selected for processing (2)
  • src/renderer/src/store/slices/browser.ts
  • src/renderer/src/store/slices/store-session-cascades.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/store/slices/browser.ts

Comment on lines +768 to +770
expect(store.getState().browserPagesByWorkspace['browser-1']?.[0]).not.toHaveProperty(
'allowWindowClose'
)

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Locate file and inspect relevant test and surrounding behavior"
fd -a 'store-session-cascades.test.ts' .
file="$(fd 'store-session-cascades.test.ts' . | head -n1)"
if [ -n "${file:-}" ]; then
  wc -l "$file"
  echo "--- relevant lines 720-790 ---"
  sed -n '720,790p' "$file" | nl -ba -v720
fi

echo "--- package/test framework snippets if visible nearby ---"
rg -n "toHaveProperty|describe|it\\(|toHaveProperty\\(" "$file" || true

echo "--- search allowWindowClose related hydration/tests ---"
rg -n "allowWindowClose|browserPagesByWorkspace|hydration|persist|hydrate" src/renderer/src/store -S

Repository: stablyai/orca

Length of output: 434


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="./src/renderer/src/store/slices/store-session-cascades.test.ts"

echo "--- lines 720-790 ---"
sed -n '720,790p' "$file" | awk '{printf "%7d  %s\n", NR+719, $0}'

echo "--- package/test framework clues ---"
rg -n "toHaveProperty|`@testing-library/react`|Testing Library|Jest|vitest" package.json package-lock.json pnpm-lock.yaml yarn.lock 2>/dev/null || true

echo "--- search allowWindowClose and related slice ---"
rg -n "describe\\(|it\\(|browserPagesByWorkspace|allowWindowClose|hydrate|persist" "$file" -S || true

Repository: stablyai/orca

Length of output: 15518


🌐 Web query:

Vitest expect not toHaveProperty undefined false positive assert property

💡 Result:

In Vitest, toHaveProperty checks for the existence of a property on an object and, optionally, performs a deep equality check on its value [1][2][3]. If you encounter a situation where expect(obj).not.toHaveProperty('key') fails or behaves unexpectedly when the property is set to undefined, it is likely due to how the matcher distinguishes between a key that is missing versus a key that is present but holds an undefined value [4]. Key behaviors to understand: 1. Existence vs. Value: toHaveProperty is designed to verify that a path exists in the object [1][3]. If a property exists but its value is undefined (e.g., { myKey: undefined }), toHaveProperty('myKey') will return true because the key is present [4]. Consequently, not.toHaveProperty('myKey') will fail [1][2]. 2. Property Path Parsing: If your property name contains special characters like dots (.) or brackets ([]), Vitest may attempt to parse them as deep property paths [1][4][3]. If Vitest interprets the name incorrectly, it may fail to find the property, leading to unexpected assertion results [5]. You can avoid this by wrapping the key in an array, which tells Vitest to treat the entire string as a single, literal key path (e.g., expect(obj).toHaveProperty(['my.complex.key'])) [1][3]. 3. Recommended Workarounds: - If you need to verify that a key is completely absent (not just set to undefined), you can use the in operator in a standard JavaScript assertion: expect('key' in obj).toBe(false). - If you want to check that a property exists and is not undefined, use: expect(obj.key).toBeDefined(). - If you want to check that a property exists and is explicitly undefined, use: expect(obj).toHaveProperty('key') followed by expect(obj.key).toBeUndefined() [3][6]. If you believe you are seeing a false positive caused by a bug, verify if the property name contains characters that might conflict with path resolution, and consider using the array notation workaround [5]. Ensure you are on the latest version of Vitest, as several issues regarding toHaveProperty property resolution have been addressed in recent releases [5][7].

Citations:


🌐 Web query:

site:github.com/vitest-dev/vitest packages/expect/src/jest-expect.ts toHaveProperty undefined null

💡 Result:

In the context of the Vitest framework (which maintains the packages/expect/src/jest-expect.ts implementation [1][2][3]), using .toHaveProperty() when the subject is null or undefined has historically caused issues, but has been addressed in recent updates [4]. Historically, calling expect(null).toHaveProperty('key') or expect(undefined).toHaveProperty('key') would throw a TypeError because the internal implementation attempted to call Object.hasOwn() on the nullish subject before verifying its existence [4]. If you are encountering errors or unexpected behavior with null or undefined values using toHaveProperty, please note the following: 1. Handling of Nullish Subjects: Recent fixes in Vitest have introduced guards to handle nullish subjects gracefully [4]. Previously, these calls would crash with an internal TypeError [4]. 2. Property Value Assertion: When toHaveProperty is used with a value argument (e.g., expect(obj).toHaveProperty('key', value)), the matcher performs a deep equality check [5][6]. If the property exists but its value is null or undefined, the assertion will behave according to standard equality rules. 3. Distinguishing Existence from Value: toHaveProperty is designed to assert that a path exists in an object [5][6]. If you specifically need to verify that a property is null or undefined, you should first assert that the property exists and then check its value: - expect(obj).toHaveProperty('key'); - expect(obj.key).toBe(null); // or.toBeUndefined If you are using an older version of Vitest and experiencing crashes with nullish subjects, it is recommended to update the library, as these issues were tracked and resolved under bug reports regarding improper handling of nullish subjects [4].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- inspect installed vitest expect source if available ---"
node -e "try { const fs = require('fs'); const pkg = require.resolve('`@vitest/expect/package.json`'); console.log(pkg); const text = fs.readFileSync(pkg.replace('package.json','src/assertions/toEqual.ts').replace('../expect','expect'), 'utf8'); console.log(text.slice(0,3000)); } catch (e) { console.log(e.type || e.code + ': ' + e.message); }" 2>/dev/null || true

echo "--- installed vitest expect toHaveProperty implementation ---"
node - <<'JS'
try {
  const path = require('path');
  const pkgJson = require.resolve('`@vitest/expect/package.json`');
  const root = path.dirname(pkgJson);
  const files = [
    path.join(root, 'dist/index.js'),
    path.join(root, 'dist/chunks/index.js'),
    path.join(root, 'dist/assertions/toEqual.js'),
  ];
  let found;
  for (const file of files) {
    if (require('fs').existsSync(file)) {
      found = file;
      const text = require('fs').readFileSync(file, 'utf8');
      const idx = text.indexOf('toHaveProperty');
      console.log('FILE', file);
      console.log(text.slice(Math.max(0, idx - 800), idx + 1200));
      break;
    }
  }
  if (!found) throw new Error('source not found');
} catch (e) {
  console.log('Could not inspect local vitest source:', e.message);
}
JS

echo "--- inspect source package lock pinned version ---"
python3 - <<'PY'
import re, pathlib
p=next(pathlib.Path().glob('pnpm-lock.yaml'), None)
if not p: raise SystemExit(0)
s=p.read_text()
m=re.search(r'/vitest@[\d\.\w]+.*?:\n[ \t]{8}version: ([\d\.\w-]+)', s)
print('pinned vitest version:', m.group(1) if m else '<not found>')
PY

Repository: stablyai/orca

Length of output: 601


🌐 Web query:

Vitest expect.toHaveProperty undefined not toHaveProperty implementation

💡 Result:

In Vitest, toHaveProperty is designed to check for the existence of a property at a given key path [1][2]. If you are encountering an "undefined" error or unexpected behavior, it is typically because the matcher is strictly verifying whether the property exists on the object, and in some cases, how the property name is being parsed [3][4]. Implementation Details: Vitest's toHaveProperty matcher functions by checking if the property exists on the object and, optionally, if the value matches the provided expected value using deep equality [1][4]. Internally, it handles dot notation for deep referencing by parsing strings, which can sometimes lead to issues if property names themselves contain dots or brackets [1][5][4]. Common Causes for Unexpected Behavior: 1. Property Name Parsing: Because the matcher parses strings like 'a.b' as nested properties, property names that contain actual dots or brackets might be misinterpreted [1][4]. To treat a string as a literal key without deep parsing, you can wrap it in an array: expect(obj).toHaveProperty(['my.property']) [1][4]. 2. Strict Existence: The matcher checks for the existence of the property itself [1][4]. If a property is defined but set to undefined, or if a path does not resolve to an existing key, the assertion may fail, sometimes reporting that it expected the property to exist but found undefined [3][4]. 3. Workaround: If toHaveProperty is not behaving as expected with complex property names, a standard alternative is to access the property directly and use other matchers, such as: expect(obj['my.property']).toBeDefined [3]. If you are seeing an error message specifically mentioning "expected {... } to have property undefined," it often indicates that the matcher failed to resolve the path provided [3]. Ensure the path matches the structure of your object exactly, using array notation for keys that contain special characters [1][4].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail
echo "--- exact pnpm lock vitest entries ---"
grep -nE '(^  vitest@|^  /vitest@|version:)' pnpm-lock.yaml | grep -A1 -B1 'vitest' || true

echo "--- read only JS probe of current runtime vitest toHaveProperty if dependency installed ---"
node - <<'JS'
const fs = require('fs');
const path = require('path');
let pkg;
try {
  pkg = require.resolve('`@vitest/expect/package.json`');
} catch (e) {
  console.log('no local `@vitest/expect`');
  process.exit(0);
}
const root = path.dirname(pkg);
console.log('root', root);
console.log('files', fs.readdirSync(root).slice(0, 80).join(', '));
for (const file of fs.readdirSync(root)) {
  if (file.endsWith('.js') || file.endsWith('.mjs') || file === 'dist') {
    console.log('candidate', file);
  }
}
JS

Repository: stablyai/orca

Length of output: 669


🌐 Web query:

github vitest 4.1.5 packages/expect/src/assertions.ts toHaveProperty

💡 Result:

In Vitest version 4.1.5, the implementation of the toHaveProperty matcher is located within the packages/expect/src/jest-expect.ts file [1][2]. This matcher is designed to assert whether an object contains a specific property [3]. It supports both simple keys and deep referencing using dot notation (e.g., 'a.b.c') or arrays containing the key path (e.g., ['a', 'b', 'c']) [3][4]. The source code logic for toHaveProperty functions as follows [2]: 1. Normalization: If an array is provided as the property path, it joins the segments into a string, ensuring that array indices and special characters are handled correctly [2][4]. 2. Value Retrieval: It attempts to retrieve the value using Object.hasOwn for direct properties or utils.getPathInfo for deep paths [2]. 3. Assertion: It checks if the property exists and, if an expected value is provided, performs a deep equality check using jestEquals [2]. 4. Feedback: It provides descriptive error messages if the assertion fails, including information about the expected property name and, if applicable, the expected vs. actual values [2]. Vitest v4.1.5 was released on April 21, 2026 [5][6]. While the specific file path in your query was packages/expect/src/assertions.ts, the actual implementation of this matcher resides in packages/expect/src/jest-expect.ts within the Vitest repository [1][2].

Citations:


🌐 Web query:

github.com/vitest-dev/vitest packages/expect/src/jest-expect.ts v4.1.5 toHaveProperty Object.hasOwn

💡 Result:

In the vitest codebase, specifically within packages/expect/src/jest-expect.ts, the toHaveProperty matcher uses Object.hasOwn to check if a property exists directly on an object [1][2][3]. This implementation pattern, which replaced older uses of Object.prototype.hasOwnProperty.call [4], is designed to ensure that the matcher correctly identifies own properties before potentially falling back to deep path resolution via utils.getPathInfo [1][2][3]. The relevant section of the code in version v4.1.5 (and surrounding versions) typically appears as follows [1][3]: const getValue = => { const hasOwn = Object.hasOwn( actual, propertyName,) if (hasOwn) { return { value: actual[propertyName], exists: true } } return utils.getPathInfo(actual, propertyName) } This change is part of a broader migration within the vitest repository to utilize modern ES2022 language features, such as Object.hasOwn, instead of the older prototype method call [4].

Citations:


🌐 Web query:

github.com/vitest-dev/vitest v4.1.5 packages/expect/src/jest-expect.ts defineProperty toHaveProperty null undefined

💡 Result:

In Vitest v4.1.5, the file packages/expect/src/jest-expect.ts is responsible for defining Jest-compatible matchers within Vitest's assertion framework [1][2]. While this file contains the registration logic for matchers using Chai's utility functions, it does not contain specific logic that filters or rejects the use of null or undefined when using Object.defineProperty to modify objects that are later inspected with toHaveProperty. The matcher toHaveProperty, which is part of the Jest API surface provided by Vitest, relies on standard JavaScript property access or checks for property existence [3]. When you use Object.defineProperty to set a property on an object to null or undefined, the behavior in Vitest's toHaveProperty matcher follows standard JavaScript behavior: 1. Property Existence: The matcher checks if the property exists on the object [3]. If the property was defined using Object.defineProperty (even with a value of null or undefined), it is considered "present" on the object. 2. Value Matching: If you use toHaveProperty with a second argument (the expected value), the matcher will compare the value defined by Object.defineProperty against your expectation [3]. Because null and undefined are valid JavaScript values, the matcher will successfully confirm the property exists and matches the expected null or undefined value. There is no code in packages/expect/src/jest-expect.ts that specifically handles or prevents null or undefined values when used in conjunction with Object.defineProperty or toHaveProperty [1][2]. These matchers are designed to work with the underlying JavaScript object structure, meaning any property created via Object.defineProperty is treated as a standard property by the assertion engine [3].

Citations:


🌐 Web query:

"@vitest/expect@4.1.5" "toHaveProperty" "undefined"

💡 Result:

In Vitest (including version 4.1.5), the toHaveProperty matcher is designed to assert that an object contains a specific property [1][2]. When you receive an "expected... to have property undefined" error message, it typically indicates that the assertion failed because the property could not be found on the object, not that the property exists and is set to the value undefined [3][4]. The toHaveProperty matcher internally checks for property existence using Object.hasOwn or similar path-resolution utilities [3]. If the key path does not exist on the object, the matcher fails and reports that it expected the object to have the property [3]. If you encounter unexpected failures with this matcher, consider the following: 1. Property Path Interpretation: Vitest interprets dot-notation strings (e.g., 'a.b') as nested property paths [1][5]. If your property name actually contains a dot or other special characters (like hyphens), the matcher may misinterpret it as a path [4]. To treat a string literally as a single key, wrap the key in an array, such as expect(obj).toHaveProperty(['my.key']) [1][2]. 2. Debugging Existence: If you are unsure why a property is not being detected, you can verify its existence manually before the assertion using expect(obj.property).toBeDefined or expect(obj).toHaveProperty('key') [4]. 3. Deep Equality: If you provide a second argument to toHaveProperty, Vitest performs deep equality between the actual property value and the expected value [1][2]. If you specifically need to assert that a property exists and is explicitly set to undefined, you may need a different approach, such as: expect(obj).toHaveProperty('key'); expect(obj.key).toBeUndefined;

Citations:


Make the hydration assertion non-vacuous.

?.[0] can return undefined; assert the hydrated page exists before asserting that allowWindowClose was dropped.

Suggested test adjustment
-    expect(store.getState().browserPagesByWorkspace['browser-1']?.[0]).not.toHaveProperty(
-      'allowWindowClose'
-    )
+    const hydratedPage = store.getState().browserPagesByWorkspace['browser-1']?.[0]
+    expect(hydratedPage).toMatchObject({ id: 'page-1' })
+    expect(hydratedPage).not.toHaveProperty('allowWindowClose')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
expect(store.getState().browserPagesByWorkspace['browser-1']?.[0]).not.toHaveProperty(
'allowWindowClose'
)
const hydratedPage = store.getState().browserPagesByWorkspace['browser-1']?.[0]
expect(hydratedPage).toMatchObject({ id: 'page-1' })
expect(hydratedPage).not.toHaveProperty('allowWindowClose')

@nwparker
nwparker merged commit 4f963fd into main Aug 2, 2026
46 checks passed
@nwparker
nwparker deleted the nwparker/browser-close-policy-hardening branch August 2, 2026 04:08
gal064 pushed a commit to gal064/orca that referenced this pull request Aug 3, 2026
* fix(browser): remove unsafe window close bypass

* test(browser): strip legacy close policy on hydration

(cherry picked from commit 4f963fd)
Zhushuaijiang pushed a commit to Zhushuaijiang/orca that referenced this pull request Aug 4, 2026
…urce

The origin/main merge kept branch-side files that stablyai#12040 deleted:
browser-window-close-preload.{ts,test.ts} imported the removed shared
browser-window-close-policy module, and createMainWindow kept the dead
_allowWindowClose computation. UpdateSource hardcoded 'hourly' and lost
'adhoc' when the merge restored upstream release-channel.ts, breaking
the pinned-build assignment in updater.ts. UpdateSource now derives
from DedicatedRepoChannel again, keeping the branch's 'dfhis' origin.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(browser): remove unsafe window close bypass

* test(browser): strip legacy close policy on hydration
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.

1 participant