From 12efb383f2bf2e586aeaecccfa35f0f290075e68 Mon Sep 17 00:00:00 2001 From: Aiden Bai Date: Fri, 1 May 2026 07:13:51 -0700 Subject: [PATCH 1/8] fix(scan): use "could have" instead of "could of" in optimize prompts Closes #403. --- packages/scan/src/web/views/notifications/optimize.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/scan/src/web/views/notifications/optimize.tsx b/packages/scan/src/web/views/notifications/optimize.tsx index 7b26c0bf..8be7131a 100644 --- a/packages/scan/src/web/views/notifications/optimize.tsx +++ b/packages/scan/src/web/views/notifications/optimize.tsx @@ -147,7 +147,7 @@ We also have lower level information about react components, such as their rende ${formattedReactData} -You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could of been memoized to avoid computation +You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could have been memoized to avoid computation It's also important to remember if a component had no props/state/context change, and it was memoized, it would not render. So the flow should be: - find the most expensive components @@ -197,7 +197,7 @@ We also have lower level information about react components, such as their rende ${formattedReactData} -You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could of been memoized to avoid computation +You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could have been memoized to avoid computation It's also important to remember if a component had no props/state/context change, and it was memoized, it would not render. So the flow should be: - find the most expensive components @@ -235,7 +235,7 @@ We also have lower level information about react components, such as their rende ${formattedReactData} -You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could of been memoized to avoid computation +You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could have been memoized to avoid computation It's also important to remember if a component had no props/state/context change, and it was memoized, it would not render. So a flow we can go through is: - find the most expensive components @@ -312,7 +312,7 @@ We also have lower level information about react components, such as their rende ${formattedReactData} -You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could of been memoized to avoid computation +You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could have been memoized to avoid computation It's also important to remember if a component had no props/state/context change, and it was memoized, it would not render. So a flow we can go through is: - find the most expensive components From 05b06f02826335dee0aaba38b51cf1d426e5b722 Mon Sep 17 00:00:00 2001 From: Aiden Bai Date: Fri, 1 May 2026 07:13:57 -0700 Subject: [PATCH 2/8] chore(scan): lower published bundle target from esnext to es2019 Older webpack/babel-loader configs without @babel/preset-env for ES2020 fail to parse the optional chaining (\`?.\`) and nullish coalescing (\`??\`) that esbuild emits at \`target: esnext\`. Targeting es2019 transpiles those operators down so the same bundles parse in those toolchains without forcing every consumer to add a babel transform. Verified the published \`auto.global.js\`, \`index.mjs\`, \`index.js\`, and \`lite/index.mjs\` contain 0 occurrences of \`?.\` after the rebuild. Closes #287, #336. --- packages/scan/tsup.config.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/scan/tsup.config.ts b/packages/scan/tsup.config.ts index 09bde403..113c591b 100644 --- a/packages/scan/tsup.config.ts +++ b/packages/scan/tsup.config.ts @@ -92,7 +92,10 @@ export default defineConfig([ clean: false, sourcemap: false, format: ['iife'], - target: 'esnext', + // Target ES2019 (no `?.`, no `??`) so older babel-loader configs without + // `@babel/preset-env` for optional chaining can still parse the bundle + // (#287, #336). + target: 'es2019', platform: 'browser', treeshake: true, dts: true, @@ -130,7 +133,7 @@ export default defineConfig([ clean: false, sourcemap: false, format: ['cjs', 'esm'], - target: 'esnext', + target: 'es2019', platform: 'browser', // FIXME: tree shaking removes use client directive // Info: vercel analytics does the same thing- https://github.com/vercel/analytics/blob/main/packages/web/tsup.config.js From 07015a9eb3b092ec7a9955cc5f027c361c30fd6b Mon Sep 17 00:00:00 2001 From: Aiden Bai Date: Fri, 1 May 2026 07:14:46 -0700 Subject: [PATCH 3/8] fix(scan): correct production-environment detection + scaffold new options MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Production-environment detection (#402) --------------------------------------- \`getIsProduction()\` cached \`true\` as soon as any single registered React renderer reported a production build. Modern dev tooling commonly mounts multiple roots from different React copies — the Next.js dev overlay ships a production React build alongside the user's dev React, and the extra production renderer was enough to disable React Scan entirely. The fix preserves a permanent \`false\` cache once a non-production renderer is observed, but no longer caches \`true\` — a later dev renderer can still flip the result, even after the production overlay registered first. Adds a unit-test matrix that mocks bippy's \`getRDTHook\` / \`detectReactBuildType\` to lock the contract: - empty renderers -> null (don't know yet) - all production -> true - mixed -> false - production-then-dev (regression guard) -> flips to false - dev-then-anything -> stays false (cache) This likely also resolves #404 / #400 where the documented workaround is \`react-scan/all-environments\`, which bypassed the same broken check. New Options scaffolding ----------------------- Adds \`safeArea\` and \`useOffscreenCanvasWorker\` to the Options interface, plus runtime validation. The actual wiring is in the follow-up commit. --- .../scan/src/core/get-is-production.test.ts | 74 +++++++++++++++++++ packages/scan/src/core/index.ts | 61 +++++++++++++-- 2 files changed, 128 insertions(+), 7 deletions(-) create mode 100644 packages/scan/src/core/get-is-production.test.ts diff --git a/packages/scan/src/core/get-is-production.test.ts b/packages/scan/src/core/get-is-production.test.ts new file mode 100644 index 00000000..d56971e0 --- /dev/null +++ b/packages/scan/src/core/get-is-production.test.ts @@ -0,0 +1,74 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +interface FakeRenderer { + bundleType?: number; + rendererPackageName?: string; +} + +interface FakeRDTHook { + renderers: Map; +} + +const sharedHook: FakeRDTHook = { renderers: new Map() }; + +vi.mock('bippy', () => { + return { + detectReactBuildType: (renderer: FakeRenderer) => + renderer.bundleType === 0 ? 'production' : 'development', + getRDTHook: () => sharedHook, + getType: () => null, + isInstrumentationActive: () => false, + }; +}); + +const importFreshGetIsProduction = async () => { + vi.resetModules(); + const mod = (await import('~core/index')) as typeof import('~core/index'); + return mod.getIsProduction; +}; + +beforeEach(() => { + sharedHook.renderers.clear(); +}); + +describe('getIsProduction', () => { + it('returns null when no React renderer has registered yet', async () => { + const getIsProduction = await importFreshGetIsProduction(); + expect(getIsProduction()).toBeNull(); + }); + + it('returns true when every registered renderer is production', async () => { + const getIsProduction = await importFreshGetIsProduction(); + sharedHook.renderers.set(1, { bundleType: 0 }); + expect(getIsProduction()).toBe(true); + }); + + it('returns false when at least one renderer is non-production', async () => { + const getIsProduction = await importFreshGetIsProduction(); + sharedHook.renderers.set(1, { bundleType: 0 }); + sharedHook.renderers.set(2, { bundleType: 1 }); + expect(getIsProduction()).toBe(false); + }); + + it('does not cache `true` — a later dev renderer flips the result', async () => { + // Regression guard for #402: the Next.js dev overlay registers a + // production React build first, then the user's dev React arrives a + // tick later. Caching `true` on the first call would lock us out. + const getIsProduction = await importFreshGetIsProduction(); + sharedHook.renderers.set(1, { bundleType: 0 }); + expect(getIsProduction()).toBe(true); + + sharedHook.renderers.set(2, { bundleType: 1 }); + expect(getIsProduction()).toBe(false); + }); + + it('caches `false` permanently once a dev renderer has been seen', async () => { + const getIsProduction = await importFreshGetIsProduction(); + sharedHook.renderers.set(1, { bundleType: 1 }); + expect(getIsProduction()).toBe(false); + + sharedHook.renderers.clear(); + sharedHook.renderers.set(2, { bundleType: 0 }); + expect(getIsProduction()).toBe(false); + }); +}); diff --git a/packages/scan/src/core/index.ts b/packages/scan/src/core/index.ts index 1a07399e..d4b75b00 100644 --- a/packages/scan/src/core/index.ts +++ b/packages/scan/src/core/index.ts @@ -14,6 +14,7 @@ import styles from '~web/assets/css/styles.css'; import { createToolbar } from '~web/toolbar'; import { IS_CLIENT } from '~web/utils/constants'; import { readLocalStorage, saveLocalStorage } from '~web/utils/helpers'; +import { parseSafeAreaOption } from '~web/utils/parse-safe-area-option'; import type { States } from '~web/views/inspector/utils'; import type { ChangeReason, @@ -126,6 +127,33 @@ export interface Options { */ allowInIframe?: boolean; + /** + * Distance (in pixels) the toolbar keeps from the viewport edges. Useful + * when other dev overlays (e.g. the Next.js dev indicator) sit in the same + * corner. Pass a single number to inset all edges, or an object to inset + * edges individually. + * + * @default 24 + */ + safeArea?: + | number + | { + top?: number; + right?: number; + bottom?: number; + left?: number; + }; + + /** + * Render outline overlays via an OffscreenCanvas + Web Worker. Disable when + * a strict Content-Security-Policy without `worker-src blob:` would + * otherwise reject the blob worker — React Scan automatically falls back + * to main-thread rendering. + * + * @default true + */ + useOffscreenCanvasWorker?: boolean; + /** * Should react scan log internal errors to the console. * @@ -277,6 +305,7 @@ const validateOptions = (options: Partial): Partial => { case 'dangerouslyForceRunInProduction': case 'showFPS': case 'allowInIframe': + case 'useOffscreenCanvasWorker': if (typeof value !== 'boolean') { errors.push(`- ${key} must be a boolean. Got "${value}"`); } else { @@ -292,6 +321,15 @@ const validateOptions = (options: Partial): Partial => { validOptions[key] = value as 'slow' | 'fast' | 'off'; } break; + case 'safeArea': { + const parsed = parseSafeAreaOption(value); + if (parsed.ok) { + validOptions.safeArea = parsed.value; + } else { + errors.push(parsed.error); + } + break; + } case 'onCommitStart': if (typeof value !== 'function') { errors.push(`- ${key} must be a function. Got "${value}"`); @@ -411,21 +449,30 @@ export const setOptions = (userOptions: Partial) => { export const getOptions = () => ReactScanInternals.options; -// we only need to run this check once and will read the value in hot path let isProduction: boolean | null = null; let rdtHook: ReturnType; export const getIsProduction = () => { - if (isProduction !== null) { - return isProduction; + // Once we've definitively seen a non-production renderer, the app is "dev" + // forever — cache that and short-circuit. We deliberately do NOT cache the + // `true` result: tools like the Next.js dev overlay register a production + // React renderer alongside the user's dev React, and the dev renderer may + // arrive on a later tick. Caching `true` would lock out that flip. + if (isProduction === false) { + return false; } rdtHook ??= getRDTHook(); - for (const renderer of rdtHook.renderers.values()) { + const renderers = Array.from(rdtHook.renderers.values()); + if (renderers.length === 0) { + return null; + } + for (const renderer of renderers) { const buildType = detectReactBuildType(renderer); - if (buildType === 'production') { - isProduction = true; + if (buildType !== 'production') { + isProduction = false; + return false; } } - return isProduction; + return true; }; export const start = () => { From cb8e2cb275ec4e9e227ce6695dc6aac69d6711b3 Mon Sep 17 00:00:00 2001 From: Aiden Bai Date: Fri, 1 May 2026 07:15:05 -0700 Subject: [PATCH 4/8] fix(scan): make OffscreenCanvas worker CSP-safe + add opt-out A Content-Security-Policy of \`worker-src 'self'\` rejects the blob: worker React Scan creates for OffscreenCanvas rendering. The fallback to main-thread rendering already worked, but the failure path \`console.warn\`'d on every page load. Changes: - \`useOffscreenCanvasWorker: false\` (new Options field) lets users with strict CSP skip the attempt entirely. - The catch block now suppresses CSP-style failures unless the user set \`_debug: 'verbose'\`, so the console isn't spammed for a fallback that's working as designed. Closes #372. --- packages/scan/src/new-outlines/index.ts | 33 ++++++++++++++++++------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/packages/scan/src/new-outlines/index.ts b/packages/scan/src/new-outlines/index.ts index d4facd29..6d1e1630 100644 --- a/packages/scan/src/new-outlines/index.ts +++ b/packages/scan/src/new-outlines/index.ts @@ -321,19 +321,24 @@ export const getCanvasEl = () => { canvasEl.width = width; canvasEl.height = height; + // Users on a strict CSP without `worker-src blob:` (see #372) can opt out; + // we still render outlines on the main thread via `initCanvas` below. + const workerOptOut = + ReactScanInternals.options.value.useOffscreenCanvasWorker === false; + if ( IS_OFFSCREEN_CANVAS_WORKER_SUPPORTED && - !window.__REACT_SCAN_EXTENSION__ + !window.__REACT_SCAN_EXTENSION__ && + !workerOptOut ) { try { - worker = new Worker( - URL.createObjectURL( - new Blob([workerCode], { type: 'application/javascript' }), - ), + const blobUrl = URL.createObjectURL( + new Blob([workerCode], { type: 'application/javascript' }), ); + worker = new Worker(blobUrl); const offscreenCanvas = canvasEl.transferControlToOffscreen(); - worker?.postMessage( + worker.postMessage( { type: 'init', canvas: offscreenCanvas, @@ -343,10 +348,20 @@ export const getCanvasEl = () => { }, [offscreenCanvas], ); - } catch (e) { - // oxlint-disable-next-line no-console - console.warn('Failed to initialize OffscreenCanvas worker:', e); + } catch (error) { + // The common failure here is a strict CSP rejecting `blob:` workers. + // The fallback below renders fine on the main thread, so log only when + // the user explicitly asked for verbose diagnostics. + worker = null; + if (ReactScanInternals.options.value._debug === 'verbose') { + // oxlint-disable-next-line no-console + console.warn('Failed to initialize OffscreenCanvas worker:', error); + } } + // The blob URL stays alive until the worker is GC'd. Revoking + // synchronously after `new Worker(url)` has historically broken some + // browser versions before the worker actually fetched the URL — leave + // the (single, tiny) URL in place rather than risking that race. } if (!worker) { From 6535684fe6e6c4eccab54af5a561fa73f0bec9ee Mon Sep 17 00:00:00 2001 From: Aiden Bai Date: Fri, 1 May 2026 07:15:30 -0700 Subject: [PATCH 5/8] feat(scan): add safeArea option + allow text selection inside toolbar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit safeArea (#430) --------------- Other dev overlays (most notably the Next.js dev indicator) sit in the same screen corners as the React Scan toolbar. The expanded toolbar and collapsed bookmark would overlap them with no way for the user to inset the toolbar. Adds an \`Options.safeArea\` field that accepts either: - a single number (insets all four edges, default 24) - a per-edge \`{ top?, right?, bottom?, left? }\` object Refactors the hard-coded \`SAFE_AREA\` constant out of widget positioning math (\`calculatePosition\`, \`calculateNewSizeAndPosition\`, \`WindowDimensions\`, collapsed-corner positioning, max-size CSS) to read from a new \`getSafeArea()\` helper that resolves per-edge from options at runtime. Module-init defaults still use the raw \`SAFE_AREA\` constant — options haven't been set yet at that point, and reading them through \`ReactScanInternals.options.value\` from a top-level module would create a load-bearing optional chain through a circular import. \`defaultWidgetConfig\` is preserved as a deprecated alias of \`getDefaultWidgetConfig()\` for one minor version. \`parseSafeAreaOption\` is split out as a standalone utility (one function per file per AGENTS.md) with a unit-test matrix covering arrays, NaN, negative numbers, partial objects, and non-objects. Toolbar text selection (#415) ----------------------------- The toolbar root has \`select-none\` (so dragging the bar doesn't start a text selection), and its root \`onPointerDown\` handler calls \`e.preventDefault()\` (which suppresses focus and selection on every click). Together those two made the AI-prompt \`
\`
text impossible to highlight or copy.

Fix:
- New \`TOOLBAR_INTERACTIVE_SELECTOR\` constant lists the elements
  that should bypass drag and accept native focus/selection. Used
  from both the JSX (drag handler bail-out) and the CSS
  (\`user-select: text\` re-enable). Single source of truth.
- \`handleDrag\` now bails — without calling \`preventDefault()\` —
  when the pointerdown lands on a button, link, input, textarea,
  select, pre, contenteditable, or \`[data-react-scan-selectable]\`.
- Flat CSS selectors (no nesting) so the rule applies in older
  Firefox/Safari that lack native CSS nesting.

Note: this is a small behavior change for button clicks — the
original code called \`preventDefault()\` even on button hits;
buttons now receive native focus on pointerdown.
---
 .../src/web/assets/css/styles.tailwind.css    | 11 +++
 packages/scan/src/web/constants.ts            |  6 ++
 packages/scan/src/web/state.ts                | 38 ++++++----
 .../web/utils/parse-safe-area-option.test.ts  | 72 +++++++++++++++++++
 .../src/web/utils/parse-safe-area-option.ts   | 42 +++++++++++
 packages/scan/src/web/utils/safe-area.ts      | 43 +++++++++++
 packages/scan/src/web/widget/helpers.ts       | 66 ++++++++++-------
 packages/scan/src/web/widget/index.tsx        | 54 ++++++++------
 8 files changed, 272 insertions(+), 60 deletions(-)
 create mode 100644 packages/scan/src/web/utils/parse-safe-area-option.test.ts
 create mode 100644 packages/scan/src/web/utils/parse-safe-area-option.ts
 create mode 100644 packages/scan/src/web/utils/safe-area.ts

diff --git a/packages/scan/src/web/assets/css/styles.tailwind.css b/packages/scan/src/web/assets/css/styles.tailwind.css
index 992e5491..e21830e4 100644
--- a/packages/scan/src/web/assets/css/styles.tailwind.css
+++ b/packages/scan/src/web/assets/css/styles.tailwind.css
@@ -107,6 +107,17 @@ svg {
   backface-visibility: hidden;
 }
 
+/* The toolbar uses select-none for drag UX, so re-enable text selection on
+ * content elements (e.g. AI prompt 
, search inputs). See #415. */
+#react-scan-toolbar pre,
+#react-scan-toolbar textarea,
+#react-scan-toolbar input[type='text'],
+#react-scan-toolbar input[type='search'],
+#react-scan-toolbar [data-react-scan-selectable] {
+  @apply select-text;
+  cursor: text;
+}
+
 .button {
   &:hover {
     background: rgba(255, 255, 255, 0.1);
diff --git a/packages/scan/src/web/constants.ts b/packages/scan/src/web/constants.ts
index 3b7b8bcc..580e3819 100644
--- a/packages/scan/src/web/constants.ts
+++ b/packages/scan/src/web/constants.ts
@@ -10,3 +10,9 @@ export const MIN_CONTAINER_WIDTH = 240;
 export const LOCALSTORAGE_KEY = "react-scan-widget-settings-v2";
 export const LOCALSTORAGE_COLLAPSED_KEY = "react-scan-widget-collapsed-v1";
 export const LOCALSTORAGE_LAST_VIEW_KEY = "react-scan-widget-last-view-v1";
+
+// CSS selector for elements inside #react-scan-toolbar that should NOT
+// trigger drag and SHOULD allow native text selection / focus (#415).
+// Keep in sync with the matching CSS rule in styles.tailwind.css.
+export const TOOLBAR_INTERACTIVE_SELECTOR =
+  "button, a, input, textarea, select, pre, [contenteditable], [data-react-scan-selectable]";
diff --git a/packages/scan/src/web/state.ts b/packages/scan/src/web/state.ts
index 4d1a197c..c7feb5ea 100644
--- a/packages/scan/src/web/state.ts
+++ b/packages/scan/src/web/state.ts
@@ -8,6 +8,7 @@ import {
 } from "./constants";
 import { IS_CLIENT } from "./utils/constants";
 import { readLocalStorage, saveLocalStorage } from "./utils/helpers";
+import { getSafeArea } from "./utils/safe-area";
 import type { Corner, WidgetConfig, WidgetSettings } from "./widget/types";
 import type { CollapsedPosition } from "./widget/types";
 
@@ -16,8 +17,10 @@ export const signalRefWidget = /* @__PURE__ */ signal(
   null
 );
 
-export const defaultWidgetConfig = {
-  corner: "bottom-right" as Corner,
+// Use the raw SAFE_AREA constant (not getSafeArea()) here: this runs at
+// module-init time, before any user has called scan() with options.
+export const getDefaultWidgetConfig = (): WidgetConfig => ({
+  corner: "bottom-right" satisfies Corner,
   dimensions: {
     isFullWidth: false,
     isFullHeight: false,
@@ -35,30 +38,36 @@ export const defaultWidgetConfig = {
   componentsTree: {
     width: MIN_CONTAINER_WIDTH,
   },
-} as WidgetConfig;
+});
+
+// Deprecated alias kept for one minor version to avoid breaking downstream
+// imports of the pre-refactor `defaultWidgetConfig` const.
+/** @deprecated use {@link getDefaultWidgetConfig} */
+export const defaultWidgetConfig: WidgetConfig = getDefaultWidgetConfig();
 
 export const getInitialWidgetConfig = (): WidgetConfig => {
+  const defaults = getDefaultWidgetConfig();
   const stored = readLocalStorage(LOCALSTORAGE_KEY);
   if (!stored) {
     saveLocalStorage(LOCALSTORAGE_KEY, {
-      corner: defaultWidgetConfig.corner,
-      dimensions: defaultWidgetConfig.dimensions,
-      lastDimensions: defaultWidgetConfig.lastDimensions,
-      componentsTree: defaultWidgetConfig.componentsTree,
+      corner: defaults.corner,
+      dimensions: defaults.dimensions,
+      lastDimensions: defaults.lastDimensions,
+      componentsTree: defaults.componentsTree,
     });
 
-    return defaultWidgetConfig;
+    return defaults;
   }
 
   return {
-    corner: stored.corner ?? defaultWidgetConfig.corner,
-    dimensions: stored.dimensions ?? defaultWidgetConfig.dimensions,
+    corner: stored.corner ?? defaults.corner,
+    dimensions: stored.dimensions ?? defaults.dimensions,
 
     lastDimensions:
       stored.lastDimensions ??
       stored.dimensions ??
-      defaultWidgetConfig.lastDimensions,
-    componentsTree: stored.componentsTree ?? defaultWidgetConfig.componentsTree,
+      defaults.lastDimensions,
+    componentsTree: stored.componentsTree ?? defaults.componentsTree,
   };
 };
 
@@ -69,12 +78,13 @@ export const updateDimensions = (): void => {
 
   const { dimensions } = signalWidget.value;
   const { width, height, position } = dimensions;
+  const safeArea = getSafeArea();
 
   signalWidget.value = {
     ...signalWidget.value,
     dimensions: {
-      isFullWidth: width >= window.innerWidth - SAFE_AREA * 2,
-      isFullHeight: height >= window.innerHeight - SAFE_AREA * 2,
+      isFullWidth: width >= window.innerWidth - safeArea.left - safeArea.right,
+      isFullHeight: height >= window.innerHeight - safeArea.top - safeArea.bottom,
       width,
       height,
       position,
diff --git a/packages/scan/src/web/utils/parse-safe-area-option.test.ts b/packages/scan/src/web/utils/parse-safe-area-option.test.ts
new file mode 100644
index 00000000..0fa1d9e4
--- /dev/null
+++ b/packages/scan/src/web/utils/parse-safe-area-option.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from 'vitest';
+import { parseSafeAreaOption } from '~web/utils/parse-safe-area-option';
+
+describe('parseSafeAreaOption', () => {
+  it('accepts a non-negative finite number', () => {
+    expect(parseSafeAreaOption(0)).toEqual({ ok: true, value: 0 });
+    expect(parseSafeAreaOption(24)).toEqual({ ok: true, value: 24 });
+    expect(parseSafeAreaOption(96)).toEqual({ ok: true, value: 96 });
+  });
+
+  it('rejects negative numbers', () => {
+    const result = parseSafeAreaOption(-1);
+    expect(result.ok).toBe(false);
+  });
+
+  it('rejects NaN and Infinity', () => {
+    expect(parseSafeAreaOption(Number.NaN).ok).toBe(false);
+    expect(parseSafeAreaOption(Number.POSITIVE_INFINITY).ok).toBe(false);
+    expect(parseSafeAreaOption(Number.NEGATIVE_INFINITY).ok).toBe(false);
+  });
+
+  it('accepts a partial per-edge object', () => {
+    expect(parseSafeAreaOption({ right: 96 })).toEqual({
+      ok: true,
+      value: { right: 96 },
+    });
+    expect(parseSafeAreaOption({ top: 0, bottom: 40 })).toEqual({
+      ok: true,
+      value: { top: 0, bottom: 40 },
+    });
+  });
+
+  it('accepts a full per-edge object', () => {
+    expect(
+      parseSafeAreaOption({ top: 1, right: 2, bottom: 3, left: 4 }),
+    ).toEqual({
+      ok: true,
+      value: { top: 1, right: 2, bottom: 3, left: 4 },
+    });
+  });
+
+  it('rejects per-edge object with a negative value', () => {
+    const result = parseSafeAreaOption({ right: -10 });
+    expect(result.ok).toBe(false);
+  });
+
+  it('rejects per-edge object with a non-number value', () => {
+    const result = parseSafeAreaOption({ top: '24' });
+    expect(result.ok).toBe(false);
+  });
+
+  it('rejects arrays (not plain objects)', () => {
+    const result = parseSafeAreaOption([10, 20, 30, 40]);
+    expect(result.ok).toBe(false);
+  });
+
+  it('rejects null and undefined', () => {
+    expect(parseSafeAreaOption(null).ok).toBe(false);
+    expect(parseSafeAreaOption(undefined).ok).toBe(false);
+  });
+
+  it('rejects strings', () => {
+    expect(parseSafeAreaOption('24').ok).toBe(false);
+    expect(parseSafeAreaOption('').ok).toBe(false);
+  });
+
+  it('ignores undefined edges in a per-edge object', () => {
+    expect(
+      parseSafeAreaOption({ top: 5, right: undefined }),
+    ).toEqual({ ok: true, value: { top: 5 } });
+  });
+});
diff --git a/packages/scan/src/web/utils/parse-safe-area-option.ts b/packages/scan/src/web/utils/parse-safe-area-option.ts
new file mode 100644
index 00000000..69b70d36
--- /dev/null
+++ b/packages/scan/src/web/utils/parse-safe-area-option.ts
@@ -0,0 +1,42 @@
+import type { Options } from '~core/index';
+
+type SafeAreaOption = NonNullable;
+
+export type ParsedSafeAreaOption =
+  | { ok: true; value: SafeAreaOption }
+  | { ok: false; error: string };
+
+const SAFE_AREA_EDGES = ['top', 'right', 'bottom', 'left'] as const;
+
+const isFinitePositive = (value: unknown): value is number =>
+  typeof value === 'number' && Number.isFinite(value) && value >= 0;
+
+const isPlainObject = (value: unknown): value is Record =>
+  Boolean(value) && typeof value === 'object' && !Array.isArray(value);
+
+export const parseSafeAreaOption = (value: unknown): ParsedSafeAreaOption => {
+  if (isFinitePositive(value)) {
+    return { ok: true, value };
+  }
+
+  if (!isPlainObject(value)) {
+    return {
+      ok: false,
+      error: `- safeArea must be a non-negative number or { top?, right?, bottom?, left? }. Got "${JSON.stringify(value)}"`,
+    };
+  }
+
+  const inset: Partial> = {};
+  for (const edge of SAFE_AREA_EDGES) {
+    const edgeValue = value[edge];
+    if (edgeValue === undefined) continue;
+    if (!isFinitePositive(edgeValue)) {
+      return {
+        ok: false,
+        error: `- safeArea.${edge} must be a non-negative number. Got "${JSON.stringify(edgeValue)}"`,
+      };
+    }
+    inset[edge] = edgeValue;
+  }
+  return { ok: true, value: inset };
+};
diff --git a/packages/scan/src/web/utils/safe-area.ts b/packages/scan/src/web/utils/safe-area.ts
new file mode 100644
index 00000000..1336d960
--- /dev/null
+++ b/packages/scan/src/web/utils/safe-area.ts
@@ -0,0 +1,43 @@
+import { ReactScanInternals } from '~core/index';
+import { SAFE_AREA } from '~web/constants';
+
+export interface SafeAreaInsets {
+  top: number;
+  right: number;
+  bottom: number;
+  left: number;
+}
+
+const isFinitePositive = (value: unknown): value is number =>
+  typeof value === 'number' && Number.isFinite(value) && value >= 0;
+
+const isPlainObject = (value: unknown): value is Record =>
+  Boolean(value) && typeof value === 'object' && !Array.isArray(value);
+
+export const getSafeArea = (): SafeAreaInsets => {
+  const value = ReactScanInternals.options.value.safeArea;
+
+  if (isFinitePositive(value)) {
+    return { top: value, right: value, bottom: value, left: value };
+  }
+
+  if (isPlainObject(value)) {
+    const top = value.top;
+    const right = value.right;
+    const bottom = value.bottom;
+    const left = value.left;
+    return {
+      top: isFinitePositive(top) ? top : SAFE_AREA,
+      right: isFinitePositive(right) ? right : SAFE_AREA,
+      bottom: isFinitePositive(bottom) ? bottom : SAFE_AREA,
+      left: isFinitePositive(left) ? left : SAFE_AREA,
+    };
+  }
+
+  return {
+    top: SAFE_AREA,
+    right: SAFE_AREA,
+    bottom: SAFE_AREA,
+    left: SAFE_AREA,
+  };
+};
diff --git a/packages/scan/src/web/widget/helpers.ts b/packages/scan/src/web/widget/helpers.ts
index e3b6589d..f77da1aa 100644
--- a/packages/scan/src/web/widget/helpers.ts
+++ b/packages/scan/src/web/widget/helpers.ts
@@ -1,4 +1,5 @@
-import { MIN_SIZE, SAFE_AREA } from '../constants';
+import { MIN_SIZE } from '../constants';
+import { getSafeArea, type SafeAreaInsets } from '../utils/safe-area';
 import type { Corner, Position, ResizeHandleProps, Size } from './types';
 
 class WindowDimensions {
@@ -8,17 +9,18 @@ class WindowDimensions {
   constructor(
     public width: number,
     public height: number,
+    public safeArea: SafeAreaInsets,
   ) {
-    this.maxWidth = width - SAFE_AREA * 2;
-    this.maxHeight = height - SAFE_AREA * 2;
+    this.maxWidth = width - safeArea.left - safeArea.right;
+    this.maxHeight = height - safeArea.top - safeArea.bottom;
   }
 
   rightEdge(width: number): number {
-    return this.width - width - SAFE_AREA;
+    return this.width - width - this.safeArea.right;
   }
 
   bottomEdge(height: number): number {
-    return this.height - height - SAFE_AREA;
+    return this.height - height - this.safeArea.bottom;
   }
 
   isFullWidth(width: number): boolean {
@@ -32,19 +34,31 @@ class WindowDimensions {
 
 let cachedWindowDimensions: WindowDimensions | undefined;
 
+const safeAreaMatches = (a: SafeAreaInsets, b: SafeAreaInsets): boolean =>
+  a.top === b.top &&
+  a.right === b.right &&
+  a.bottom === b.bottom &&
+  a.left === b.left;
+
 export const getWindowDimensions = () => {
   const currentWidth = window.innerWidth;
   const currentHeight = window.innerHeight;
+  const currentSafeArea = getSafeArea();
 
   if (
     cachedWindowDimensions &&
     cachedWindowDimensions.width === currentWidth &&
-    cachedWindowDimensions.height === currentHeight
+    cachedWindowDimensions.height === currentHeight &&
+    safeAreaMatches(cachedWindowDimensions.safeArea, currentSafeArea)
   ) {
     return cachedWindowDimensions;
   }
 
-  cachedWindowDimensions = new WindowDimensions(currentWidth, currentHeight);
+  cachedWindowDimensions = new WindowDimensions(
+    currentWidth,
+    currentHeight,
+    currentSafeArea,
+  );
 
   return cachedWindowDimensions;
 };
@@ -98,6 +112,7 @@ export const calculatePosition = (
 
   const windowWidth = window.innerWidth;
   const windowHeight = window.innerHeight;
+  const safeArea = getSafeArea();
 
   // Check if widget is minimized
   const isMinimized = width === MIN_SIZE.width;
@@ -105,19 +120,19 @@ export const calculatePosition = (
   // Only bound dimensions if minimized
   const effectiveWidth = isMinimized
     ? width
-    : Math.min(width, windowWidth - SAFE_AREA * 2);
+    : Math.min(width, windowWidth - safeArea.left - safeArea.right);
   const effectiveHeight = isMinimized
     ? height
-    : Math.min(height, windowHeight - SAFE_AREA * 2);
+    : Math.min(height, windowHeight - safeArea.top - safeArea.bottom);
 
   // Calculate base positions
   let x: number;
   let y: number;
 
-  let leftBound = SAFE_AREA;
-  let rightBound =  windowWidth - effectiveWidth - SAFE_AREA;
-  let topBound = SAFE_AREA;
-  let bottomBound = windowHeight - effectiveHeight - SAFE_AREA;
+  let leftBound = safeArea.left;
+  let rightBound =  windowWidth - effectiveWidth - safeArea.right;
+  let topBound = safeArea.top;
+  let bottomBound = windowHeight - effectiveHeight - safeArea.bottom;
 
   switch (corner) {
     case 'top-right':
@@ -224,9 +239,10 @@ export const calculateNewSizeAndPosition = (
   deltaY: number,
 ): { newSize: Size; newPosition: Position } => {
   const isRTL = getComputedStyle(document.body).direction === 'rtl';
+  const safeArea = getSafeArea();
 
-  const maxWidth = window.innerWidth - SAFE_AREA * 2;
-  const maxHeight = window.innerHeight - SAFE_AREA * 2;
+  const maxWidth = window.innerWidth - safeArea.left - safeArea.right;
+  const maxHeight = window.innerHeight - safeArea.top - safeArea.bottom;
 
   let newWidth = initialSize.width;
   let newHeight = initialSize.height;
@@ -236,27 +252,27 @@ export const calculateNewSizeAndPosition = (
   // horizontal resize for RTL
   if (isRTL && position.includes('right')) {
     // Check if we have enough space on the right
-    const availableWidth = -initialPosition.x + initialSize.width - SAFE_AREA;
+    const availableWidth = -initialPosition.x + initialSize.width - safeArea.right;
     const proposedWidth = Math.min(initialSize.width + deltaX, availableWidth);
     newWidth = Math.min(maxWidth, Math.max(MIN_SIZE.width, proposedWidth));
     newX = initialPosition.x + (newWidth - initialSize.width);
   }
   if (isRTL && position.includes('left')) {
     // Check if we have enough space on the left
-    const availableWidth = window.innerWidth - initialPosition.x - SAFE_AREA;
+    const availableWidth = window.innerWidth - initialPosition.x - safeArea.left;
     const proposedWidth = Math.min(initialSize.width - deltaX, availableWidth);
     newWidth = Math.min(maxWidth, Math.max(MIN_SIZE.width, proposedWidth));
   }
   // horizontal resize for LTR
   if (!isRTL && position.includes('right')) {
     // Check if we have enough space on the right
-    const availableWidth = window.innerWidth - initialPosition.x - SAFE_AREA;
+    const availableWidth = window.innerWidth - initialPosition.x - safeArea.right;
     const proposedWidth = Math.min(initialSize.width + deltaX, availableWidth);
     newWidth = Math.min(maxWidth, Math.max(MIN_SIZE.width, proposedWidth));
   }
   if (!isRTL && position.includes('left')) {
     // Check if we have enough space on the left
-    const availableWidth = initialPosition.x + initialSize.width - SAFE_AREA;
+    const availableWidth = initialPosition.x + initialSize.width - safeArea.left;
     const proposedWidth = Math.min(initialSize.width - deltaX, availableWidth);
     newWidth = Math.min(maxWidth, Math.max(MIN_SIZE.width, proposedWidth));
     newX = initialPosition.x - (newWidth - initialSize.width);
@@ -265,7 +281,7 @@ export const calculateNewSizeAndPosition = (
   // vertical resize
   if (position.includes('bottom')) {
     // Check if we have enough space at the bottom
-    const availableHeight = window.innerHeight - initialPosition.y - SAFE_AREA;
+    const availableHeight = window.innerHeight - initialPosition.y - safeArea.bottom;
     const proposedHeight = Math.min(
       initialSize.height + deltaY,
       availableHeight,
@@ -277,7 +293,7 @@ export const calculateNewSizeAndPosition = (
   }
   if (position.includes('top')) {
     // Check if we have enough space at the top
-    const availableHeight = initialPosition.y + initialSize.height - SAFE_AREA;
+    const availableHeight = initialPosition.y + initialSize.height - safeArea.top;
     const proposedHeight = Math.min(
       initialSize.height - deltaY,
       availableHeight,
@@ -289,10 +305,10 @@ export const calculateNewSizeAndPosition = (
     newY = initialPosition.y - (newHeight - initialSize.height);
   }
 
-  let leftBound = SAFE_AREA;
-  let rightBound = window.innerWidth - SAFE_AREA - newWidth;
-  let topBound = SAFE_AREA;
-  let bottomBound = window.innerHeight - SAFE_AREA - newHeight;
+  let leftBound = safeArea.left;
+  let rightBound = window.innerWidth - safeArea.right - newWidth;
+  let topBound = safeArea.top;
+  let bottomBound = window.innerHeight - safeArea.bottom - newHeight;
 
   // Ensure position stays within bounds
   if (isRTL) {
diff --git a/packages/scan/src/web/widget/index.tsx b/packages/scan/src/web/widget/index.tsx
index b7223a79..7025eb03 100644
--- a/packages/scan/src/web/widget/index.tsx
+++ b/packages/scan/src/web/widget/index.tsx
@@ -13,17 +13,18 @@ import {
   LOCALSTORAGE_KEY,
   LOCALSTORAGE_COLLAPSED_KEY,
   MIN_SIZE,
-  SAFE_AREA,
   LOCALSTORAGE_LAST_VIEW_KEY,
+  TOOLBAR_INTERACTIVE_SELECTOR,
 } from "../constants";
 import {
-  defaultWidgetConfig,
+  getDefaultWidgetConfig,
   signalRefWidget,
   signalWidget,
   signalWidgetViews,
   updateDimensions,
   type WidgetStates,
 } from "../state";
+import { getSafeArea } from "../utils/safe-area";
 import {
   calculateBoundedSize,
   calculatePosition,
@@ -82,25 +83,26 @@ export const Widget = () => {
       const { corner: collapsedCorner, orientation = "horizontal" } =
         signalWidgetCollapsed.value;
       const size = COLLAPSED_SIZE[orientation];
+      const safeArea = getSafeArea();
 
       switch (collapsedCorner) {
         case "top-left":
           finalPosition =
             orientation === "horizontal"
-              ? { x: -1, y: SAFE_AREA }
-              : { x: SAFE_AREA, y: -1 };
+              ? { x: -1, y: safeArea.top }
+              : { x: safeArea.left, y: -1 };
           break;
         case "bottom-left":
           finalPosition =
             orientation === "horizontal"
-              ? { x: -1, y: window.innerHeight - size.height - SAFE_AREA }
-              : { x: SAFE_AREA, y: window.innerHeight - size.height + 1 };
+              ? { x: -1, y: window.innerHeight - size.height - safeArea.bottom }
+              : { x: safeArea.left, y: window.innerHeight - size.height + 1 };
           break;
         case "top-right":
           finalPosition =
             orientation === "horizontal"
-              ? { x: window.innerWidth - size.width + 1, y: SAFE_AREA }
-              : { x: window.innerWidth - size.width - SAFE_AREA, y: -1 };
+              ? { x: window.innerWidth - size.width + 1, y: safeArea.top }
+              : { x: window.innerWidth - size.width - safeArea.right, y: -1 };
           break;
         case "bottom-right":
         default:
@@ -108,10 +110,10 @@ export const Widget = () => {
             orientation === "horizontal"
               ? {
                   x: window.innerWidth - size.width + 1,
-                  y: window.innerHeight - size.height - SAFE_AREA,
+                  y: window.innerHeight - size.height - safeArea.bottom,
                 }
               : {
-                  x: window.innerWidth - size.width - SAFE_AREA,
+                  x: window.innerWidth - size.width - safeArea.right,
                   y: window.innerHeight - size.height + 1,
                 };
           break;
@@ -145,9 +147,10 @@ export const Widget = () => {
       rafId = null;
     });
 
+    const safeArea = getSafeArea();
     const newDimensions = {
-      isFullWidth: newWidth >= window.innerWidth - SAFE_AREA * 2,
-      isFullHeight: newHeight >= window.innerHeight - SAFE_AREA * 2,
+      isFullWidth: newWidth >= window.innerWidth - safeArea.left - safeArea.right,
+      isFullHeight: newHeight >= window.innerHeight - safeArea.top - safeArea.bottom,
       width: newWidth,
       height: newHeight,
       position: finalPosition,
@@ -178,10 +181,17 @@ export const Widget = () => {
 
   const handleDrag = useCallback(
     (e: JSX.TargetedPointerEvent) => {
-      e.preventDefault();
+      const target = e.target as HTMLElement;
 
-      if (!refWidget.current || (e.target as HTMLElement).closest("button"))
+      // Skip drag on interactive/text-selectable surfaces so users can select
+      // prompt text, focus inputs, and click buttons normally.
+      if (target.closest(TOOLBAR_INTERACTIVE_SELECTOR)) {
         return;
+      }
+
+      e.preventDefault();
+
+      if (!refWidget.current) return;
 
       const container = refWidget.current;
       const containerStyle = container.style;
@@ -478,13 +488,14 @@ export const Widget = () => {
                 let newX = e.clientX - targetWidth / 2;
                 let newY = e.clientY - targetHeight / 2;
 
+                const safeArea = getSafeArea();
                 newX = Math.max(
-                  SAFE_AREA,
-                  Math.min(newX, window.innerWidth - targetWidth - SAFE_AREA)
+                  safeArea.left,
+                  Math.min(newX, window.innerWidth - targetWidth - safeArea.right)
                 );
                 newY = Math.max(
-                  SAFE_AREA,
-                  Math.min(newY, window.innerHeight - targetHeight - SAFE_AREA)
+                  safeArea.top,
+                  Math.min(newY, window.innerHeight - targetHeight - safeArea.bottom)
                 );
 
                 signalWidget.value = {
@@ -558,8 +569,9 @@ export const Widget = () => {
       refInitialMinimizedWidth.current = 0;
     }
 
-    refWidget.current.style.maxWidth = `calc(100vw - ${SAFE_AREA * 2}px)`;
-    refWidget.current.style.maxHeight = `calc(100vh - ${SAFE_AREA * 2}px)`;
+    const safeArea = getSafeArea();
+    refWidget.current.style.maxWidth = `calc(100vw - ${safeArea.left + safeArea.right}px)`;
+    refWidget.current.style.maxHeight = `calc(100vh - ${safeArea.top + safeArea.bottom}px)`;
 
     updateWidgetPosition();
 
@@ -631,7 +643,7 @@ export const Widget = () => {
       unsubscribeSignalWidget();
 
       saveLocalStorage(LOCALSTORAGE_KEY, {
-        ...defaultWidgetConfig,
+        ...getDefaultWidgetConfig(),
         corner: signalWidget.value.corner,
       });
     };

From 7d5ad759740134856ef7707981c1d35fd09972a3 Mon Sep 17 00:00:00 2001
From: Aiden Bai 
Date: Fri, 1 May 2026 07:26:55 -0700
Subject: [PATCH 6/8] refactor(scan): dedupe isFinitePositive / isPlainObject
 across utils

\`safe-area.ts\` and \`parse-safe-area-option.ts\` each defined their own
copy of the same two predicates. If validation logic ever diverged
(e.g. one gets a bugfix the other doesn't), runtime behavior would
silently differ between option validation at \`scan()\` time and the
\`getSafeArea()\` read path.

Extracts both into their own files in \`web/utils/\` (one utility per
file per AGENTS.md) and imports them from both consumers.

Addresses Cursor Bugbot review on #437.
---
 packages/scan/src/web/utils/is-finite-positive.ts     | 2 ++
 packages/scan/src/web/utils/is-plain-object.ts        | 4 ++++
 packages/scan/src/web/utils/parse-safe-area-option.ts | 8 ++------
 packages/scan/src/web/utils/safe-area.ts              | 8 ++------
 4 files changed, 10 insertions(+), 12 deletions(-)
 create mode 100644 packages/scan/src/web/utils/is-finite-positive.ts
 create mode 100644 packages/scan/src/web/utils/is-plain-object.ts

diff --git a/packages/scan/src/web/utils/is-finite-positive.ts b/packages/scan/src/web/utils/is-finite-positive.ts
new file mode 100644
index 00000000..17910233
--- /dev/null
+++ b/packages/scan/src/web/utils/is-finite-positive.ts
@@ -0,0 +1,2 @@
+export const isFinitePositive = (value: unknown): value is number =>
+  typeof value === 'number' && Number.isFinite(value) && value >= 0;
diff --git a/packages/scan/src/web/utils/is-plain-object.ts b/packages/scan/src/web/utils/is-plain-object.ts
new file mode 100644
index 00000000..2558f466
--- /dev/null
+++ b/packages/scan/src/web/utils/is-plain-object.ts
@@ -0,0 +1,4 @@
+export const isPlainObject = (
+  value: unknown,
+): value is Record =>
+  Boolean(value) && typeof value === 'object' && !Array.isArray(value);
diff --git a/packages/scan/src/web/utils/parse-safe-area-option.ts b/packages/scan/src/web/utils/parse-safe-area-option.ts
index 69b70d36..0708db41 100644
--- a/packages/scan/src/web/utils/parse-safe-area-option.ts
+++ b/packages/scan/src/web/utils/parse-safe-area-option.ts
@@ -1,4 +1,6 @@
 import type { Options } from '~core/index';
+import { isFinitePositive } from '~web/utils/is-finite-positive';
+import { isPlainObject } from '~web/utils/is-plain-object';
 
 type SafeAreaOption = NonNullable;
 
@@ -8,12 +10,6 @@ export type ParsedSafeAreaOption =
 
 const SAFE_AREA_EDGES = ['top', 'right', 'bottom', 'left'] as const;
 
-const isFinitePositive = (value: unknown): value is number =>
-  typeof value === 'number' && Number.isFinite(value) && value >= 0;
-
-const isPlainObject = (value: unknown): value is Record =>
-  Boolean(value) && typeof value === 'object' && !Array.isArray(value);
-
 export const parseSafeAreaOption = (value: unknown): ParsedSafeAreaOption => {
   if (isFinitePositive(value)) {
     return { ok: true, value };
diff --git a/packages/scan/src/web/utils/safe-area.ts b/packages/scan/src/web/utils/safe-area.ts
index 1336d960..3432fed6 100644
--- a/packages/scan/src/web/utils/safe-area.ts
+++ b/packages/scan/src/web/utils/safe-area.ts
@@ -1,5 +1,7 @@
 import { ReactScanInternals } from '~core/index';
 import { SAFE_AREA } from '~web/constants';
+import { isFinitePositive } from '~web/utils/is-finite-positive';
+import { isPlainObject } from '~web/utils/is-plain-object';
 
 export interface SafeAreaInsets {
   top: number;
@@ -8,12 +10,6 @@ export interface SafeAreaInsets {
   left: number;
 }
 
-const isFinitePositive = (value: unknown): value is number =>
-  typeof value === 'number' && Number.isFinite(value) && value >= 0;
-
-const isPlainObject = (value: unknown): value is Record =>
-  Boolean(value) && typeof value === 'object' && !Array.isArray(value);
-
 export const getSafeArea = (): SafeAreaInsets => {
   const value = ReactScanInternals.options.value.safeArea;
 

From 8cd91fb836b001c72fcf9f68eac1fc71d9a8f45e Mon Sep 17 00:00:00 2001
From: Aiden Bai 
Date: Fri, 1 May 2026 07:40:22 -0700
Subject: [PATCH 7/8] refactor(scan): rename isFinitePositive ->
 isFiniteNonNegative

The predicate accepts \`value >= 0\`, which includes zero, but the
\`isFinitePositive\` name implies strictly > 0 (the standard math
meaning of "positive"). The error messages already correctly say
"non-negative number". Renames the helper file + export to match
the actual semantics so a future caller doesn't rely on the misleading
name to exclude zero.

Addresses Cursor Bugbot review on #437.
---
 .../scan/src/web/utils/is-finite-non-negative.ts     |  2 ++
 packages/scan/src/web/utils/is-finite-positive.ts    |  2 --
 .../scan/src/web/utils/parse-safe-area-option.ts     |  6 +++---
 packages/scan/src/web/utils/safe-area.ts             | 12 ++++++------
 4 files changed, 11 insertions(+), 11 deletions(-)
 create mode 100644 packages/scan/src/web/utils/is-finite-non-negative.ts
 delete mode 100644 packages/scan/src/web/utils/is-finite-positive.ts

diff --git a/packages/scan/src/web/utils/is-finite-non-negative.ts b/packages/scan/src/web/utils/is-finite-non-negative.ts
new file mode 100644
index 00000000..17fbd8f2
--- /dev/null
+++ b/packages/scan/src/web/utils/is-finite-non-negative.ts
@@ -0,0 +1,2 @@
+export const isFiniteNonNegative = (value: unknown): value is number =>
+  typeof value === 'number' && Number.isFinite(value) && value >= 0;
diff --git a/packages/scan/src/web/utils/is-finite-positive.ts b/packages/scan/src/web/utils/is-finite-positive.ts
deleted file mode 100644
index 17910233..00000000
--- a/packages/scan/src/web/utils/is-finite-positive.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export const isFinitePositive = (value: unknown): value is number =>
-  typeof value === 'number' && Number.isFinite(value) && value >= 0;
diff --git a/packages/scan/src/web/utils/parse-safe-area-option.ts b/packages/scan/src/web/utils/parse-safe-area-option.ts
index 0708db41..7c70810f 100644
--- a/packages/scan/src/web/utils/parse-safe-area-option.ts
+++ b/packages/scan/src/web/utils/parse-safe-area-option.ts
@@ -1,5 +1,5 @@
 import type { Options } from '~core/index';
-import { isFinitePositive } from '~web/utils/is-finite-positive';
+import { isFiniteNonNegative } from '~web/utils/is-finite-non-negative';
 import { isPlainObject } from '~web/utils/is-plain-object';
 
 type SafeAreaOption = NonNullable;
@@ -11,7 +11,7 @@ export type ParsedSafeAreaOption =
 const SAFE_AREA_EDGES = ['top', 'right', 'bottom', 'left'] as const;
 
 export const parseSafeAreaOption = (value: unknown): ParsedSafeAreaOption => {
-  if (isFinitePositive(value)) {
+  if (isFiniteNonNegative(value)) {
     return { ok: true, value };
   }
 
@@ -26,7 +26,7 @@ export const parseSafeAreaOption = (value: unknown): ParsedSafeAreaOption => {
   for (const edge of SAFE_AREA_EDGES) {
     const edgeValue = value[edge];
     if (edgeValue === undefined) continue;
-    if (!isFinitePositive(edgeValue)) {
+    if (!isFiniteNonNegative(edgeValue)) {
       return {
         ok: false,
         error: `- safeArea.${edge} must be a non-negative number. Got "${JSON.stringify(edgeValue)}"`,
diff --git a/packages/scan/src/web/utils/safe-area.ts b/packages/scan/src/web/utils/safe-area.ts
index 3432fed6..7a33ae9f 100644
--- a/packages/scan/src/web/utils/safe-area.ts
+++ b/packages/scan/src/web/utils/safe-area.ts
@@ -1,6 +1,6 @@
 import { ReactScanInternals } from '~core/index';
 import { SAFE_AREA } from '~web/constants';
-import { isFinitePositive } from '~web/utils/is-finite-positive';
+import { isFiniteNonNegative } from '~web/utils/is-finite-non-negative';
 import { isPlainObject } from '~web/utils/is-plain-object';
 
 export interface SafeAreaInsets {
@@ -13,7 +13,7 @@ export interface SafeAreaInsets {
 export const getSafeArea = (): SafeAreaInsets => {
   const value = ReactScanInternals.options.value.safeArea;
 
-  if (isFinitePositive(value)) {
+  if (isFiniteNonNegative(value)) {
     return { top: value, right: value, bottom: value, left: value };
   }
 
@@ -23,10 +23,10 @@ export const getSafeArea = (): SafeAreaInsets => {
     const bottom = value.bottom;
     const left = value.left;
     return {
-      top: isFinitePositive(top) ? top : SAFE_AREA,
-      right: isFinitePositive(right) ? right : SAFE_AREA,
-      bottom: isFinitePositive(bottom) ? bottom : SAFE_AREA,
-      left: isFinitePositive(left) ? left : SAFE_AREA,
+      top: isFiniteNonNegative(top) ? top : SAFE_AREA,
+      right: isFiniteNonNegative(right) ? right : SAFE_AREA,
+      bottom: isFiniteNonNegative(bottom) ? bottom : SAFE_AREA,
+      left: isFiniteNonNegative(left) ? left : SAFE_AREA,
     };
   }
 

From 22b8f462f36b8b77d19efb97eab7c4beca990f9c Mon Sep 17 00:00:00 2001
From: Aiden Bai 
Date: Fri, 1 May 2026 07:56:01 -0700
Subject: [PATCH 8/8] fix(scan): apply correct safeArea edge to physical side
 in RTL
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

The pre-asymmetric \`SAFE_AREA\` constant masked a longstanding bug in
the RTL positioning math. \`calculatePosition\` used
\`x = -leftBound\` for right corners and \`x = -rightBound\` for left
corners — fine when both bounds embed the same number, but wrong when
\`safeArea.left !== safeArea.right\`.

In RTL the toolbar is right-anchored (\`position: fixed\` with both
\`left:0\` and \`right:0\` plus an explicit width pins to inline-end),
so a translateX(-N) leaves an N-pixel gap on the *physical* right
edge. To inset physical right by \`safeArea.right\` and physical left
by \`safeArea.left\`, the corner offsets must be:
- right corners: \`-safeArea.right\`
- left corners: \`-(windowWidth - width - safeArea.left)\`

Same fix applied to the bound clamping in \`calculateNewSizeAndPosition\`.
With symmetric values these collapse to the original
\`-leftBound\` / \`-rightBound\` so behavior is unchanged for users
who don't set \`safeArea\`.

Addresses Cursor Bugbot review on #437.
---
 packages/scan/src/web/widget/helpers.ts | 37 +++++++++++++++++--------
 1 file changed, 25 insertions(+), 12 deletions(-)

diff --git a/packages/scan/src/web/widget/helpers.ts b/packages/scan/src/web/widget/helpers.ts
index f77da1aa..f0984adb 100644
--- a/packages/scan/src/web/widget/helpers.ts
+++ b/packages/scan/src/web/widget/helpers.ts
@@ -134,21 +134,32 @@ export const calculatePosition = (
   let topBound = safeArea.top;
   let bottomBound = windowHeight - effectiveHeight - safeArea.bottom;
 
+  // In RTL the toolbar's containing block resolves to the right viewport
+  // edge (position: fixed with both left:0 and right:0 plus an explicit
+  // width pins to inline-end). translateX(negative) moves it leftward
+  // from that right anchor, so the *physical* right inset is `-safeArea.right`
+  // and the physical left inset is `-(windowWidth - width - safeArea.left)`.
+  // With symmetric SAFE_AREA these collapse to the original `-leftBound` /
+  // `-rightBound` values; asymmetric `safeArea` would otherwise apply the
+  // wrong edge to the wrong physical side.
+  const rtlRightCornerX = -safeArea.right;
+  const rtlLeftCornerX = -(windowWidth - effectiveWidth - safeArea.left);
+
   switch (corner) {
     case 'top-right':
-      x = isRTL ? -leftBound : rightBound;
+      x = isRTL ? rtlRightCornerX : rightBound;
       y = topBound;
       break;
     case 'bottom-right':
-      x = isRTL ? -leftBound : rightBound;
+      x = isRTL ? rtlRightCornerX : rightBound;
       y = bottomBound;
       break;
     case 'bottom-left':
-      x = isRTL ? -rightBound : leftBound;
+      x = isRTL ? rtlLeftCornerX : leftBound;
       y = bottomBound;
       break;
     case 'top-left':
-      x = isRTL ? -rightBound : leftBound;
+      x = isRTL ? rtlLeftCornerX : leftBound;
       y = topBound;
       break;
     default:
@@ -160,13 +171,11 @@ export const calculatePosition = (
   // Only ensure positions are within bounds if minimized
   if (isMinimized) {
     if (isRTL) {
-      // For RTL
       x = Math.min(
-        -leftBound,
-        Math.max(x, -rightBound)
+        rtlRightCornerX,
+        Math.max(x, rtlLeftCornerX),
       );
     } else {
-      // For LTR
       x = Math.max(
         leftBound,
         Math.min(x, rightBound),
@@ -310,15 +319,19 @@ export const calculateNewSizeAndPosition = (
   let topBound = safeArea.top;
   let bottomBound = window.innerHeight - safeArea.bottom - newHeight;
 
+  // See `calculatePosition` for why RTL uses these values: the toolbar is
+  // right-anchored in RTL, so physical-edge insets need different bounds
+  // than the LTR `[leftBound, rightBound]` clamp.
+  const rtlRightCornerX = -safeArea.right;
+  const rtlLeftCornerX = -(window.innerWidth - newWidth - safeArea.left);
+
   // Ensure position stays within bounds
   if (isRTL) {
-    // for RTL
     newX = Math.min(
-      -leftBound,
-      Math.max(newX, -rightBound)
+      rtlRightCornerX,
+      Math.max(newX, rtlLeftCornerX),
     );
   } else {
-    // for LTR
     newX = Math.max(
       leftBound,
       Math.min(newX, rightBound),