diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index d0b6347805d..4d52e46d4a1 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -123,6 +123,12 @@ graph. Local affected tests do not replace CI.
Use `pnpm test`, not raw `vitest`: only it keeps the transform cache that makes repeat runs fast.
+Most unit files share a worker and its module cache with the files before them. After each file
+the worker undoes mocks, fake timers, stubs, env, cwd, and leftover timers, listeners, and globals.
+Files using `vi.doMock`, `vi.resetModules`, a DOM environment, or direct `globalThis` writes keep
+their own worker. If a file passes alone but fails after others, add `// @orca-isolated-worker`
+to it; `ORCA_VITEST_ISOLATE_EVERY_FILE=1` isolates every file to confirm a leak.
+
To reduce main-process rebuild CPU and memory when you do not need its source maps,
set `ORCA_DEV_MAIN_SOURCEMAPS=0` before `pnpm dev`. In Bash/zsh:
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index edc22bc6505..c88dc0f782f 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -342,12 +342,6 @@ jobs:
if [ "$PREFLIGHT_PHASE_SELECTED" != true ] || [ "$PREFLIGHT_PRIOR_SUCCESS" != true ]; then exit 0; fi
node config/scripts/preflight/changed-checks/check-changed-code-quality.mjs "${{ github.event.pull_request.base.sha }}"
- - name: Verify locked audit tools
- if: needs.code_paths.outputs.static_analysis == 'true'
- env:
- ORCA_BACKGROUND_LAUNCH: '1'
- run: node config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs
-
- name: Enforce React Doctor on changed lines
if: needs.code_paths.outputs.static_analysis == 'true'
run: node config/scripts/static-analysis/react-doctor/check-react-doctor-changed.mjs "${{ github.event.pull_request.base.sha }}"
diff --git a/config/audit-tools/README.md b/config/audit-tools/README.md
index 7ae8738106c..9c060fa55a2 100644
--- a/config/audit-tools/README.md
+++ b/config/audit-tools/README.md
@@ -13,4 +13,3 @@ To update a tool, change its exact version in this package's manifest, run
`pnpm --dir config/audit-tools install --ignore-scripts`, and review both the manifest
and generated lockfile. The workspace enforces a three-day release delay and
disables install scripts. Keep its package-manager pin aligned with the root.
-Run `node config/scripts/verify-locked-audit-tools.mjs` to exercise both tools.
diff --git a/config/build-plugins/react-compiler.ts b/config/build-plugins/react-compiler.ts
new file mode 100644
index 00000000000..fcdb314daa8
--- /dev/null
+++ b/config/build-plugins/react-compiler.ts
@@ -0,0 +1,47 @@
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import type { Options } from '@vitejs/plugin-react'
+
+// Hand-kept list plus every file still in a hazard ratchet; compiled, these would run differently.
+const UNCOMPILED_FILE_LISTS = [
+ 'config/react-compiler-uncompiled-files.txt',
+ 'config/render-path-translate-baseline.txt',
+ 'config/react-compiler-hazard-baseline.txt'
+]
+
+function listedFiles(list: string): string[] {
+ return readFileSync(resolve(list), 'utf8')
+ .split('\n')
+ .map((line) => line.trim())
+ .filter((line) => line && !line.startsWith('#'))
+ .map((line) => line.replace(/^\d+\s+/, '').split('#')[0])
+}
+
+export function reactCompilerExcludedFiles(): string[] {
+ return [...new Set(UNCOMPILED_FILE_LISTS.flatMap(listedFiles))]
+}
+
+export function isReactCompilerEnabled(): boolean {
+ return process.env.ORCA_REACT_COMPILER !== '0'
+}
+
+export const REACT_COMPILER_OPTIONS = { target: '19' } as const
+
+function escapeRegExp(text: string): string {
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+}
+
+export function reactCompilerExcludePattern(): RegExp {
+ return new RegExp(`/(?:${reactCompilerExcludedFiles().map(escapeRegExp).join('|')})$`)
+}
+
+// ORCA_REACT_COMPILER=0 builds without the compiler for bisecting.
+export function reactPluginOptions(): Options {
+ if (!isReactCompilerEnabled()) {
+ return {}
+ }
+ return {
+ compiler: REACT_COMPILER_OPTIONS,
+ exclude: [/\/node_modules\//, reactCompilerExcludePattern()]
+ }
+}
diff --git a/config/build-plugins/vitest-compiler-runtime-fallback.ts b/config/build-plugins/vitest-compiler-runtime-fallback.ts
new file mode 100644
index 00000000000..9c917969fb6
--- /dev/null
+++ b/config/build-plugins/vitest-compiler-runtime-fallback.ts
@@ -0,0 +1,25 @@
+import { createRequire } from 'node:module'
+
+// Why: hook-harness tests mock React or call hooks outside render; there, run uncached like uncompiled code.
+const require = createRequire(import.meta.url)
+const react: {
+ __CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE: { H: unknown }
+} = require('react')
+const internals = react.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE
+const runtime: { c: (size: number) => unknown[] } = require('react/compiler-runtime')
+const sentinel = Symbol.for('react.memo_cache_sentinel')
+const uncached = (size: number): unknown[] => Array.from({ length: size }, () => sentinel)
+
+export function c(size: number): unknown[] {
+ if (!internals.H) {
+ return uncached(size)
+ }
+ try {
+ return runtime.c(size)
+ } catch (error) {
+ if (error instanceof Error && error.message.startsWith('Invalid hook call')) {
+ return uncached(size)
+ }
+ throw error
+ }
+}
diff --git a/config/build-plugins/vitest-react-compiler.ts b/config/build-plugins/vitest-react-compiler.ts
new file mode 100644
index 00000000000..1b3a180f43a
--- /dev/null
+++ b/config/build-plugins/vitest-react-compiler.ts
@@ -0,0 +1,66 @@
+import { resolve } from 'node:path'
+import { normalizePath, type Plugin } from 'vite'
+import {
+ REACT_COMPILER_OPTIONS,
+ isReactCompilerEnabled,
+ reactCompilerExcludePattern
+} from './react-compiler'
+
+const rendererSource = /\/src\/renderer\/src\/.*\.tsx?$/
+// Only shipped code is compiled; tests, fixtures, mocks and harnesses run as written.
+const testSupport =
+ /\/__(?:mocks|fixtures|tests)__\/|\.(?:test|spec|bench)\.tsx?$|[.-]test-|[.-]fixtures?\.tsx?$/
+const importsVitest = /\bfrom ['"]vitest['"]/
+const runtimeFallback = normalizePath(
+ resolve(import.meta.dirname, 'vitest-compiler-runtime-fallback.ts')
+)
+
+// Why: @vitejs/plugin-react skips the compiler for vitest's server consumer, so call it directly.
+export function vitestReactCompiler(): Plugin[] {
+ if (!isReactCompilerEnabled()) {
+ return []
+ }
+ const excluded = reactCompilerExcludePattern()
+ return [
+ {
+ name: 'vitest-react-compiler',
+ enforce: 'pre',
+ configureVitest({ defineCacheKeyGenerator }) {
+ // Ratchet baselines move files in and out of compilation without touching their source.
+ defineCacheKeyGenerator(({ id }) =>
+ excluded.test(normalizePath(id.split('?')[0])) ? 'react-compiler:excluded' : ''
+ )
+ },
+ async transform(source, id) {
+ const filename = normalizePath(id.split('?')[0])
+ if (
+ !rendererSource.test(filename) ||
+ testSupport.test(filename) ||
+ excluded.test(filename) ||
+ importsVitest.test(source)
+ ) {
+ return null
+ }
+ const { transform } = await import('oxc-transform-react')
+ const result = await transform(filename, source, {
+ jsx: { runtime: 'automatic', development: true },
+ reactCompiler: REACT_COMPILER_OPTIONS,
+ sourcemap: true
+ })
+ const diagnostics = result.errors.map(
+ (e) => `${e.message}${e.codeframe ? `\n${e.codeframe}` : ''}`
+ )
+ if (result.fatal) {
+ this.error(diagnostics.join('\n\n') || `React Compiler transform failed: ${filename}`)
+ }
+ return {
+ code: result.code.replace(
+ /from ["']react\/compiler-runtime["']/,
+ `from ${JSON.stringify(runtimeFallback)}`
+ ),
+ map: result.map
+ }
+ }
+ }
+ ]
+}
diff --git a/config/focus-setting-read-baseline.txt b/config/focus-setting-read-baseline.txt
index 1e553776daa..9e6d01f833d 100644
--- a/config/focus-setting-read-baseline.txt
+++ b/config/focus-setting-read-baseline.txt
@@ -225,7 +225,7 @@
1 src/renderer/src/lib/default-creation-host.ts # the sanctioned reader of the default host
1 src/renderer/src/lib/launch-ai-vault-session.ts
1 src/renderer/src/lib/local-preflight-context.ts
-2 src/renderer/src/lib/provider-runtime-context.ts
+2 src/renderer/src/runtime/hosts/observations/provider-runtime-context.ts
2 src/renderer/src/lib/repo-runtime-owner.ts
1 src/renderer/src/lib/runtime-session-mirror-owners.ts
1 src/renderer/src/lib/runtime-session-mirror-targets.ts
diff --git a/config/host-list-render-baseline.txt b/config/host-list-render-baseline.txt
index b1a39632401..09d3a029300 100644
--- a/config/host-list-render-baseline.txt
+++ b/config/host-list-render-baseline.txt
@@ -7,7 +7,7 @@
1 src/renderer/src/components/settings/browser/profiles/BrowserSessionCookiesSection.tsx
1 src/renderer/src/components/settings/browser/routing/BrowserSshWorkspaceRoutingSetting.tsx
1 src/renderer/src/components/settings/quick-commands/QuickCommandsToolbar.tsx
-1 src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.tsx
+1 src/renderer/src/components/settings/repository/hosts/RepositoryHostSetupsSection.tsx
1 src/renderer/src/components/sidebar/host-admission/ssh/AddRemoteHostSshConfigPicker.tsx
4 src/renderer/src/components/status-bar/SshStatusSegment.tsx
1 src/renderer/src/components/status-bar/resource-usage-popover-body.tsx
diff --git a/config/localization-coverage-allowlist.json b/config/localization-coverage-allowlist.json
index 18549199187..4222e7a5add 100644
--- a/config/localization-coverage-allowlist.json
+++ b/config/localization-coverage-allowlist.json
@@ -60,31 +60,45 @@
"kind": "object-property:keywords",
"text": "ghostty",
"dynamic": false,
- "count": 2
+ "count": 1
+ },
+ {
+ "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts",
+ "kind": "object-property:keywords",
+ "text": "ghostty",
+ "dynamic": false,
+ "count": 1
},
{
"filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts",
"kind": "object-property:keywords",
"text": "Ghostty",
"dynamic": false,
- "count": 2
+ "count": 1
},
{
- "filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts",
+ "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts",
+ "kind": "object-property:keywords",
+ "text": "Ghostty",
+ "dynamic": false,
+ "count": 1
+ },
+ {
+ "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts",
"kind": "object-property:keywords",
"text": "Kitty",
"dynamic": false,
"count": 1
},
{
- "filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts",
+ "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts",
"kind": "object-property:keywords",
"text": "kitty",
"dynamic": false,
"count": 1
},
{
- "filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts",
+ "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts",
"kind": "object-property:keywords",
"text": "kitty.conf",
"dynamic": false,
diff --git a/config/path-literal-baseline.txt b/config/path-literal-baseline.txt
index a0a0ede85ea..3d31a05c9e5 100644
--- a/config/path-literal-baseline.txt
+++ b/config/path-literal-baseline.txt
@@ -6,7 +6,6 @@
config/scripts/performance/session-search/session-search-tool-heavy-corpus.ts src/main/ai-vault/session-transcript-reader.ts
config/scripts/runtime-verification/desktop-transport/run-linux-lid-sleep-assertion-docker.mjs src/main/linux-lid-sleep-assertion.ts
config/scripts/runtime-verification/desktop-transport/run-ssh-staged-upload-reliability.mjs src/main/ssh/ssh-relay-install-namespace.test.ts
-config/scripts/session-search-file-id-e2e/run.ts src/main/ai-vault/session-scanner-service-entry.ts
config/scripts/static-analysis/ratchets/renderer-state/check-layout-writer-ratchets.mjs src/renderer/src/runtime/remote-workspace-frozen/
config/scripts/workflow/source-routing/pr-code-change-scope.mjs src/main/runtime/runtime-worktree-agent-
config/scripts/workflow/source-routing/pr-code-change-scope.mjs src/shared/agent-session-mutation-envelope
diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt
index b1a89fbefe0..c4cd51da520 100644
--- a/config/react-compiler-bailout-baseline.txt
+++ b/config/react-compiler-bailout-baseline.txt
@@ -422,11 +422,11 @@
1 src/renderer/src/components/settings/privacy/PrivacyPane.tsx
1 src/renderer/src/components/settings/quick-commands/QuickCommandsPane.tsx
1 src/renderer/src/components/settings/repository/RepositoryFormatterSection.tsx
-2 src/renderer/src/components/settings/repository/RepositoryGitHubAccountSection.tsx
+2 src/renderer/src/components/settings/repository/source-control/RepositoryGitHubAccountSection.tsx
3 src/renderer/src/components/settings/repository/RepositoryJiraProjectSection.tsx
-2 src/renderer/src/components/settings/repository/execution/RepositoryForkSyncSection.tsx
-3 src/renderer/src/components/settings/repository/execution/RepositoryHostSetupActions.tsx
-2 src/renderer/src/components/settings/repository/execution/SparsePresetSettingsSection.tsx
+2 src/renderer/src/components/settings/repository/source-control/RepositoryForkSyncSection.tsx
+3 src/renderer/src/components/settings/repository/hosts/RepositoryHostSetupActions.tsx
+2 src/renderer/src/components/settings/repository/worktrees/SparsePresetSettingsSection.tsx
2 src/renderer/src/components/settings/repository/identity/RepositoryIconPicker.tsx
1 src/renderer/src/components/settings/repository/mcp/McpConfigSection.tsx
9 src/renderer/src/components/settings/repository/source-control/repository-source-control-ai-global-ux.ts
@@ -441,7 +441,7 @@
1 src/renderer/src/components/settings/session-history/SessionHistoryServerRow.tsx
2 src/renderer/src/components/settings/session-history/SessionHistorySettingsPane.tsx
1 src/renderer/src/components/settings/session-history/SessionSearchAdvancedSection.tsx
-1 src/renderer/src/components/settings/session-history/use-session-search-status.ts
+1 src/renderer/src/components/session-search/use-session-search-status.ts
1 src/renderer/src/components/settings/shortcuts/ShortcutRecorderButton.tsx
2 src/renderer/src/components/settings/source-control/AutoRenameBranchFromWorkSetting.tsx
1 src/renderer/src/components/settings/source-control/CommitMessageAiPane.tsx
@@ -449,7 +449,7 @@
1 src/renderer/src/components/settings/ssh/SshPane.tsx
1 src/renderer/src/components/settings/ssh/server-actions/SshHostDeltaMoveDialog.tsx
1 src/renderer/src/components/settings/ssh/server-actions/SshHostKeepServerVersionDialog.tsx
-1 src/renderer/src/components/settings/ssh/server-actions/SshHostMoveAnywayAction.tsx
+1 src/renderer/src/components/ssh-host-recovery/SshHostMoveAnywayAction.tsx
1 src/renderer/src/components/settings/ssh/server-actions/SshHostRecoverServerAction.tsx
1 src/renderer/src/components/settings/ssh/server-actions/SshHostRestartServerAction.tsx
1 src/renderer/src/components/settings/ssh/ssh-hosts-header-slot.tsx
diff --git a/config/react-compiler-uncompiled-files.txt b/config/react-compiler-uncompiled-files.txt
new file mode 100644
index 00000000000..7c7b729df86
--- /dev/null
+++ b/config/react-compiler-uncompiled-files.txt
@@ -0,0 +1,37 @@
+# Renderer files React Compiler skips; compiled, they would run differently. Hand-maintained.
+# Files in config/render-path-translate-baseline.txt and config/react-compiler-hazard-baseline.txt
+# are skipped too. Remove a line once its file is safe to compile.
+
+# Render-time reads of providerRuntimeSessionGeneration (lib/provider-runtime-context.ts; hazard live-read-in-memo-block).
+src/renderer/src/components/feature-wall/FeatureWallSetupChecklist.tsx
+src/renderer/src/components/feature-wall/use-integration-connection-status.ts
+src/renderer/src/components/integrations/task-trackers/jira-integration-card.tsx
+src/renderer/src/components/integrations/task-trackers/linear-integration-card.tsx
+src/renderer/src/components/new-workspace/use-jira-source-connection.ts
+src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts
+src/renderer/src/components/settings/skills/linear/LinearAgentSkillPane.tsx
+src/renderer/src/components/settings/tasks/use-task-source-provider-readiness.ts
+src/renderer/src/components/sidebar/workspace-card/details/use-worktree-card-review-details.ts
+src/renderer/src/components/task-page/jira/Content.tsx
+src/renderer/src/components/task-page/jira/use-task-page-jira-list-projection.ts
+src/renderer/src/components/task-page/jira/use-task-page-jira-list-state.ts
+src/renderer/src/hooks/use-integration-provider-status-refresh.ts
+
+# structuredSessionSelectionAuthority/Controller read module state the selection lifetime replaces (live-read-in-memo-block).
+src/renderer/src/components/native-chat/session/options/structured/use-structured-agent-session-option-state.ts
+
+# applyTerminalColdActivation mutates controller refs during render on the terminal hot path.
+src/renderer/src/components/use-terminal-controller.ts
+
+# Caches keyed on a TanStack virtualizer, which mutates in place (hazard virtualizer-in-memo-block).
+src/renderer/src/components/editor/combined-diff/scroll-viewport/combined-diff-section-list.tsx
+src/renderer/src/components/editor/markdown-preview/search/use-markdown-preview-search-reveal.ts
+src/renderer/src/components/editor/markdown-preview/viewport/use-markdown-preview-scroll-anchor.ts
+src/renderer/src/components/github-item-dialog/inspect-pull-request/pr-files-combined-diff-body.tsx
+src/renderer/src/components/right-sidebar/file-explorer/panel/FileExplorerVirtualRows.tsx
+src/renderer/src/components/right-sidebar/file-explorer/tree/FileExplorerFilesTreePane.tsx
+src/renderer/src/components/sidebar/worktree-list/viewport/VirtualizedWorktreeViewport.tsx
+
+# The workbench subtree relies on the shell re-rendering on every app render.
+src/renderer/src/app-shell/AppWorkspaceShell.tsx
+src/renderer/src/app-shell/use-app-chrome-layout.ts
diff --git a/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs b/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs
index 7d97c713144..a1d27b2dbec 100644
--- a/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs
+++ b/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs
@@ -5,11 +5,7 @@ import {
withScratch,
copyWrittenBundle
} from '../../mobile-web-app/mobile-web-app-bundle-test-fixture.mjs'
-import {
- bundleMobileWebApp,
- renameOutputsByContent,
- routeChunkNames
-} from './build-mobile-web-app-bundle.mjs'
+import { bundleMobileWebApp } from './build-mobile-web-app-bundle.mjs'
import { MOBILE_WEB_APP_ROUTE_ROOT } from '../../mobile-web-app/mobile-web-app-route-manifest.mjs'
import { verifyMobileWebAppBundle } from './verify-mobile-web-app-bundle.mjs'
import {
@@ -141,33 +137,3 @@ describe('the verifier', () => {
240_000
)
})
-
-describe('naming an output by its bytes', () => {
- it('refuses two outputs that name each other', () => {
- const emitted = (text) => new TextEncoder().encode(text)
- const metafile = {
- outputs: {
- 'dist/a.js': { imports: [{ path: 'dist/b.js', kind: 'import-statement' }] },
- 'dist/b.js': { imports: [{ path: 'dist/a.js', kind: 'import-statement' }] }
- }
- }
- // Cycles have no final dependency names/content hash; fail if esbuild ever stops emitting a DAG.
- expect(() =>
- renameOutputsByContent(metafile, [
- { path: 'dist/a.js', contents: emitted('import "/assets/b.js"') },
- { path: 'dist/b.js', contents: emitted('import "/assets/a.js"') }
- ])
- ).toThrow(/output cycle/)
- })
-
- it('refuses a route it cannot find an output for', async () => {
- await withScratch(async (scratch) => {
- const module = join(scratch, 'index.tsx')
- await writeFile(module, 'export default function Route() { return null }\n')
- // Only metafile maps routes to chunks; missing output must fail before phones request undefined/404.
- expect(() =>
- routeChunkNames({ outputs: {} }, [{ key: './index.tsx', module }], new Map())
- ).toThrow(/\.\/index\.tsx reached no output/)
- })
- })
-})
diff --git a/config/scripts/build/mobile-web-app/mobile-web-bundle-manifest.test.mjs b/config/scripts/build/mobile-web-app/mobile-web-bundle-manifest.test.mjs
deleted file mode 100644
index e00c3366b52..00000000000
--- a/config/scripts/build/mobile-web-app/mobile-web-bundle-manifest.test.mjs
+++ /dev/null
@@ -1,50 +0,0 @@
-import { existsSync } from 'node:fs'
-import { mkdtemp, rm } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { describe, expect, it } from 'vitest'
-import {
- contentTypeForExtension,
- hashedAsset,
- sha256Hex,
- writeMobileWebBundleTree
-} from './mobile-web-bundle-manifest.mjs'
-
-describe('hashedAsset', () => {
- it('refuses an extension with no registered content type', () => {
- // Unknown content type must fail rather than leave phone guessing how to serve addressed bytes.
- expect(() => hashedAsset(Buffer.from('body'), 'wasm')).toThrow(/no content type registered/)
- })
-})
-
-describe('writeMobileWebBundleTree', () => {
- it('marks a dark build outside the manifest, so its buildId is the same tree’s', async () => {
- const outDir = await mkdtemp(join(tmpdir(), 'mobile-web-bundle-manifest-'))
- try {
- const bytes = Buffer.from('\n', 'utf8')
- const tree = (env) =>
- writeMobileWebBundleTree({
- outDir,
- written: [
- {
- path: 'index.html',
- bytes,
- sha256: sha256Hex(bytes),
- byteLength: bytes.byteLength,
- contentType: contentTypeForExtension('html')
- }
- ],
- desktopVersion: '1.0.0',
- protocolWindow: { runtimeProtocolVersion: 3, minCompatibleRuntimeProtocolVersion: 3 },
- env
- })
- const dark = await tree({ ORCA_SIDEBAR_INPUTS: 'main' })
- expect(existsSync(join(outDir, 'ORCA_SIDEBAR_INPUTS_MAIN'))).toBe(true)
- const off = await tree({})
- expect(existsSync(join(outDir, 'ORCA_SIDEBAR_INPUTS_MAIN'))).toBe(false)
- expect(dark.manifest.buildId).toBe(off.manifest.buildId)
- } finally {
- await rm(outDir, { recursive: true, force: true })
- }
- })
-})
diff --git a/config/scripts/build/mobile-web-app/mobile-web-page-routes.test.mjs b/config/scripts/build/mobile-web-app/mobile-web-page-routes.test.mjs
deleted file mode 100644
index eb7522f2543..00000000000
--- a/config/scripts/build/mobile-web-app/mobile-web-page-routes.test.mjs
+++ /dev/null
@@ -1,99 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import {
- MOBILE_WEB_BUNDLE_MAX_ROUTE_GRANTS,
- MobileWebBundleRouteSchema
-} from '../../../../src/shared/mobile-web-bundle/manifest-contract.ts'
-import { resolveMobileWebPageRoutes } from './build-mobile-web-app-bundle.mjs'
-import { MOBILE_WEB_PAGE_ROUTES } from './mobile-web-page-routes.mjs'
-import { routePathnameFromKey } from '../../mobile-web-app/mobile-web-app-route-manifest.mjs'
-
-// Test declared screens separately from bundle mechanics so route inventory can grow without coupling builder test size.
-
-describe('the page routes the manifest declares', () => {
- it('turns a route key into the URL pattern expo-router gives it', () => {
- expect(routePathnameFromKey('./h/[hostId]/index.tsx')).toBe('/h/[hostId]')
- expect(routePathnameFromKey('./h/[hostId]/tasks.tsx')).toBe('/h/[hostId]/tasks')
- expect(routePathnameFromKey('./h/[hostId]/session/[worktreeId].tsx')).toBe(
- '/h/[hostId]/session/[worktreeId]'
- )
- })
-
- it('answers null for a layout, which is not a screen anyone navigates to', () => {
- expect(routePathnameFromKey('./h/_layout.tsx')).toBeNull()
- expect(routePathnameFromKey('./h/[hostId]/_layout.tsx')).toBeNull()
- })
-
- // Synthetic optional-grant input checks member-by-member mapping; newly declared field must survive builder map before reaching phone.
- it('carries an optional grant list through, and writes no key for a route without one', () => {
- expect(
- resolveMobileWebPageRoutes(
- ['./h/[hostId]/index.tsx', './h/[hostId]/tasks.tsx'],
- [
- {
- pathname: '/h/[hostId]',
- grants: ['navigate'],
- optionalGrants: ['externalNavigation']
- },
- { pathname: '/h/[hostId]/tasks', grants: ['navigate'], optionalGrants: [] }
- ]
- )
- ).toEqual([
- { pathname: '/h/[hostId]', grants: ['navigate'], optionalGrants: ['externalNavigation'] },
- { pathname: '/h/[hostId]/tasks', grants: ['navigate'] }
- ])
- })
-
- it('carries the host-area declaration through, and writes no key where there is none', () => {
- expect(
- resolveMobileWebPageRoutes(
- ['./h/[hostId]/index.tsx', './h/[hostId]/tasks.tsx'],
- [
- { pathname: '/h/[hostId]', grants: ['navigate'], canOwnHostArea: true },
- { pathname: '/h/[hostId]/tasks', grants: ['navigate'] }
- ]
- )
- ).toEqual([
- { pathname: '/h/[hostId]', grants: ['navigate'], canOwnHostArea: true },
- { pathname: '/h/[hostId]/tasks', grants: ['navigate'] }
- ])
- })
-
- /**
- * The wide iPad's host-area session is granted every served route's list, so its in-page hops
- * stay in the page. Bounded by what one route can be granted, so that grant never outgrows one route's.
- */
-
- // The phone refuses the whole manifest over one bad route, which takes every page down.
- it('declares only routes the manifest schema accepts', () => {
- for (const route of MOBILE_WEB_PAGE_ROUTES) {
- expect(
- MobileWebBundleRouteSchema.safeParse(route).error?.issues ?? [],
- route.pathname
- ).toEqual([])
- }
- })
-
- it('holds the optional lane to the manifest grammar and its own ceiling', () => {
- // Released shells read each list against the ceiling on its own, so the writer bounds each the same way.
- const withOptional = (optionalGrants, grants = []) =>
- MobileWebBundleRouteSchema.safeParse({ pathname: '/h/[hostId]', grants, optionalGrants })
- .success
- expect(withOptional(['externalNavigation'])).toBe(true)
- expect(withOptional(['native.externalNavigation'])).toBe(false)
- const names = (count, prefix) =>
- Array.from({ length: count }, (_value, index) => `${prefix}${String(index)}`)
- const cap = MOBILE_WEB_BUNDLE_MAX_ROUTE_GRANTS
- expect(withOptional(names(cap, 'opt'), names(cap, 'req'))).toBe(true)
- expect(withOptional(names(cap + 1, 'opt'))).toBe(false)
- })
-
- it('fails the build on a declaration the bundle cannot render', () => {
- // Declared-but-unbundled route opens page then paints Unmatched; catch mismatch at declaration.
- expect(() =>
- resolveMobileWebPageRoutes(
- ['./h/[hostId]/index.tsx'],
- [{ pathname: '/h/[hostId]/gone', grants: [] }]
- )
- ).toThrow('has no module in the bundle')
- })
-})
diff --git a/config/scripts/build/mobile-web-app/mobile-web-source-line-endings.test.mjs b/config/scripts/build/mobile-web-app/mobile-web-source-line-endings.test.mjs
deleted file mode 100644
index e5df4594bb8..00000000000
--- a/config/scripts/build/mobile-web-app/mobile-web-source-line-endings.test.mjs
+++ /dev/null
@@ -1,19 +0,0 @@
-import { mkdtemp, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { describe, expect, it } from 'vitest'
-import { assertNoCarriageReturnsInSource } from './mobile-web-source-line-endings.mjs'
-
-describe('assertNoCarriageReturnsInSource', () => {
- it('rejects a CRLF source file, because CRLF changes every asset hash and the buildId', async () => {
- const scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-eol-'))
- try {
- await writeFile(join(scratch, 'route.tsx'), 'const a = 1\r\nconst b = 2\r\n', 'utf8')
- await expect(assertNoCarriageReturnsInSource(scratch)).rejects.toThrow(
- /CRLF in mobile web source/
- )
- } finally {
- await rm(scratch, { recursive: true, force: true })
- }
- })
-})
diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json
index 2a25d38facd..da79a66c8cf 100644
--- a/config/scripts/ci/sharding/ci-shard-timings.json
+++ b/config/scripts/ci/sharding/ci-shard-timings.json
@@ -5190,8 +5190,8 @@
"src/renderer/src/components/github/github-work-item-mutation-target.test.ts": 348,
"src/renderer/src/components/github/use-image-input.test.ts": 2619,
"src/renderer/src/components/gitlab-item-dialog/use-gitlab-primary-actions.test.ts": 2141,
- "src/renderer/src/components/host-picker/bounded-host-list.test.tsx": 667,
- "src/renderer/src/components/host-picker/host-list-surfaces.large-config.test.tsx": 2963,
+ "src/renderer/src/components/host-picker/HostListSearchField.test.tsx": 667,
+ "src/renderer/src/components/sidebar/project-admission/host-selection/AddRepoHostSelector.large-config.test.tsx": 2963,
"src/renderer/src/components/jira-attachment-image.test.tsx": 2117,
"src/renderer/src/components/jira-connect-scoped-token.test.tsx": 1047,
"src/renderer/src/components/jira-issue-assignee-control.test.tsx": 2875,
@@ -5606,7 +5606,7 @@
"src/renderer/src/components/settings/form-controls/SettingsFormControls.segmented-control.test.tsx": 730,
"src/renderer/src/components/settings/shortcuts/ShortcutFilterRail.test.ts": 273,
"src/renderer/src/components/settings/shortcuts/ShortcutsPane.provenance.test.tsx": 2302,
- "src/renderer/src/components/settings/repository/execution/SparsePresetSettingsSection.test.tsx": 744,
+ "src/renderer/src/components/settings/repository/worktrees/SparsePresetSettingsSection.test.tsx": 744,
"src/renderer/src/components/settings/ssh/server-actions/SshHostDeltaMoveDialog.test.tsx": 438,
"src/renderer/src/components/settings/ssh/server-actions/SshHostRecoverServerAction.test.tsx": 669,
"src/renderer/src/components/settings/ssh/SshPane.test.tsx": 1699,
@@ -5636,23 +5636,23 @@
"src/renderer/src/components/settings/notifications/notification-host-pending-save.test.tsx": 2029,
"src/renderer/src/components/settings/repository/RepositoryJiraProjectSection.test.tsx": 463,
"src/renderer/src/components/settings/repository/RepositoryPaneDraftInput.test.tsx": 314,
- "src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.settings-entry.test.tsx": 2007,
- "src/renderer/src/components/settings/repository/execution/RepositoryWorktreeDefaultsSection.test.tsx": 495,
+ "src/renderer/src/components/settings/repository/hosts/RepositoryHostSetupsSection.settings-entry.test.tsx": 2007,
+ "src/renderer/src/components/settings/repository/worktrees/RepositoryWorktreeDefaultsSection.test.tsx": 495,
"src/renderer/src/components/settings/repository/identity/RepositoryIconPicker.github-avatar-refresh.test.tsx": 615,
"src/renderer/src/components/settings/runtime-environments/pairing/runtime-share-computer-button.test.tsx": 2092,
"src/renderer/src/components/settings/navigation/settings-project-list.test.ts": 99,
"src/renderer/src/components/settings/source-control/source-control-action-card-layout.test.tsx": 4551,
"src/renderer/src/components/settings/source-control/source-control-action-permission-draft.test.tsx": 6938,
- "src/renderer/src/components/settings/ssh/targets/ssh-target-draft.test.ts": 72,
+ "src/renderer/src/components/ssh-host-form/ssh-target-draft.test.ts": 72,
"src/renderer/src/components/settings/ssh/targets/ssh-target-list-model.test.ts": 56,
"src/renderer/src/components/integrations/task-trackers/linear-integration-card.test.tsx": 1414,
"src/renderer/src/components/settings/appearance/themes/use-catalog-app-themes.test.ts": 2159,
"src/renderer/src/components/settings/form-controls/use-debounced-settings-text-draft.test.ts": 308,
- "src/renderer/src/components/settings/repository/execution/use-repository-hook-settings-draft.test.tsx": 586,
+ "src/renderer/src/components/settings/repository/hooks/use-repository-hook-settings-draft.test.tsx": 586,
"src/renderer/src/components/settings/repository/hooks/use-repository-issue-command-wsl-stopped.test.ts": 523,
"src/renderer/src/components/settings/runtime-environments/catalog/use-runtime-environment-catalog.test.tsx": 2252,
"src/renderer/src/components/settings/runtime-environments/catalog/use-runtime-environment-mutation-actions.test.tsx": 2069,
- "src/renderer/src/components/settings/session-history/use-session-search-status.test.tsx": 477,
+ "src/renderer/src/components/session-search/use-session-search-status.test.tsx": 477,
"src/renderer/src/components/settings/accounts/usage/use-zcode-plan-credentials.test.tsx": 880,
"src/renderer/src/lib/directory-path-suggestion-filter.scan-budget.test.ts": 68,
"src/renderer/src/lib/directory-path-suggestion-filter.test.ts": 51,
diff --git a/config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs b/config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs
deleted file mode 100644
index 400546950fb..00000000000
--- a/config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs
+++ /dev/null
@@ -1,118 +0,0 @@
-import assert from 'node:assert/strict'
-import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
-import { join, resolve } from 'node:path'
-import { parse } from 'yaml'
-import { runProcessSync } from '@orca/process-host'
-import { auditToolEntry, installAuditTools } from './run-audit-tool.mjs'
-
-const root = resolve(import.meta.dirname, '../../../..')
-const installed = installAuditTools(root)
-assert.equal(installed.code, 0, 'Frozen, script-free audit tool install failed')
-
-const scratch = join(root, 'tmp')
-mkdirSync(scratch, { recursive: true })
-const fixture = mkdtempSync(join(scratch, 'locked audit tools '))
-const toolManifest = JSON.parse(readFileSync(join(root, 'config/audit-tools/package.json'), 'utf8'))
-
-function command(program, args, expectedCode = 0) {
- const result = runProcessSync({ program, args, cwd: fixture, timeoutMs: 60_000 })
- assert.equal(result.timedOut, false, `${program} timed out`)
- assert.equal(result.signal, null, `${program} received ${result.signal}`)
- assert.equal(result.code, expectedCode, `${result.stdout}\n${result.stderr}`)
- return result.stdout
-}
-
-function tool(name, args, expectedCode = 0) {
- return command(process.execPath, [auditToolEntry(name, root), ...args], expectedCode)
-}
-
-function write(file, value) {
- writeFileSync(join(fixture, file), value)
-}
-
-const cleanComponent = 'export default function App() { return }\n'
-const indexKeyComponent =
- 'export default function App() { return
{["one"].map((text, index) => {text})}
}\n'
-const doctorArgs = [
- '.',
- '--yes',
- '--no-dead-code',
- '--no-supply-chain',
- '--no-telemetry',
- '--no-cache',
- '--json',
- '--blocking',
- 'warning'
-]
-
-try {
- command('git', ['init', '--quiet'])
- command('git', ['config', 'core.hooksPath', join(fixture, '.git', 'disabled-hooks')])
- command('git', ['config', 'commit.gpgSign', 'false'])
- write(
- 'package.json',
- JSON.stringify({ name: 'locked-audit-smoke', private: true, dependencies: { react: '19.2.8' } })
- )
- write('App.tsx', cleanComponent)
- write('knip.json', JSON.stringify({ entry: ['App.tsx'], project: ['*.tsx'] }))
-
- for (const name of ['react-doctor', 'knip']) {
- assert.equal(tool(name, ['--version']).trim(), toolManifest.dependencies[name])
- }
-
- const clean = JSON.parse(tool('react-doctor', doctorArgs))
- assert.equal(clean.ok, true)
- assert.ok(clean.projects.some((project) => project.analyzedFiles.includes('App.tsx')))
- tool('knip', ['--config', 'knip.json', '--files'])
-
- write('App.tsx', indexKeyComponent)
- command('git', ['add', '.'])
- command('git', [
- '-c',
- 'user.name=Audit tool smoke',
- '-c',
- 'user.email=audit-smoke@example.invalid',
- 'commit',
- '--quiet',
- '-m',
- 'Baseline'
- ])
- write('Changed.tsx', indexKeyComponent.replace('function App', 'function Changed'))
- command('git', ['add', 'Changed.tsx'])
- const changed = JSON.parse(
- tool('react-doctor', [...doctorArgs, '--scope', 'lines', '--base', 'HEAD'], 1)
- )
- assert.ok(changed.diagnostics.some((item) => item.filePath.endsWith('Changed.tsx')))
- assert.ok(changed.diagnostics.every((item) => !item.filePath.endsWith('App.tsx')))
-
- write('Orphan.tsx', 'export const orphan = true\n')
- assert.match(tool('knip', ['--config', 'knip.json', '--files'], 1), /Orphan\.tsx/)
-
- const stale = join(fixture, 'config', 'audit-tools')
- mkdirSync(stale, { recursive: true })
- mkdirSync(join(fixture, 'config', 'patches'), { recursive: true })
- const toolPolicy = parse(
- readFileSync(join(root, 'config/audit-tools/pnpm-workspace.yaml'), 'utf8')
- )
- for (const patch of Object.values(toolPolicy.patchedDependencies ?? {})) {
- copyFileSync(join(root, 'config/audit-tools', patch), join(stale, patch))
- }
- for (const file of ['pnpm-lock.yaml', 'pnpm-workspace.yaml']) {
- copyFileSync(join(root, 'config', 'audit-tools', file), join(stale, file))
- }
- writeFileSync(
- join(stale, 'package.json'),
- JSON.stringify({
- ...toolManifest,
- dependencies: { ...toolManifest.dependencies, knip: '0.0.0' }
- })
- )
- const rejected = installAuditTools(fixture, (spec) => runProcessSync({ ...spec, stdio: 'pipe' }))
- assert.notEqual(rejected.code, 0, 'A stale tool lockfile was accepted')
- assert.match(`${rejected.stdout}\n${rejected.stderr}`, /OUTDATED_LOCKFILE/)
- console.log(
- 'Locked audit tools: real analysis, changed-line filtering, findings and stale-lock rejection passed'
- )
-} finally {
- rmSync(fixture, { recursive: true, force: true })
-}
diff --git a/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs b/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs
index 047a8d72c74..f9ddb0587af 100644
--- a/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs
+++ b/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs
@@ -1,4 +1,4 @@
-import { mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import process from 'node:process'
@@ -36,29 +36,4 @@ describe('validate-plugin-files', () => {
expect(result.code).toBe(1)
expect(result.stderr).toContain('panel/index.html')
}, 60_000)
-
- it('passes a scaffolded plugin, explaining why there is no release entry outside Git', async () => {
- const dir = path.join(await tempRoot(), 'dusk')
- await createPluginFromTemplate({ dir, template: 'theme', publisher: 'acme' })
- const result = await validate(dir)
- expect(result.code, result.stderr).toBe(0)
- expect(result.stdout).toContain('not in a Git repository')
- }, 60_000)
-
- it('passes a language pack that translates protected copy, warning that Orca ignores it', async () => {
- const dir = path.join(await tempRoot(), 'portuguese')
- await createPluginFromTemplate({ dir, template: 'language-pack', publisher: 'acme' })
- await writeFile(
- path.join(dir, 'locales', 'pt-BR.json'),
- JSON.stringify({
- common: { cancel: 'Cancelar' },
- components: { 'native-chat': { approval: { allow: 'Permitir', deny: 'Negar' } } }
- })
- )
- const result = await validate(dir)
- expect(result.code, result.stderr).toBe(0)
- expect(result.stderr).toContain(
- 'warning: contributes.languagePacks "pt-BR" (locales/pt-BR.json): 2 protected strings are ignored'
- )
- }, 60_000)
})
diff --git a/config/scripts/preflight/changed-checks/check-changed-selection.mjs b/config/scripts/preflight/changed-checks/check-changed-selection.mjs
index 3bf510cc912..99d3c46bff0 100644
--- a/config/scripts/preflight/changed-checks/check-changed-selection.mjs
+++ b/config/scripts/preflight/changed-checks/check-changed-selection.mjs
@@ -272,6 +272,7 @@ const RATCHET_SHARED_MODULES = {
'config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs': [
'check-react-compiler-compat-ratchet.mjs'
],
+ 'config/react-compiler-uncompiled-files.txt': ['check-react-compiler-compat-ratchet.mjs'],
'config/scripts/localization/reactive-translate/render-path-translate.mjs': [
'check-render-path-translate-ratchet.mjs'
]
diff --git a/config/scripts/session-search-file-id-e2e/README.md b/config/scripts/session-search-file-id-e2e/README.md
deleted file mode 100644
index ae1de7fd994..00000000000
--- a/config/scripts/session-search-file-id-e2e/README.md
+++ /dev/null
@@ -1,80 +0,0 @@
-# Windows session-search file-ID integration reproduction
-
-Opt-in Windows/NTFS harness for #20551. Run from the fix workspace root with
-dependencies, the Electron binary, and Git object `9845bef63a6` available.
-Everything generated stays under ignored `notes/search-ipc/`; each run gets fresh
-roots and a profile. No real transcripts, WSL discovery, desktop windows, or user
-profile are used. The synthetic file is recreated until NTFS assigns a real inode
-above `Number.MAX_SAFE_INTEGER`; failure to obtain one fails the test.
-
-```powershell
-$env:ORCA_BACKGROUND_LAUNCH='1'
-pnpm exec esbuild config/scripts/session-search-file-id-e2e/run.ts --bundle --platform=node --format=esm --packages=external --outfile=notes/search-ipc/run.mjs
-node notes/search-ipc/run.mjs red
-# Expected exit 1: initial indexing/query succeeds, subsequent reconciliation fails.
-node notes/search-ipc/run.mjs green
-# Expected exit 0 for both the lifecycle and fresh-host restart phases.
-node config/scripts/session-search-file-id-e2e/verify.cjs
-```
-
-Run red and green sequentially: their build step reuses the exported source tree.
-The verifier checks the expected red failure, green reports, identical oracle
-expressions after formatting normalization, and that exactly the two file-ID
-SELECT source files differ. It does not turn an arbitrary red failure into success.
-
-## Exact topology
-
-The runner exports **LOCAL integration overlay** #20516 head
-`9845bef63a6d0b80ec37af82b5b275287b8e17df` with `git archive`, then bundles the real
-scanner entry and parent modules with esbuild. It does not check out, stage, or
-push overlay sources. Green changes only the two SELECT projections to the CAST
-expressions in #20551; red retains the original projections. CLI #20514 is unused.
-
-An isolated, windowless Electron host installs the production child search
-enablement using fixture settings. The production shared scanner client invokes
-`spawnAiVaultServiceProcess`, which forks Electron with `ELECTRON_RUN_AS_NODE=1`
-and the real `session-scanner-service-entry`. That child owns the production
-instance, indexer, SQLite search engine, and IPC request handling.
-
-Marker queries come from **separate Node client processes over a real Windows
-named pipe**, through production `UnixSocketTransport`, production `RpcDispatcher`
-and `AI_VAULT_METHODS`, then the search registry/service and scanner IPC. Status
-polls and default-off/disabled responses also exercise registered handlers directly.
-An independent read-only SQLite connection verifies active FTS rows and committed
-file metadata against filesystem size/mtime. The transcript-consumer observation
-logs actual replace/append modes without supplying messages or search results.
-
-Labelled fixture seams, identical in both variants:
-
-- Parent root resolution returns the existing `isolatedScanRoots` fixture.
-- `getSettings` supplies the isolated JSON policy; real enablement/settings-change functions apply it.
-- The child's allowlisted environment includes `ORCA_BACKGROUND_LAUNCH=1`.
-- Passive child PID, IPC, stderr, and transcript-read observations are added.
-- The unused default RPC method catalog is excluded; the dispatcher receives the production `AI_VAULT_METHODS` explicitly. Its runtime context supplies only a fixture runtime ID.
-
-## Oracle and evidence
-
-Default-off creates no DB and returns disabled. Enablement indexes the marker;
-two **real default 20-second recent timer cycles** and two explicit full passes
-preserve it. An append becomes searchable; a rename replacement with equal byte
-length and exactly restored mtime removes the old marker and adds the new one.
-The scanner restarts, then a second Electron host opens the same profile/DB and
-queries again. Disablement followed by an append, explicit reconcile, and 21-second
-wait leaves the DB unchanged and the new marker absent.
-
-`red-latest.json` / `green-latest.json` locate each run. Reports contain parent and
-scanner PIDs, executable/Node/Electron versions, IPC events, raw unsafe inode,
-queries, DB metadata, read modes, and scanner exit codes. `*-stages.jsonl` gives
-live progress; `process-*.log` preserves complete output. `comparison.json` records
-the two-source-only comparison. The production scanner shutdown protocol closes
-only recorded children; the runner waits for its own Electron hosts and external
-clients. Profiles/DBs remain as evidence, not running services.
-
-## Boundaries not exercised
-
-This is not a packaged/full Orca desktop launch. The host and scanner are bundled
-from production sources by this harness, not electron-vite's complete app build.
-The actual runtime authentication/metadata server, CLI routing, remote SSH/relay
-transport, and UI are not exercised. Named-pipe framing and dispatcher are real,
-but the harness connects them directly with a fixture token; it makes no claim
-about production authentication. No session-search UI exists in this topology.
diff --git a/config/scripts/session-search-file-id-e2e/client.cjs b/config/scripts/session-search-file-id-e2e/client.cjs
deleted file mode 100644
index 1922547f6ac..00000000000
--- a/config/scripts/session-search-file-id-e2e/client.cjs
+++ /dev/null
@@ -1,30 +0,0 @@
-const { connect } = require('node:net')
-const assert = require('node:assert/strict')
-assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1')
-const socket = connect(process.argv[2])
-let buffer = ''
-socket.setEncoding('utf8')
-socket.setTimeout(10_000, () => socket.destroy(new Error('RPC client timeout')))
-socket.on('connect', () =>
- socket.write(
- `${JSON.stringify({
- id: 'file-id-query',
- authToken: 'isolated-fixture',
- method: 'aiVault.searchSessions',
- params: JSON.parse(process.argv[3])
- })}\n`
- )
-)
-socket.on('data', (chunk) => {
- buffer += String(chunk)
- const newline = buffer.indexOf('\n')
- if (newline === -1) {
- return
- }
- console.log(JSON.stringify({ pid: process.pid, response: JSON.parse(buffer.slice(0, newline)) }))
- socket.end()
-})
-socket.on('error', (error) => {
- console.error(error)
- process.exitCode = 1
-})
diff --git a/config/scripts/session-search-file-id-e2e/host.cjs b/config/scripts/session-search-file-id-e2e/host.cjs
deleted file mode 100644
index 17ddbb21ff8..00000000000
--- a/config/scripts/session-search-file-id-e2e/host.cjs
+++ /dev/null
@@ -1,325 +0,0 @@
-const { app } = require('electron')
-const assert = require('node:assert/strict')
-const fs = require('node:fs/promises')
-const { existsSync, appendFileSync } = require('node:fs')
-const { join } = require('node:path')
-const { DatabaseSync } = require('node:sqlite')
-const output = process.argv[2]
-const phase = process.argv[3]
-const profile = join(output, 'profile')
-app.setPath('userData', profile)
-app.setPath('sessionData', join(profile, 'chromium'))
-app.disableHardwareAcceleration()
-globalThis.__fileIdChildren = []
-const report = {
- phase,
- pid: process.pid,
- execPath: process.execPath,
- versions: process.versions,
- stages: [],
- children: [],
- stderr: [],
- ipc: []
-}
-globalThis.__fileIdObserveChild = (child) => {
- globalThis.__fileIdChildren.push(child)
- child.stderr.on('data', (chunk) => report.stderr.push(String(chunk)))
- child.on('message', (message) =>
- report.ipc.push({ pid: child.pid, type: message.type, operation: message.operation })
- )
-}
-const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
-const sessionId = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'
-const markers = {
- initial: 'quartzinitialmarker',
- append: 'cobaltappendedmarker',
- replacement: 'velvetreplacedmarker',
- disabled: 'tungstendisabledmarker'
-}
-let api
-let registration
-let transport
-const endpoint = `\\\\.\\pipe\\orca-file-id-${process.pid}`
-let settings = {}
-let transcript
-const database = join(profile, 'ai-vault', 'session-search.sqlite')
-function record(stage, data = {}) {
- const entry = { stage, at: Date.now(), ...data }
- report.stages.push(entry)
- appendFileSync(join(output, `${phase}-stages.jsonl`), `${JSON.stringify(entry)}\n`)
- console.log(stage, JSON.stringify(data))
-}
-function inspect(marker) {
- const db = new DatabaseSync(database, { readOnly: true })
- try {
- const query = db.prepare(
- 'SELECT CAST(ino AS TEXT) AS ino, byte_offset, size_bytes, mtime_ms FROM files WHERE path = ?'
- )
- const rows = db
- .prepare(`SELECT s.session_id FROM messages_fts f JOIN messages m ON m.id=f.rowid
- JOIN sessions s ON s.id=m.session_row_id WHERE messages_fts MATCH ?`)
- .all(marker)
- return { file: query.get(transcript), sessions: rows.map((row) => row.session_id) }
- } finally {
- db.close()
- }
-}
-async function query(marker, present) {
- const result = await api.runProcess({
- program: process.env.ORCA_FILE_ID_NODE,
- args: [
- join(output, 'client.cjs'),
- endpoint,
- JSON.stringify({ query: `"${marker}"`, scope: 'conversation', freshness: 'indexed' })
- ],
- env: process.env,
- timeoutMs: 15_000
- })
- assert.equal(result.code, 0, result.stderr)
- const external = JSON.parse(result.stdout)
- assert.equal(external.response.ok, true, JSON.stringify(external))
- const response = external.response.result
- assert.equal(response.kind, 'results', JSON.stringify(response))
- assert.equal(
- response.hits.some((hit) => hit.sessionId === sessionId),
- present,
- `RPC ${marker}`
- )
- const disk = inspect(marker)
- assert.equal(disk.sessions.includes(sessionId), present, `DB ${marker}`)
- const actual = await fs.stat(transcript)
- assert.equal(
- disk.file.byte_offset,
- actual.size,
- 'Committed cursor covers actual transcript bytes'
- )
- assert.equal(disk.file.size_bytes, actual.size)
- assert.equal(disk.file.mtime_ms, actual.mtimeMs)
- record('query', { marker, present, clientPid: external.pid, endpoint, response, disk })
-}
-async function status() {
- return api.rpc('aiVault.searchStatus', {})
-}
-async function waitFor(predicate, label, timeout = 30_000) {
- const until = Date.now() + timeout
- while (Date.now() < until) {
- const current = await status()
- if (predicate(current)) {
- return current
- }
- await sleep(200)
- }
- throw new Error(`Timed out: ${label}`)
-}
-async function policy(next) {
- const before = settings
- settings = next
- await fs.writeFile(join(profile, 'fixture-settings.json'), JSON.stringify(settings))
- api.applySessionSearchSettingsChange(before, settings)
-}
-async function stopChild() {
- const children = [...globalThis.__fileIdChildren]
- api.resetAiVaultScannerServiceForTests()
- for (const child of children) {
- const until = Date.now() + 5000
- while (child.exitCode === null && child.signalCode === null && Date.now() < until) {
- await sleep(50)
- }
- assert.ok(
- child.exitCode !== null || child.signalCode !== null,
- `Child ${child.pid} did not exit`
- )
- if (!report.children.some((row) => row.pid === child.pid)) {
- report.children.push({
- pid: child.pid,
- spawnfile: child.spawnfile,
- spawnargs: child.spawnargs,
- exitCode: child.exitCode,
- signalCode: child.signalCode
- })
- }
- }
-}
-async function run() {
- assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1')
- await fs.mkdir(profile, { recursive: true })
- api = require('./production.js')
- api.setAppEnvironment({
- getPath: (name) => (name === 'userData' ? profile : app.getPath(name)),
- getAppPath: () => output,
- getVersion: () => app.getVersion(),
- isPackaged: () => false,
- onWillQuit: (handler) => app.on('will-quit', handler),
- exit: (code) => app.exit(code),
- getAppMetrics: () => app.getAppMetrics()
- })
- const dispatcher = new api.RpcDispatcher({
- methods: api.AI_VAULT_METHODS,
- runtime: { getRuntimeId: () => `file-id-${process.pid}` }
- })
- transport = new api.UnixSocketTransport({ endpoint, kind: 'named-pipe' })
- transport.onMessage((message, reply) => {
- void dispatcher
- .dispatch(JSON.parse(message))
- .then((response) => reply(JSON.stringify(response)))
- })
- await transport.start()
- record('rpc-transport', {
- endpoint,
- auth: 'fixture; production auth/metadata server not booted',
- methods: 'production AI_VAULT_METHODS',
- dispatcher: 'production RpcDispatcher'
- })
- const roots = {
- ...api.isolatedScanRoots(join(output, 'roots')),
- wslHomeDirs: [],
- additionalCodexSessionsDirs: [],
- executionHostId: 'local'
- }
- process.env.ORCA_FILE_ID_ROOTS = JSON.stringify(roots)
- await fs.mkdir(roots.claudeProjectsDir, { recursive: true })
- transcript = join(roots.claudeProjectsDir, `${sessionId}.jsonl`)
- if (phase === 'restart') {
- settings = JSON.parse(await fs.readFile(join(profile, 'fixture-settings.json'), 'utf8'))
- assert.equal(settings.aiVaultSearch.enabled, true)
- const beforeRestart = inspect(markers.replacement)
- registration = api.installChildSessionSearchService({
- dataRoot: profile,
- getSettings: () => settings
- })
- await waitFor((s) => s.filesIndexed === 1 && s.phase === 'current', 'Electron host restart')
- await query(markers.append, false)
- await query(markers.replacement, true)
- assert.deepEqual(inspect(markers.replacement), beforeRestart)
- record('app-host-restart-same-db')
- await disableAndCheck()
- return
- }
- const body = `${api.claudeLines([markers.initial], sessionId, 0).join('\n')}\n`
- await fs.writeFile(transcript, body)
- let raw = await fs.stat(transcript, { bigint: true })
- for (let n = 0; raw.ino <= BigInt(Number.MAX_SAFE_INTEGER) && n < 512; n++) {
- await fs.unlink(transcript)
- await fs.writeFile(transcript, body)
- raw = await fs.stat(transcript, { bigint: true })
- }
- assert.ok(raw.ino > BigInt(Number.MAX_SAFE_INTEGER), 'NTFS must supply an actual unsafe inode')
- record('fixture', {
- transcript,
- rawIno: raw.ino.toString(),
- numericIno: BigInt(Number(raw.ino)).toString()
- })
- registration = api.installChildSessionSearchService({
- dataRoot: profile,
- getSettings: () => settings
- })
- assert.ok(registration)
- assert.equal((await status()).enabled, false)
- assert.deepEqual(await api.rpc('aiVault.searchSessions', { query: markers.initial }), {
- kind: 'unavailable',
- reason: 'disabled'
- })
- assert.equal(existsSync(database), false)
- record('default-off')
- await policy({ aiVaultSearch: { enabled: true, historyDays: null } })
- const initial = await waitFor(
- (s) => s.filesIndexed === 1 && s.phase === 'current',
- 'initial indexing'
- )
- assert.equal(inspect(markers.initial).file.ino, BigInt(Number(raw.ino)).toString())
- await query(markers.initial, true)
- record('initial-indexing', { status: initial })
- let recent = initial
- for (let n = 0; n < 2; n++) {
- const previous = recent
- recent = await waitFor(
- (s) => s.lastReconcileAt > previous.lastReconcileAt,
- 'recent timer reconciliation'
- )
- assert.equal(
- recent.lastSweepCompletedAt,
- initial.lastSweepCompletedAt,
- 'Expected a recent pass'
- )
- await query(markers.initial, true)
- record('recent-pass', { status: recent })
- }
- for (let n = 0; n < 2; n++) {
- await api.reconcileSessionSearchInService()
- await query(markers.initial, true)
- record('full-pass', { status: await status() })
- }
- await fs.appendFile(
- transcript,
- `${api.claudeLines([markers.append], sessionId, 10).join('\n')}\n`
- )
- const frozen = new Date(Math.floor((await fs.stat(transcript)).mtimeMs))
- await fs.utimes(transcript, frozen, frozen)
- await api.reconcileSessionSearchInService()
- await query(markers.append, true)
- const before = await fs.stat(transcript)
- const replacement = `${transcript}.replacement`
- const replacementBody = (await fs.readFile(transcript, 'utf8')).replaceAll(
- markers.append,
- markers.replacement
- )
- assert.equal(Buffer.byteLength(replacementBody), before.size)
- await fs.writeFile(replacement, replacementBody)
- await fs.rename(replacement, transcript)
- await fs.utimes(transcript, before.atime, before.mtime)
- const after = await fs.stat(transcript)
- assert.equal(after.size, before.size)
- assert.equal(after.mtimeMs, before.mtimeMs)
- assert.notEqual(after.ino, before.ino)
- await api.reconcileSessionSearchInService()
- await query(markers.append, false)
- await query(markers.replacement, true)
- record('replacement', { beforeIno: before.ino, afterIno: after.ino })
- await stopChild()
- await waitFor((s) => s.filesIndexed === 1 && s.phase === 'current', 'scanner restart')
- await query(markers.append, false)
- await query(markers.replacement, true)
- record('service-restart')
-}
-async function disableAndCheck() {
- await policy({ aiVaultSearch: { enabled: false, historyDays: null } })
- await waitFor((s) => !s.enabled, 'disable')
- const snapshot = inspect(markers.replacement)
- await fs.appendFile(
- transcript,
- `${api.claudeLines([markers.disabled], sessionId, 20).join('\n')}\n`
- )
- await api.reconcileSessionSearchInService()
- await sleep(21_000)
- assert.deepEqual(await api.rpc('aiVault.searchSessions', { query: markers.disabled }), {
- kind: 'unavailable',
- reason: 'disabled'
- })
- assert.deepEqual(inspect(markers.replacement), snapshot)
- assert.deepEqual(inspect(markers.disabled).sessions, [])
- record('disabled-no-indexing')
-}
-app.whenReady().then(async () => {
- try {
- await run()
- report.ok = true
- } catch (error) {
- report.ok = false
- report.error = error.stack
- console.error(error)
- } finally {
- registration?.dispose()
- await transport?.stop()
- if (api) {
- await stopChild().catch((error) => {
- report.cleanupError = String(error)
- report.ok = false
- })
- }
- if (report.stderr.some((text) => text.includes('[ai-vault-search]'))) {
- report.ok = false
- }
- await fs.writeFile(join(output, `report-${phase}.json`), JSON.stringify(report, null, 2))
- app.exit(report.ok ? 0 : 1)
- }
-})
diff --git a/config/scripts/session-search-file-id-e2e/run.ts b/config/scripts/session-search-file-id-e2e/run.ts
deleted file mode 100644
index 3ab6b5ae15d..00000000000
--- a/config/scripts/session-search-file-id-e2e/run.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-import assert from 'node:assert/strict'
-import { mkdir, readFile, writeFile, copyFile } from 'node:fs/promises'
-import { resolve, join, relative } from 'node:path'
-import { createHash } from 'node:crypto'
-import { build } from 'esbuild'
-import { runProcess } from '@orca/process-host'
-
-const root = process.cwd()
-const evidence = resolve('notes/search-ipc')
-const overlay = join(evidence, 'overlay')
-const wiring = '9845bef63a6'
-const mode = process.argv[2]
-assert.equal(process.platform, 'win32', 'This harness requires native Windows and NTFS')
-assert.ok(mode === 'red' || mode === 'green', 'Pass red or green')
-assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1')
-const output = join(evidence, mode, String(Date.now()))
-await mkdir(output, { recursive: true })
-
-async function command(program: string, args: string[]) {
- const result = await runProcess({ program, args, cwd: root, timeoutMs: 120_000 })
- assert.equal(result.code, 0, result.stderr)
- return result.stdout.trim()
-}
-
-// The overlay is exported, never checked out or staged on the fix branch.
-await mkdir(overlay, { recursive: true })
-await command('git', [
- 'archive',
- '--format=tar',
- `--output=${join(evidence, 'overlay.tar')}`,
- wiring,
- 'src'
-])
-await command('tar', [
- '-xf',
- relative(root, join(evidence, 'overlay.tar')),
- '-C',
- relative(root, overlay)
-])
-const edits: { path: string; sha256: string }[] = []
-function replaceOnce(source: string, before: string, after: string) {
- assert.equal(source.split(before).length, 2, `Expected exactly one injection: ${before}`)
- return source.replace(before, after)
-}
-
-const adapter = join(output, 'adapter.mjs')
-const source = (path: string) => JSON.stringify(join(overlay, 'src', path))
-await writeFile(
- adapter,
- `
-export { installChildSessionSearchService, applySessionSearchSettingsChange } from ${source('main/ai-vault-search/session-search-enablement.ts')};
-export { resetAiVaultScannerServiceForTests, reconcileSessionSearchInService } from ${source('main/ai-vault/session-scanner-service-spawn.ts')};
-export { setAppEnvironment } from ${source('shared/app-environment.ts')};
-export { isolatedScanRoots } from ${source('main/ai-vault/session-scanner-test-fixtures.ts')};
-export { claudeLines } from ${source('main/ai-vault-search/session-search-indexer-test-fixture.ts')};
-export { runProcess } from '@orca/process-host';
-export { UnixSocketTransport } from ${source('main/runtime/rpc/unix-socket-transport.ts')};
-export { RpcDispatcher } from ${source('main/runtime/rpc/dispatcher.ts')};
-export { AI_VAULT_METHODS } from ${source('main/runtime/rpc/methods/ai-vault.ts')};
-import { buildRegistry } from ${source('main/runtime/rpc/core.ts')};
-import { AI_VAULT_METHODS } from ${source('main/runtime/rpc/methods/ai-vault.ts')};
-const registry = buildRegistry(AI_VAULT_METHODS);
-export async function rpc(name, params) {
- const method = registry.get(name);
- if (!method || !name.startsWith('aiVault.search')) throw new Error('Unexpected method');
- return method.handler(method.params.parse(params), {});
-}
-`
-)
-
-await build({
- entryPoints: {
- production: adapter,
- 'session-scanner-service-entry': join(
- overlay,
- 'src/main/ai-vault/session-scanner-service-entry.ts'
- )
- },
- outdir: output,
- platform: 'node',
- format: 'cjs',
- bundle: true,
- packages: 'external',
- define: { ORCA_FEATURE_WALL_ENABLED: 'true' },
- plugins: [
- {
- name: 'labelled-local-fixtures',
- setup(api) {
- api.onLoad({ filter: /\.ts$/ }, async (args) => {
- let contents = await readFile(args.path, 'utf8')
- const path = args.path.replaceAll('\\', '/')
- if (path.endsWith('/runtime/rpc/methods/rpc-method-registry.ts')) {
- // DispatcherOptions explicitly supplies AI_VAULT_METHODS; don't load unrelated default methods.
- contents = 'export const ALL_RPC_METHODS = []'
- }
- if (path.endsWith('/cached-session-list.ts')) {
- contents = replaceOnce(
- contents,
- ' const [additionalCodexHomes, wslHomeDirs] = await Promise.all([',
- ' return JSON.parse(process.env.ORCA_FILE_ID_ROOTS!);\n const [additionalCodexHomes, wslHomeDirs] = await Promise.all(['
- )
- }
- if (path.endsWith('/session-scanner-service-env.ts')) {
- contents = replaceOnce(
- contents,
- " env.ELECTRON_RUN_AS_NODE = '1'",
- " env.ORCA_BACKGROUND_LAUNCH = '1'\n env.ELECTRON_RUN_AS_NODE = '1'"
- )
- }
- if (path.endsWith('/session-scanner-service-spawn.ts')) {
- contents = replaceOnce(
- contents,
- ' lowerAiVaultServicePriority(child.pid)',
- ' globalThis.__fileIdObserveChild?.(child)\n lowerAiVaultServicePriority(child.pid)'
- )
- }
- if (path.endsWith('/session-scanner-service-entry.ts')) {
- contents = `import { registerTranscriptConsumer } from './session-transcript-consumers';
-registerTranscriptConsumer({beginRead: start => { console.error('[file-id-read]', JSON.stringify({mode:start.mode,path:start.candidate.file.path})); return null }});
-console.error('[file-id-child]', JSON.stringify({pid:process.pid,execPath:process.execPath,versions:process.versions,background:process.env.ORCA_BACKGROUND_LAUNCH}));\n${contents}`
- }
- if (mode === 'green' && path.endsWith('/session-search-store.ts')) {
- contents = replaceOnce(
- contents,
- 'SELECT path, dev, ino, mtime_ms',
- 'SELECT path, CAST(dev AS REAL) AS dev, CAST(ino AS REAL) AS ino, mtime_ms'
- )
- }
- if (mode === 'green' && path.endsWith('/session-search-index-writer.ts')) {
- contents = replaceOnce(
- contents,
- 'SELECT dev, ino, byte_offset',
- 'SELECT CAST(dev AS REAL) AS dev, CAST(ino AS REAL) AS ino, byte_offset'
- )
- }
- edits.push({
- path: path.replace(overlay.replaceAll('\\', '/'), ''),
- sha256: createHash('sha256').update(contents).digest('hex')
- })
- return { contents, loader: 'ts' }
- })
- }
- }
- ]
-})
-await copyFile(
- join(root, 'config/scripts/session-search-file-id-e2e/host.cjs'),
- join(output, 'host.cjs')
-)
-await copyFile(
- join(root, 'config/scripts/session-search-file-id-e2e/client.cjs'),
- join(output, 'client.cjs')
-)
-await writeFile(
- join(output, 'topology.json'),
- JSON.stringify(
- {
- wiring: await command('git', ['rev-parse', wiring]),
- fix: await command('git', ['rev-parse', 'HEAD']),
- mode,
- injections: [
- 'isolated root resolver',
- 'background child env',
- 'child PID/error/read observation',
- 'unused default RPC catalog excluded; explicit production AI_VAULT_METHODS'
- ],
- files: edits.sort((a, b) => a.path.localeCompare(b.path))
- },
- null,
- 2
- )
-)
-await writeFile(join(evidence, `${mode}-latest.json`), JSON.stringify({ output }))
-for (const phase of ['lifecycle', 'restart']) {
- console.log(JSON.stringify({ mode, phase, output }))
- const result = await runProcess({
- program: join(root, 'node_modules/electron/dist/electron.exe'),
- args: [join(output, 'host.cjs'), output, phase],
- cwd: output,
- env: {
- ...process.env,
- ORCA_BACKGROUND_LAUNCH: '1',
- ELECTRON_RUN_AS_NODE: undefined,
- ORCA_FILE_ID_NODE: process.execPath
- },
- timeoutMs: 180_000
- })
- await writeFile(join(output, `process-${phase}.log`), result.stdout + result.stderr)
- console.log(JSON.stringify({ mode, phase, code: result.code, timedOut: result.timedOut, output }))
- process.exitCode = result.code ?? 1
- if (process.exitCode !== 0) {
- break
- }
-}
diff --git a/config/scripts/session-search-file-id-e2e/verify.cjs b/config/scripts/session-search-file-id-e2e/verify.cjs
deleted file mode 100644
index 180bf4cf154..00000000000
--- a/config/scripts/session-search-file-id-e2e/verify.cjs
+++ /dev/null
@@ -1,62 +0,0 @@
-const assert = require('node:assert/strict')
-const { readFileSync, writeFileSync } = require('node:fs')
-const { join, resolve } = require('node:path')
-const { createHash } = require('node:crypto')
-const { transformSync } = require('esbuild')
-const evidence = resolve('notes/search-ipc')
-const json = (path) => JSON.parse(readFileSync(path, 'utf8'))
-const red = json(join(evidence, 'red-latest.json')).output
-const green = json(join(evidence, 'green-latest.json')).output
-const before = json(join(red, 'topology.json'))
-const after = json(join(green, 'topology.json'))
-assert.equal(before.wiring, after.wiring)
-assert.deepEqual(before.injections, after.injections)
-const oldFiles = new Map(before.files.map((row) => [row.path, row.sha256]))
-assert.equal(oldFiles.size, after.files.length)
-const changed = after.files
- .filter((row) => oldFiles.get(row.path) !== row.sha256)
- .map((row) => row.path)
- .sort()
-assert.deepEqual(changed, [
- '/src/main/ai-vault-search/session-search-index-writer.ts',
- '/src/main/ai-vault-search/session-search-store.ts'
-])
-for (const name of ['host.cjs', 'client.cjs']) {
- // Ignore formatter-only differences; preserve every expression and assertion.
- const hash = (root) =>
- createHash('sha256')
- .update(
- transformSync(readFileSync(join(root, name), 'utf8'), {
- loader: 'js',
- minifyWhitespace: true
- }).code
- )
- .digest('hex')
- assert.equal(hash(red), hash(green), `Identical oracle: ${name}`)
-}
-const failed = json(join(red, 'report-lifecycle.json'))
-assert.equal(failed.ok, false)
-assert.match(failed.stderr.join(''), /RangeError: Value is too large/)
-assert.ok(failed.stages.some((row) => row.stage === 'initial-indexing'))
-const reports = [
- json(join(green, 'report-lifecycle.json')),
- json(join(green, 'report-restart.json'))
-]
-for (const report of reports) {
- assert.equal(report.ok, true)
- assert.ok(report.ipc.some((row) => row.operation === 'searchSessions'))
- assert.ok(report.stages.some((row) => row.stage === 'query' && row.clientPid !== report.pid))
- assert.ok(report.children.every((child) => child.exitCode === 0))
-}
-assert.notEqual(reports[0].pid, reports[1].pid)
-const result = {
- ok: true,
- wiring: before.wiring,
- changed,
- red,
- green,
- parentPids: [failed.pid, ...reports.map((row) => row.pid)],
- childPids: [failed, ...reports].flatMap((report) => report.children.map((child) => child.pid))
-}
-writeFileSync(join(evidence, 'comparison.json'), JSON.stringify(result, null, 2))
-console.log(JSON.stringify(result))
diff --git a/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs b/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs
index 69c920f9add..714acf736a6 100644
--- a/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs
+++ b/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs
@@ -16,9 +16,15 @@ import {
} from '../../ratchet-baseline/ratchet-baseline.mjs'
import {
HAZARD_FIXES,
+ LIVE_MODULE_READERS,
+ VIRTUALIZER_HOOKS,
+ findLiveReadWrappers,
findMemoizedCalls,
findSourceHazards,
+ findVirtualizerMemoFlows,
+ findVirtualizerWrappers,
hookCallLines,
+ renderLiveReadLines,
renderStoreReadLines
} from './react-compiler-hazards.mjs'
@@ -28,6 +34,8 @@ import {
const SCAN_ROOT = 'src/renderer/src'
const BAILOUT_BASELINE = 'config/react-compiler-bailout-baseline.txt'
const HAZARD_BASELINE = 'config/react-compiler-hazard-baseline.txt'
+// The build leaves these files uncompiled, so their hazards cannot run.
+const UNCOMPILED_LIST = 'config/react-compiler-uncompiled-files.txt'
const COMMAND = 'pnpm check:react-compiler-compat-ratchet'
const NOT_SHIPPED =
/(?:^|\/)__(?:mocks|fixtures|tests)__\/|\.(?:test|spec|bench)\.[cm]?tsx?$|[.-]test-|[.-]fixtures?\.tsx?$/
@@ -93,6 +101,59 @@ function addTo(map, key, value) {
map.set(key, [...(map.get(key) ?? []), value])
}
+function readUncompiledFiles(root) {
+ const file = path.join(root, UNCOMPILED_LIST)
+ if (!fs.existsSync(file)) {
+ return new Set()
+ }
+ return new Set(
+ fs
+ .readFileSync(file, 'utf8')
+ .split('\n')
+ .map((line) => line.trim())
+ .filter((line) => line && !line.startsWith('#'))
+ )
+}
+
+/** Virtualizer hooks plus every hook that returns one, followed through wrappers of wrappers. */
+function collectVirtualizerHooks(sources) {
+ const hooks = new Map(VIRTUALIZER_HOOKS)
+ for (let grew = true; grew;) {
+ grew = false
+ for (const [rel, text] of sources) {
+ for (const { name, shape } of findVirtualizerWrappers(rel, text, hooks)) {
+ if (!hooks.has(name)) {
+ hooks.set(name, shape)
+ grew = true
+ }
+ }
+ }
+ }
+ return hooks
+}
+
+/** Live module-state readers plus every plain function that calls one, followed through wrappers. */
+function collectLiveReaders(sources) {
+ const readers = new Set(LIVE_MODULE_READERS)
+ for (let grew = true; grew;) {
+ grew = false
+ for (const [rel, text] of sources) {
+ for (const name of findLiveReadWrappers(rel, text, readers)) {
+ if (!readers.has(name)) {
+ readers.add(name)
+ grew = true
+ }
+ }
+ }
+ }
+ return readers
+}
+
+function sourceLineOf(text, snippet) {
+ const index = text.split('\n').findIndex((line) => line.includes(snippet.split('(')[0]))
+ return index === -1 ? '?' : index + 1
+}
+
async function scanFile(rel, text, result) {
const output = await transform(rel, text, COMPILER_OPTIONS)
if (output.fatal) {
@@ -105,15 +166,37 @@ async function scanFile(rel, text, result) {
const message = error.message.split('\n')[0]
addTo(result.diagnostics, rel, { line: lineAt(bytes, error.labels[0]?.start ?? 0), message })
}
+ if (result.uncompiled.has(rel)) {
+ return
+ }
+ for (const { fn, text: snippet } of findVirtualizerMemoFlows(
+ rel,
+ text,
+ output.code,
+ result.virtualizerHooks
+ )) {
+ addTo(
+ result.hazards,
+ `${rel}#${fn}:virtualizer-in-memo-block`,
+ `${sourceLineOf(text, snippet)}: ${snippet}`
+ )
+ }
for (const hazard of findSourceHazards(rel, text)) {
addTo(result.hazards, `${rel}#${hazard.fn}:${hazard.kind}`, `${hazard.line}: ${hazard.text}`)
}
const storeReadFns = new Set()
- for (const { fn, kind, name } of findMemoizedCalls(rel, output.code)) {
+ for (const { fn, kind, name } of findMemoizedCalls(rel, output.code, result.liveReaders)) {
if (kind === 'store-read') {
storeReadFns.add(fn)
continue
}
+ if (kind === 'live-read') {
+ // A call inside the source's own useMemo or a closure keeps its written behavior.
+ for (const line of renderLiveReadLines(rel, text, fn, name)) {
+ addTo(result.hazards, `${rel}#${fn}:live-read-in-memo-block`, `${line}: ${name}()`)
+ }
+ continue
+ }
const lines = hookCallLines(rel, text, fn, name)
addTo(result.hazards, `${rel}#${fn}:hook-in-memo-block`, `${lines.join(', ')}: ${name}()`)
}
@@ -126,8 +209,17 @@ async function scanFile(rel, text, result) {
}
export async function scanRenderer(root = process.cwd()) {
- const result = { files: 0, compiled: 0, diagnostics: new Map(), hazards: new Map() }
- const pending = [...readTrackedSources(root, [SCAN_ROOT], isScannedPath)]
+ const sources = [...readTrackedSources(root, [SCAN_ROOT], isScannedPath)]
+ const result = {
+ files: 0,
+ compiled: 0,
+ diagnostics: new Map(),
+ hazards: new Map(),
+ uncompiled: readUncompiledFiles(root),
+ virtualizerHooks: collectVirtualizerHooks(sources),
+ liveReaders: collectLiveReaders(sources)
+ }
+ const pending = [...sources]
result.files = pending.length
await Promise.all(
Array.from({ length: IN_FLIGHT }, async () => {
diff --git a/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs b/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs
index 0dee8c26189..fbe7590cf13 100644
--- a/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs
+++ b/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs
@@ -31,6 +31,16 @@ export const HAZARD_FIXES = {
'React Compiler caches this render-time `store.getState()` snapshot on unrelated inputs, so it',
'goes stale. Read it in the event handler or effect that uses it, or select it with a hook.'
],
+ 'virtualizer-in-memo-block': [
+ 'A TanStack virtualizer is one object mutated in place, so React Compiler serves rows, sizes or',
+ 'child elements cached on it after every scroll. Add the file to',
+ 'config/react-compiler-uncompiled-files.txt, owners that pass the virtualizer down included.'
+ ],
+ 'live-read-in-memo-block': [
+ 'React Compiler caches this render-time read of module state (a provider runtime context key or a',
+ 'structured selection) on its arguments, so it misses the module-level change. Add the file to',
+ 'config/react-compiler-uncompiled-files.txt, or subscribe to the state so a change re-renders.'
+ ],
'hook-in-memo-block': [
'React Compiler memoizes this hook call inside a cached block, so it runs only when the block',
'recomputes (a conditional hook). Call the hook in its own top-level `const` and use the variable.'
@@ -247,16 +257,19 @@ function isStoreRead(node) {
)
}
-function memoizedCallKind(node) {
+function memoizedCallKind(node, liveReaders) {
if (isStoreRead(node)) {
return { kind: 'store-read', name: 'getState' }
}
- const hook = calleeName(node.expression)
- return hook && HOOK_NAME.test(hook) ? { kind: 'hook', name: hook } : null
+ const callee = calleeName(node.expression)
+ if (callee && liveReaders.has(callee)) {
+ return { kind: 'live-read', name: callee }
+ }
+ return callee && HOOK_NAME.test(callee) ? { kind: 'hook', name: callee } : null
}
-/** Hook calls and `getState()` reads the compiler placed inside a memo-cache guarded block. */
-export function findMemoizedCalls(fileName, compiledCode) {
+/** Hook calls, `getState()` reads and live module-state reads the compiler placed inside a memo-cache guarded block. */
+export function findMemoizedCalls(fileName, compiledCode, liveReaders = new Set()) {
if (!compiledCode.includes('compiler-runtime')) {
return []
}
@@ -271,7 +284,7 @@ export function findMemoizedCalls(fileName, compiledCode) {
if (isFunctionNode(node)) {
return
}
- const call = ts.isCallExpression(node) ? memoizedCallKind(node) : null
+ const call = ts.isCallExpression(node) ? memoizedCallKind(node, liveReaders) : null
// Nested guarded blocks are walked once per enclosing block; keying by node dedupes them.
if (call) {
found.set(node, { fn, ...call })
@@ -315,6 +328,20 @@ export function findMemoizedStoreReads(fileName, compiledCode) {
/** Source lines of render-time `getState()` calls in `fnName`; a useMemo/callback read is excluded. */
export function renderStoreReadLines(fileName, text, fnName) {
+ return renderCallLines(fileName, text, fnName, isStoreRead)
+}
+
+/** Source lines of render-time calls to `callee` in `fnName`; a useMemo/callback call is excluded. */
+export function renderLiveReadLines(fileName, text, fnName, callee) {
+ return renderCallLines(
+ fileName,
+ text,
+ fnName,
+ (node) => ts.isCallExpression(node) && calleeName(node.expression) === callee
+ )
+}
+
+function renderCallLines(fileName, text, fnName, matches) {
const sourceFile = parseModule(fileName, text)
const lines = new Set()
for (const { name, node: root } of listReactFunctions(sourceFile)) {
@@ -325,7 +352,7 @@ export function renderStoreReadLines(fileName, text, fnName) {
if (node !== root && isFunctionNode(node)) {
return
}
- if (isStoreRead(node)) {
+ if (matches(node)) {
lines.add(lineOf(sourceFile, node))
}
ts.forEachChild(node, visit)
@@ -335,6 +362,69 @@ export function renderStoreReadLines(fileName, text, fnName) {
return [...lines].sort((a, b) => a - b)
}
+// Reads of module-level state that changes without a React update; a cache keyed on props keeps the old value.
+export const LIVE_MODULE_READERS = [
+ // Both fold in providerRuntimeSessionGeneration (lib/provider-runtime-context.ts).
+ 'getProviderRuntimeContextKey',
+ 'getEnvironmentRuntimeContextKey',
+ // Both read the selection lifetime registry in structured-agent-session-selection-controller.ts.
+ 'structuredSessionSelectionAuthority',
+ 'structuredSessionSelectionController'
+]
+
+function moduleFunctionName(node) {
+ if (ts.isFunctionDeclaration(node) && node.name) {
+ return node.name.text
+ }
+ const parent = node.parent
+ return (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) &&
+ ts.isVariableDeclaration(parent) &&
+ ts.isIdentifier(parent.name) &&
+ ts.isVariableStatement(parent.parent?.parent)
+ ? parent.name.text
+ : null
+}
+
+/** Module-scope plain functions whose own body calls a live reader, so their result is live too. */
+export function findLiveReadWrappers(fileName, text, readers) {
+ if (![...readers].some((reader) => text.includes(reader))) {
+ return []
+ }
+ const sourceFile = parseModule(fileName, text)
+ const wrappers = []
+ for (const statement of sourceFile.statements) {
+ const candidates = ts.isFunctionDeclaration(statement)
+ ? [statement]
+ : ts.isVariableStatement(statement)
+ ? statement.declarationList.declarations
+ .map((declaration) => declaration.initializer && unwrap(declaration.initializer))
+ .filter((init) => init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init)))
+ : []
+ for (const fn of candidates) {
+ const name = moduleFunctionName(fn)
+ if (!name || isReactName(name) || readers.has(name)) {
+ continue
+ }
+ let calls = false
+ const visit = (node) => {
+ if (calls || (node !== fn && isFunctionNode(node))) {
+ return
+ }
+ if (ts.isCallExpression(node) && readers.has(calleeName(node.expression) ?? '')) {
+ calls = true
+ return
+ }
+ ts.forEachChild(node, visit)
+ }
+ visit(fn)
+ if (calls) {
+ wrappers.push(name)
+ }
+ }
+ }
+ return wrappers
+}
+
/** Source lines of `hook` calls in `fnName` that sit inside a larger expression. */
export function hookCallLines(fileName, text, fnName, hook) {
const sourceFile = parseModule(fileName, text)
@@ -358,3 +448,204 @@ export function hookCallLines(fileName, text, fnName, hook) {
}
return lines.size > 0 ? [...lines].sort((a, b) => a - b) : ['?']
}
+
+// A TanStack virtualizer is one object mutated in place, so a cache keyed on it never refreshes.
+export const VIRTUALIZER_HOOKS = new Map([
+ ['useVirtualizer', 'direct'],
+ ['useWindowVirtualizer', 'direct']
+])
+const VIRTUALIZER_NAME = /^\w*[vV]irtualizer$/
+const VIRTUALIZER_TYPE = /\bVirtualizer\s*
+// Bound methods: passing one (e.g. as a row ref) reads no virtualizer state.
+const STABLE_VIRTUALIZER_METHODS = new Set(['measureElement', 'scrollToIndex', 'scrollToOffset'])
+
+function virtualizerHookShape(expression, hooks) {
+ const node = expression && unwrap(expression)
+ return node && ts.isCallExpression(node)
+ ? (hooks.get(calleeName(node.expression) ?? '') ?? null)
+ : null
+}
+
+/** Hooks returning a virtualizer (`direct`) or an object with a `virtualizer` (`property`). */
+export function findVirtualizerWrappers(fileName, text, hooks = VIRTUALIZER_HOOKS) {
+ if (![...hooks.keys()].some((hook) => text.includes(hook))) {
+ return []
+ }
+ const sourceFile = parseModule(fileName, text)
+ const wrappers = []
+ for (const { name, node } of listReactFunctions(sourceFile)) {
+ if (!HOOK_NAME.test(name) || hooks.has(name)) {
+ continue
+ }
+ const bound = new Set()
+ let shape = null
+ const visit = (child) => {
+ if (child !== node && isFunctionNode(child)) {
+ return
+ }
+ if (
+ ts.isVariableDeclaration(child) &&
+ ts.isIdentifier(child.name) &&
+ virtualizerHookShape(child.initializer, hooks) === 'direct'
+ ) {
+ bound.add(child.name.text)
+ }
+ if (ts.isReturnStatement(child) && child.expression) {
+ const value = unwrap(child.expression)
+ if (
+ (ts.isIdentifier(value) && bound.has(value.text)) ||
+ virtualizerHookShape(value, hooks) === 'direct'
+ ) {
+ shape = 'direct'
+ } else if (
+ ts.isObjectLiteralExpression(value) &&
+ value.properties.some(
+ (p) => p.name && ts.isIdentifier(p.name) && p.name.text === 'virtualizer'
+ )
+ ) {
+ shape ??= 'property'
+ }
+ }
+ ts.forEachChild(child, visit)
+ }
+ visit(node)
+ if (shape) {
+ wrappers.push({ name, shape })
+ }
+ }
+ return wrappers
+}
+
+/** Prop and parameter names this module types as a Virtualizer. */
+function virtualizerTypedNames(fileName, text) {
+ const names = new Set()
+ if (!VIRTUALIZER_TYPE.test(text)) {
+ return names
+ }
+ const sourceFile = parseModule(fileName, text)
+ const visit = (node) => {
+ if (
+ (ts.isPropertySignature(node) || ts.isParameter(node)) &&
+ node.type &&
+ ts.isIdentifier(node.name) &&
+ VIRTUALIZER_TYPE.test(node.type.getText(sourceFile))
+ ) {
+ names.add(node.name.text)
+ }
+ ts.forEachChild(node, visit)
+ }
+ visit(sourceFile)
+ return names
+}
+
+/** Cache blocks keyed on a virtualizer that read it or pass it as a JSX prop: `{ fn, text }`. */
+export function findVirtualizerMemoFlows(
+ fileName,
+ sourceText,
+ compiledCode,
+ hooks = VIRTUALIZER_HOOKS
+) {
+ if (
+ !compiledCode.includes('compiler-runtime') ||
+ !(
+ /[vV]irtualizer/.test(compiledCode) ||
+ [...hooks.keys()].some((hook) => compiledCode.includes(hook))
+ )
+ ) {
+ return []
+ }
+ const typed = virtualizerTypedNames(fileName, sourceText)
+ const sourceFile = parseModule(fileName, compiledCode)
+ const runtime = compilerCacheNames(sourceFile)
+ if (runtime.size === 0) {
+ return []
+ }
+ const caches = new Set()
+ const bound = new Set()
+ const isVirtualizer = (expression) => {
+ const node = unwrap(expression)
+ if (ts.isIdentifier(node)) {
+ const name = node.text.replace(/_\d+$/, '')
+ return bound.has(node.text) || VIRTUALIZER_NAME.test(name) || typed.has(name)
+ }
+ if (ts.isPropertyAccessExpression(node)) {
+ const name = node.name.text
+ return VIRTUALIZER_NAME.test(name) || typed.has(name)
+ }
+ return false
+ }
+ const keyedOnVirtualizer = (condition) => {
+ let keyed = false
+ const visit = (node) => {
+ if (
+ ts.isBinaryExpression(node) &&
+ node.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsEqualsToken &&
+ (isVirtualizer(node.left) || isVirtualizer(node.right))
+ ) {
+ keyed = true
+ }
+ if (!keyed) {
+ ts.forEachChild(node, visit)
+ }
+ }
+ visit(condition)
+ return keyed
+ }
+ const found = new Map()
+ // Closures call the live virtualizer when they run; only render-time reads and props go stale.
+ const collect = (fn, node) => {
+ if (isFunctionNode(node)) {
+ return
+ }
+ const passed =
+ ts.isJsxAttribute(node) &&
+ node.initializer &&
+ ts.isJsxExpression(node.initializer) &&
+ node.initializer.expression &&
+ isVirtualizer(node.initializer.expression)
+ const read =
+ ts.isPropertyAccessExpression(node) &&
+ isVirtualizer(node.expression) &&
+ !(STABLE_VIRTUALIZER_METHODS.has(node.name.text) && !ts.isCallExpression(node.parent))
+ if (passed || read) {
+ found.set(node, { fn, text: node.getText(sourceFile).split('\n')[0].slice(0, 100) })
+ return
+ }
+ ts.forEachChild(node, (child) => collect(fn, child))
+ }
+ const visit = (fn, node) => {
+ if (ts.isVariableDeclaration(node) && node.initializer) {
+ const init = unwrap(node.initializer)
+ const shape = virtualizerHookShape(init, hooks)
+ if (ts.isIdentifier(node.name)) {
+ if (
+ ts.isCallExpression(init) &&
+ ts.isIdentifier(init.expression) &&
+ runtime.has(init.expression.text)
+ ) {
+ caches.add(node.name.text)
+ } else if (shape === 'direct' || isVirtualizer(init)) {
+ bound.add(node.name.text)
+ }
+ } else if (ts.isObjectBindingPattern(node.name)) {
+ for (const element of node.name.elements) {
+ const key = (element.propertyName ?? element.name).getText(sourceFile)
+ if (ts.isIdentifier(element.name) && (key === 'virtualizer' || typed.has(key))) {
+ bound.add(element.name.text)
+ }
+ }
+ }
+ }
+ if (
+ ts.isIfStatement(node) &&
+ readsCache(node.expression, caches) &&
+ keyedOnVirtualizer(node.expression)
+ ) {
+ collect(fn, node.thenStatement)
+ }
+ const next = isFunctionNode(node) ? (reactFunctionName(node) ?? fn) : fn
+ ts.forEachChild(node, (child) => visit(next, child))
+ }
+ visit('(module)', sourceFile)
+ return [...found.values()]
+}
diff --git a/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.test.mjs b/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.test.mjs
index e7ec711261d..5a249927121 100644
--- a/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.test.mjs
+++ b/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.test.mjs
@@ -1,9 +1,14 @@
import { describe, expect, it } from 'vitest'
import {
+ findLiveReadWrappers,
+ findMemoizedCalls,
findMemoizedHookCalls,
findMemoizedStoreReads,
findSourceHazards,
+ findVirtualizerMemoFlows,
+ findVirtualizerWrappers,
+ renderLiveReadLines,
renderStoreReadLines
} from './react-compiler-hazards.mjs'
@@ -101,3 +106,90 @@ describe('store reads in memo blocks', () => {
expect(renderStoreReadLines('a.ts', src, 'useRoute')).toEqual([3])
})
})
+
+describe('virtualizer flows into memo blocks', () => {
+ it('follows wrapper hooks and flags cached reads and props, not closures or bound methods', () => {
+ const wrapper = [
+ 'export function useRows(n) {',
+ ' const virtualizer = useVirtualizer({ count: n })',
+ ' return { virtualizer, n }',
+ '}'
+ ].join('\n')
+ expect(findVirtualizerWrappers('w.ts', wrapper)).toEqual([
+ { name: 'useRows', shape: 'property' }
+ ])
+ const hooks = new Map([
+ ['useVirtualizer', 'direct'],
+ ['useList', 'direct']
+ ])
+ const compiled = [
+ 'import { c as _c } from "react/compiler-runtime";',
+ 'export function Pane() {',
+ ' const $ = _c(4);',
+ ' const list = useList();',
+ ' let t0;',
+ ' if ($[0] !== list) {',
+ ' t0 = list.scrollToIndex(0)} rowRef={list.measureElement} />;',
+ ' $[0] = list;',
+ ' $[1] = t0;',
+ ' } else {',
+ ' t0 = $[1];',
+ ' }',
+ ' let t1;',
+ ' if ($[2] !== list) {',
+ ' t1 = () => list.getVirtualItems();',
+ ' $[2] = list;',
+ ' $[3] = t1;',
+ ' } else {',
+ ' t1 = $[3];',
+ ' }',
+ ' return t0;',
+ '}'
+ ].join('\n')
+ expect(
+ findVirtualizerMemoFlows('a.jsx', '', compiled, hooks).map(({ fn, text }) => `${fn}:${text}`)
+ ).toEqual(['Pane:list={list}', 'Pane:list.getTotalSize'])
+ })
+})
+
+describe('live module-state reads in memo blocks', () => {
+ it('follows plain wrappers and flags a render read the compiler caches, not a useMemo one', () => {
+ const lib = [
+ 'export function scopeKey(s) {',
+ ' return s ? runtimeKey(s.env) : null',
+ '}',
+ 'export const later = (s) => () => runtimeKey(s)',
+ 'export function useScope(s) {',
+ ' return runtimeKey(s)',
+ '}'
+ ].join('\n')
+ expect(findLiveReadWrappers('lib.ts', lib, new Set(['runtimeKey']))).toEqual(['scopeKey'])
+ const compiled = [
+ 'import { c as _c } from "react/compiler-runtime";',
+ 'export function Card(t0) {',
+ ' const $ = _c(2);',
+ ' const { settings } = t0;',
+ ' let t1;',
+ ' if ($[0] !== settings) {',
+ ' t1 = scopeKey(settings);',
+ ' $[0] = settings;',
+ ' $[1] = t1;',
+ ' } else {',
+ ' t1 = $[1];',
+ ' }',
+ ' return t1;',
+ '}'
+ ].join('\n')
+ const readers = new Set(['runtimeKey', 'scopeKey'])
+ expect(findMemoizedCalls('a.js', compiled, readers)).toEqual([
+ { fn: 'Card', kind: 'live-read', name: 'scopeKey' }
+ ])
+ const src = [
+ 'export function Card({ settings }) {',
+ ' const kept = useMemo(() => scopeKey(settings), [settings])',
+ ' return [kept, scopeKey(settings)]',
+ '}'
+ ].join('\n')
+ expect(renderLiveReadLines('a.tsx', src, 'Card', 'scopeKey')).toEqual([3])
+ })
+})
diff --git a/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs b/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs
deleted file mode 100644
index 7e0a827a2ff..00000000000
--- a/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs
+++ /dev/null
@@ -1,66 +0,0 @@
-import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { afterAll, describe, expect, it } from 'vitest'
-import { copyScriptWithLocalModules } from './script-module-dependencies.mjs'
-
-const fixtureDir = mkdtempSync(join(tmpdir(), 'script-module-dependencies-'))
-
-afterAll(() => {
- rmSync(fixtureDir, { recursive: true, force: true })
-})
-
-function sourceTree(files) {
- const sourceDir = mkdtempSync(join(fixtureDir, 'source-'))
- for (const [name, contents] of Object.entries(files)) {
- writeFileSync(join(sourceDir, name), contents)
- }
- return sourceDir
-}
-
-function copiedNames(files, entryName) {
- const sourceDir = sourceTree(files)
- const destinationDir = join(mkdtempSync(join(fixtureDir, 'dest-')), 'scripts')
- copyScriptWithLocalModules(join(sourceDir, entryName), destinationDir)
- const names = readdirSync(destinationDir).sort()
- for (const name of names) {
- expect(readFileSync(join(destinationDir, name), 'utf8'), name).toBe(files[name])
- }
- return names
-}
-
-describe('copyScriptWithLocalModules', () => {
- it('preserves parent paths for modules shared with the runtime', () => {
- const sourceDir = sourceTree({ 'runtime.ts': 'export const value = 42\n' })
- mkdirSync(join(sourceDir, 'scripts'))
- writeFileSync(join(sourceDir, 'scripts', 'entry.mjs'), "export { value } from '../runtime'\n")
- const destinationRoot = mkdtempSync(join(fixtureDir, 'dest-'))
- copyScriptWithLocalModules(
- join(sourceDir, 'scripts', 'entry.mjs'),
- join(destinationRoot, 'scripts')
- )
- expect(readFileSync(join(destinationRoot, 'runtime.ts'), 'utf8')).toBe(
- 'export const value = 42\n'
- )
- })
-
- // Cover require-only CJS gate dependencies so copied fixture fails for target defect, not missing module.
-
- it('follows a require reached only through an imported module', () => {
- const names = copiedNames(
- {
- 'entry.mjs': "import './middle.cjs'\n",
- 'middle.cjs': "require('./leaf.cjs')\n",
- 'leaf.cjs': 'module.exports = {}\n'
- },
- 'entry.mjs'
- )
- expect(names).toContain('leaf.cjs')
- })
-
- it('terminates on a cycle rather than recursing forever', () => {
- expect(
- copiedNames({ 'a.mjs': "import './b.mjs'\n", 'b.mjs': "import './a.mjs'\n" }, 'a.mjs')
- ).toEqual(['a.mjs', 'b.mjs'])
- })
-})
diff --git a/config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs b/config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs
new file mode 100644
index 00000000000..dff75d916d4
--- /dev/null
+++ b/config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs
@@ -0,0 +1,201 @@
+// Shared-worker files run back to back in one module cache; undo each file's mocks and process state.
+// A file that leaves timers, listeners or globals behind also drops the module cache, as isolation would.
+// Plain JS: it rewires Vitest's mocker and the timer globals, which have no public types.
+import { promisify } from 'node:util'
+import { afterAll, vi } from 'vitest'
+
+const VITEST_INTERNAL = /\/vitest\/dist\/|\/@vitest\/|vitest-virtual-/
+// Registries their owners create on first use and look up again on every access.
+const LAZY_GLOBAL_REGISTRY = /^(?:Symbol\(orca\.|__zod_global)/
+const PROCESS_KEYS = ['platform', 'arch', 'execPath', 'argv', 'exitCode']
+
+function resetNode(node) {
+ node.evaluated = false
+ node.promise = undefined
+ node.exports = undefined
+}
+
+// Same reset Vitest's isolation applies, limited to modules that saw the mocked one.
+function resetImportersOf(modules, id) {
+ const pending = [...(modules.getModuleById(id)?.importers ?? [])]
+ const seen = new Set()
+ while (pending.length > 0) {
+ const importer = pending.pop()
+ if (seen.has(importer) || VITEST_INTERNAL.test(importer)) {
+ continue
+ }
+ seen.add(importer)
+ const node = modules.getModuleById(importer)
+ if (node) {
+ resetNode(node)
+ pending.push(...node.importers)
+ }
+ }
+}
+
+function resetAllModules(modules) {
+ for (const [id, node] of modules.idToModuleMap) {
+ if (!VITEST_INTERNAL.test(id)) {
+ resetNode(node)
+ node.importers.clear()
+ }
+ }
+}
+
+function trackTimers(state) {
+ const real = { setTimeout, setInterval, clearTimeout, clearInterval }
+ function trackedSetTimeout(callback, ms, ...args) {
+ if (typeof callback !== 'function') {
+ return real.setTimeout(callback, ms, ...args)
+ }
+ const handle = real.setTimeout(
+ (...callbackArgs) => {
+ state.pendingTimers.delete(handle)
+ callback(...callbackArgs)
+ },
+ ms,
+ ...args
+ )
+ state.pendingTimers.add(handle)
+ return handle
+ }
+ trackedSetTimeout[promisify.custom] = real.setTimeout[promisify.custom]
+ globalThis.setTimeout = trackedSetTimeout
+ globalThis.setInterval = (...args) => {
+ const handle = real.setInterval(...args)
+ state.pendingTimers.add(handle)
+ return handle
+ }
+ globalThis.clearTimeout = (handle) => {
+ state.pendingTimers.delete(handle)
+ real.clearTimeout(handle)
+ }
+ globalThis.clearInterval = (handle) => {
+ state.pendingTimers.delete(handle)
+ real.clearInterval(handle)
+ }
+ state.clearTimer = (handle) => {
+ real.clearTimeout(handle)
+ real.clearInterval(handle)
+ }
+}
+
+// The mocker lives across files, unlike this module, so it carries the once-per-worker state.
+function installOnce(mocker) {
+ if (mocker.orcaSharedWorkerState) {
+ return mocker.orcaSharedWorkerState
+ }
+ const mockPath = mocker.mockPath.bind(mocker)
+ // Modules cached by an earlier file hold the real binding; re-run them against this file's mock.
+ mocker.mockPath = (originalId, id, ...rest) => {
+ mockPath(originalId, id, ...rest)
+ resetImportersOf(mocker.evaluatedModules, id)
+ }
+ const reset = mocker.reset.bind(mocker)
+ // And re-run them against the real module before the next file imports them.
+ mocker.reset = () => {
+ for (const registry of mocker.registries.values()) {
+ for (const url of registry.keys()) {
+ resetImportersOf(mocker.evaluatedModules, registry.get(url).id)
+ }
+ }
+ reset()
+ }
+ const state = { pendingTimers: new Set(), clearTimer: () => {} }
+ trackTimers(state)
+ mocker.orcaSharedWorkerState = state
+ return state
+}
+
+const mocker = globalThis.__vitest_mocker__
+const state = mocker ? installOnce(mocker) : undefined
+state?.pendingTimers.clear()
+
+const initialGlobals = Object.getOwnPropertyDescriptors(globalThis)
+const initialProcess = Object.fromEntries(
+ PROCESS_KEYS.map((key) => [key, Object.getOwnPropertyDescriptor(process, key)])
+)
+const initialListeners = new Map(
+ process.eventNames().map((event) => [event, new Set(process.listeners(event))])
+)
+const initialEnv = { ...process.env }
+const initialCwd = process.cwd()
+const evaluatedBefore = new Set(
+ [...(mocker?.evaluatedModules.idToModuleMap ?? [])]
+ .filter(([, node]) => node.evaluated)
+ .map(([id]) => id)
+)
+
+/** Puts process state back and reports what this file had left behind. */
+function restoreProcessState() {
+ const leaks = { globals: [], process: [] }
+ for (const key of Reflect.ownKeys(globalThis)) {
+ if (!(key in initialGlobals) && !LAZY_GLOBAL_REGISTRY.test(String(key))) {
+ leaks.globals.push(String(key))
+ Reflect.deleteProperty(globalThis, key)
+ }
+ }
+ for (const [key, descriptor] of Object.entries(initialGlobals)) {
+ const current = Object.getOwnPropertyDescriptor(globalThis, key)
+ if (!Object.is(current?.value, descriptor.value) || current?.get !== descriptor.get) {
+ leaks.globals.push(key)
+ try {
+ Object.defineProperty(globalThis, key, descriptor)
+ } catch {
+ // Non-configurable globals cannot be put back; the module reset below still applies.
+ }
+ }
+ }
+ for (const key of PROCESS_KEYS) {
+ const descriptor = initialProcess[key]
+ if (descriptor) {
+ Object.defineProperty(process, key, descriptor)
+ } else {
+ Reflect.deleteProperty(process, key)
+ }
+ }
+ for (const event of process.eventNames()) {
+ const before = initialListeners.get(event)
+ for (const listener of process.listeners(event)) {
+ if (!before?.has(listener)) {
+ leaks.process.push(`${String(event)} listener`)
+ process.removeListener(event, listener)
+ }
+ }
+ }
+ for (const handle of state?.pendingTimers ?? []) {
+ leaks.process.push('timer')
+ state.clearTimer(handle)
+ }
+ state?.pendingTimers.clear()
+ for (const key of Object.keys(process.env)) {
+ if (!(key in initialEnv)) {
+ delete process.env[key]
+ }
+ }
+ Object.assign(process.env, initialEnv)
+ if (process.cwd() !== initialCwd) {
+ process.chdir(initialCwd)
+ }
+ return leaks
+}
+
+afterAll(() => {
+ // Runs Vitest's end-of-file spy restore now: a spy restored by hand would otherwise be re-applied after this hook.
+ vi.restoreAllMocks()
+ vi.useRealTimers()
+ vi.unstubAllEnvs()
+ vi.unstubAllGlobals()
+ const leaks = restoreProcessState()
+ if (mocker && leaks.process.length > 0) {
+ // Any cached module may own a cleared timer or listener.
+ resetAllModules(mocker.evaluatedModules)
+ } else if (mocker && leaks.globals.length > 0) {
+ // A module this file loaded may have installed the global it now expects.
+ for (const [id, node] of mocker.evaluatedModules.idToModuleMap) {
+ if (node.evaluated && !evaluatedBefore.has(id) && !VITEST_INTERNAL.test(id)) {
+ resetNode(node)
+ }
+ }
+ }
+})
diff --git a/config/scripts/test-runtime/execution-policy/vitest-shared-worker-files.mjs b/config/scripts/test-runtime/execution-policy/vitest-shared-worker-files.mjs
new file mode 100644
index 00000000000..e436fafecca
--- /dev/null
+++ b/config/scripts/test-runtime/execution-policy/vitest-shared-worker-files.mjs
@@ -0,0 +1,94 @@
+import { readFileSync, statSync } from 'node:fs'
+import { dirname, join, relative, resolve } from 'node:path'
+
+// vitest-shared-worker-file-reset.mjs undoes mocks, timers, stubs, env and cwd after each file.
+// These can't be undone between files, so a file that uses them keeps its own worker.
+const ISOLATION_REQUIRING_API = new RegExp(
+ [
+ // Opt-out for a file whose state leaks in ways the reset cannot see.
+ String.raw`@orca-isolated-worker\b`,
+ String.raw`\bvi\.(?:doMock|unmock|doUnmock|resetModules)\(`,
+ String.raw`@vitest-environment\s+(?!node\b)`,
+ String.raw`\bglobalThis(?:\.\w+|\[[^\]]+\])\s*=[^=]`,
+ String.raw`\bObject\.defineProperty\(\s*(?:globalThis|process|navigator|window|document)\b`
+ ].join('|')
+)
+const IMPORT_SPECIFIER = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)['"]([^'"]+)['"]/g
+const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.mts', '.mjs', '.js']
+
+function isFile(path) {
+ try {
+ return statSync(path).isFile()
+ } catch {
+ return false
+ }
+}
+
+function resolveLocal(fromFile, specifier, aliases) {
+ let base = null
+ if (specifier.startsWith('./') || specifier.startsWith('../')) {
+ base = resolve(dirname(fromFile), specifier)
+ } else {
+ const alias = aliases.find(({ find }) => specifier === find || specifier.startsWith(`${find}/`))
+ if (!alias) {
+ return null
+ }
+ base = join(alias.replacement, specifier.slice(alias.find.length))
+ }
+ const stem = base.replace(/\.[cm]?jsx?$/, '')
+ const candidates = [
+ base,
+ ...SOURCE_EXTENSIONS.map((extension) => stem + extension),
+ ...SOURCE_EXTENSIONS.map((extension) => join(base, `index${extension}`))
+ ]
+ return (
+ candidates.find(
+ (candidate) => !/[\\/]node_modules[\\/]/.test(candidate) && isFile(candidate)
+ ) ?? null
+ )
+}
+
+/**
+ * Returns the test files (root-relative, forward slashes) that can share a worker's module cache.
+ * Only the test file and the test-support files it imports are scanned, not production modules.
+ */
+export function filesSafeToShareWorker(root, files, aliases = []) {
+ const sources = new Map()
+ const read = (file) => {
+ let source = sources.get(file)
+ if (source === undefined) {
+ source = readFileSync(file, 'utf8')
+ sources.set(file, source)
+ }
+ return source
+ }
+ const isTestSupport = (file) => /\bfrom\s+['"]vitest['"]/.test(read(file))
+ const memo = new Map()
+ const visiting = new Set()
+ const requiresIsolation = (file) => {
+ const known = memo.get(file)
+ if (known !== undefined) {
+ return known
+ }
+ if (visiting.has(file)) {
+ return false
+ }
+ visiting.add(file)
+ const source = read(file)
+ let result = ISOLATION_REQUIRING_API.test(source)
+ for (const match of result ? [] : source.matchAll(IMPORT_SPECIFIER)) {
+ const target = resolveLocal(file, match[1], aliases)
+ if (target && isTestSupport(target) && requiresIsolation(target)) {
+ result = true
+ break
+ }
+ }
+ visiting.delete(file)
+ memo.set(file, result)
+ return result
+ }
+ return files
+ .map((file) => resolve(root, file))
+ .filter((file) => isFile(file) && !requiresIsolation(file))
+ .map((file) => relative(root, file).replaceAll('\\', '/'))
+}
diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs
index 3fc7dd70837..11fa95a615f 100644
--- a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs
+++ b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs
@@ -58,7 +58,6 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/acp/session/acp-structured-sign-in.test.ts',
'src/main/acp/session/acp-structured-session-adapter.test.ts',
'src/main/acp/session/acp-structured-session-adapter-resume.test.ts',
- 'src/main/acp/history/acp-history-scaling.test.ts',
'src/main/pi/rpc-turn-races.test.ts',
'src/main/acp/session/children/acp-structured-child-session-end.test.ts',
'src/main/acp/session/children/acp-structured-child-stop.test.ts',
diff --git a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs
index 3166e02549d..22cec99aa84 100644
--- a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs
+++ b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs
@@ -157,7 +157,6 @@ export const WINDOWS_BOUNDARY_TESTS = [
'config/scripts/native-build/windows/windows-pe-machine.test.mjs',
'config/scripts/native-build/windows/build-windows-cli-launcher.test.mjs',
'config/scripts/desktop-distribution/runtime-verification/verify-packaged-windows-agent-hook.test.mjs',
- 'config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs',
'src/main/windows/windows-registry-addon.test.ts',
'src/main/daemon/executable-host/windows/testing/daemon-host-process-package.test.ts',
'src/shared/windows-security-addon.win32.test.ts',
diff --git a/config/scripts/workflow/source-routing/pr-unit-support-routing.test.mjs b/config/scripts/workflow/source-routing/pr-unit-support-routing.test.mjs
deleted file mode 100644
index 7e3a023c4f4..00000000000
--- a/config/scripts/workflow/source-routing/pr-unit-support-routing.test.mjs
+++ /dev/null
@@ -1,98 +0,0 @@
-import { beforeAll, describe, expect, it } from 'vitest'
-import {
- buildUnitDependencyGraph,
- collectUnitDependencyGraph,
- unitConsumers
-} from '../../ci/unit-selection/dependency-graph/ci-unit-dependency-graph.mjs'
-import {
- CROSS_VERSION_WIRE_DIR,
- discoverUnitFiles
-} from '../../ci/unit-selection/dependency-graph/ci-unit-files.mjs'
-
-const harness =
- 'src/renderer/src/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture.ts'
-const structuredSessionHarness =
- 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx'
-
-const unitHarnesses = [
- harness,
- structuredSessionHarness,
- 'src/renderer/src/store/slices/editor/editor-slice-test-harness.ts',
- 'src/renderer/src/store/slices/browser/browser-slice-test-harness.ts',
- 'src/renderer/src/runtime/hosted-terminals/creation/testing/web-runtime-terminal-create.test-fixture.ts',
- 'src/renderer/src/runtime/sync-runtime-graph/testing/sync-runtime-graph-test-harness.ts'
-]
-const supportBridges = new Set([
- // Launch request suites' store rig; it takes the terminal harness's workspace layout.
- 'src/renderer/src/runtime/hosted-terminals/creation/agent-launch/web-runtime-agent-launch-options.test-fixture.ts',
- 'src/renderer/src/runtime/browser/creation/testing/web-runtime-browser-creation-placement-test-rig.ts',
- 'src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts',
- // Autosave suites' store rig; it takes the editor harness's tab-layout maps.
- 'src/renderer/src/components/editor/autosave/editor-autosave-controller-test-fixture.ts',
- // Closed-saving-view save suites' rig; it builds on the autosave rig above.
- 'src/renderer/src/components/editor/save/queue/editor-save-closed-view.test-fixture.ts',
- // Browser suites' store with main drawing their tabs; it takes the browser harness's store.
- 'src/renderer/src/store/slices/browser/browser-slice-drawn-from-main.test-fixture.ts'
-])
-
-function productConsumers(file, graph, unitFiles) {
- return [...unitConsumers([file], graph.reverse)].filter(
- (consumer) =>
- consumer !== file &&
- !unitFiles.has(consumer) &&
- !(consumer.startsWith(CROSS_VERSION_WIRE_DIR) && consumer.endsWith('.unit.test.ts')) &&
- !supportBridges.has(consumer)
- )
-}
-
-describe('unit support import ownership', () => {
- let graph
- let unitFiles
- beforeAll(() => {
- graph = collectUnitDependencyGraph()
- unitFiles = new Set(discoverUnitFiles())
- }, 60_000)
-
- it.each(unitHarnesses)('rejects any product consumer of %s', (unitHarness) => {
- expect(graph.files.has(unitHarness)).toBe(true)
- expect(
- [...unitConsumers([unitHarness], graph.reverse)].some((file) => unitFiles.has(file))
- ).toBe(true)
- expect(productConsumers(unitHarness, graph, unitFiles)).toEqual([])
- })
-
- it.each([
- "import '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'",
- "export * from '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'",
- "import('@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture')",
- "import type { Fixture } from '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'"
- ])('detects a product importer using %s', (source) => {
- const importer = 'src/renderer/src/runtime/product.ts'
- const test = 'src/renderer/src/runtime/ownership.test.ts'
- const synthetic = buildUnitDependencyGraph(
- new Map([
- [harness, 'export const value = 1'],
- [importer, source],
- [test, "import './web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'"]
- ])
- )
- expect(productConsumers(harness, synthetic, new Set([test]))).toEqual([importer])
- })
-
- it('rejects product consumers reached through an audited support bridge', () => {
- const bridge =
- 'src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts'
- const importer = 'src/renderer/src/components/editor/product.ts'
- const synthetic = buildUnitDependencyGraph(
- new Map([
- [harness, 'export const value = 1'],
- [
- bridge,
- "import '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'"
- ],
- [importer, "import './model-lifetime/retention/editor-model-lifetime-fixture'"]
- ])
- )
- expect(productConsumers(harness, synthetic, new Set())).toEqual([importer])
- })
-})
diff --git a/config/vitest.config.ts b/config/vitest.config.ts
index 6202566aa32..7dc0f04c525 100644
--- a/config/vitest.config.ts
+++ b/config/vitest.config.ts
@@ -1,4 +1,4 @@
-import { readFileSync } from 'node:fs'
+import { globSync, readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { resolve } from 'node:path'
import { normalizePath, transformWithOxc, type Plugin } from 'vite'
@@ -9,12 +9,14 @@ import {
UNIT_SETUP_FILES
} from './scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs'
import TimingSequencer from './scripts/ci/sharding/ci-unit-sequencer.mjs'
+import { filesSafeToShareWorker } from './scripts/test-runtime/execution-policy/vitest-shared-worker-files.mjs'
import RuntimeSequencer from './scripts/test-runtime/execution-policy/vitest-runtime-sequencer.mjs'
import { getNodeRuntimeInclude } from './scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs'
import { nodeRuntimePool } from './scripts/test-runtime/node-worker/vitest-node-runtime-pool'
import { readRunFilters } from './scripts/test-runtime/execution-policy/vitest-run-filters.mjs'
import { createWorkspaceSourceResolver } from './scripts/workspace/source-exports/workspace-source-exports.mjs'
import { moduleCacheResolutionKey } from './scripts/test-runtime/module-cache/vitest-module-cache-resolution-key'
+import { vitestReactCompiler } from './build-plugins/vitest-react-compiler'
const nodeRuntimeInclude = process.versions.bun
? getNodeRuntimeInclude({ filters: readRunFilters() })
@@ -44,6 +46,7 @@ const transforms = {
}
} satisfies Plugin,
...(moduleCachePath ? [moduleCacheResolutionKey()] : []),
+ ...vitestReactCompiler(),
{
// Unit tests have no asset server; retain real catalog parsing through fetch(data:).
name: 'locale-catalog-test-assets',
@@ -121,7 +124,46 @@ const bunProject = {
sequence: { groupOrder: 1 }
}
}
-const projects = [...(process.versions.bun ? [bunProject] : []), nodeProject]
+// Files whose state the per-file reset can undo share one worker's module cache instead of
+// re-importing thousands of modules each. ORCA_VITEST_ISOLATE_EVERY_FILE=1 turns it off.
+const runtimeProject = process.versions.bun ? bunProject : nodeProject
+const nodeRuntimeFiles = new Set(nodeRuntimeInclude.map((file) => file.replaceAll('\\', '/')))
+const sharedWorkerFiles =
+ process.env.ORCA_VITEST_ISOLATE_EVERY_FILE === '1'
+ ? []
+ : filesSafeToShareWorker(
+ process.cwd(),
+ globSync(UNIT_INCLUDE)
+ .map((file) => file.replaceAll('\\', '/'))
+ .filter((file) => !nodeRuntimeFiles.has(file)),
+ [
+ { find: '@renderer', replacement: resolve('src/renderer/src') },
+ { find: '@', replacement: resolve('src/renderer/src') }
+ ]
+ )
+const sharedProjects =
+ sharedWorkerFiles.length > 0
+ ? [
+ {
+ ...runtimeProject,
+ test: {
+ ...runtimeProject.test,
+ name: `${runtimeProject.test.name}-shared`,
+ include: sharedWorkerFiles,
+ isolate: false,
+ setupFiles: [
+ ...runtimeProject.test.setupFiles,
+ resolve('config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs')
+ ]
+ }
+ }
+ ]
+ : []
+runtimeProject.test.exclude = [
+ ...(runtimeProject.test.exclude ?? testOptions.exclude),
+ ...sharedWorkerFiles
+]
+const projects = [...(process.versions.bun ? [bunProject] : []), nodeProject, ...sharedProjects]
export default defineConfig({
...transforms,
diff --git a/electron.vite.config.ts b/electron.vite.config.ts
index 673eb8847e7..0a2e110aca1 100644
--- a/electron.vite.config.ts
+++ b/electron.vite.config.ts
@@ -15,6 +15,7 @@ import { createViteCacheRetentionPlugin } from './config/build-plugins/vite-cach
import { MAIN_BUILD_ENTRY_POINTS } from './config/build-plugins/main-build-entry-points'
import { createPlainNodeEntryGuardPlugin } from './config/build-plugins/plain-node-entry-guard'
import { createDevServeConfig } from './config/build-plugins/dev-serve-config'
+import { reactPluginOptions } from './config/build-plugins/react-compiler'
import { resolveBuildSourceCommit } from './config/scripts/build-identity/build-source-commit.mjs'
const BUNDLED_MAIN_DEPENDENCIES = new Set([
@@ -284,7 +285,7 @@ export const electronViteConfig: UserConfig = {
}
},
plugins: [
- react(),
+ react(reactPluginOptions()),
tailwindcss(),
createPdfjsViewerAssetsPlugin(),
createViteCacheRetentionPlugin()
diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt
index d3df9fffb59..045cce54908 100644
--- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt
+++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt
@@ -3,6 +3,9 @@ package expo.modules.orcamobilewebshell
/** Shared page/native bridge contract; framework-free for off-device checks. */
internal const val MOBILE_WEB_SHELL_BRIDGE_OBJECT = "orcaBridge"
+/** Tells a page booted ahead of its screen to stop asking for init; the screen that adopts it answers. */
+internal const val MOBILE_WEB_SHELL_PARKED_FRAME = """{"v":1,"type":"parked"}"""
+
/** Enforce the shared UTF-8 JSON byte ceiling natively, before parsing. */
internal const val MOBILE_WEB_SHELL_BRIDGE_MAX_MESSAGE_BYTES = 640 * 1024
diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellDocument.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellDocument.kt
new file mode 100644
index 00000000000..af1aff6a343
--- /dev/null
+++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellDocument.kt
@@ -0,0 +1,413 @@
+package expo.modules.orcamobilewebshell
+
+import android.annotation.SuppressLint
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Color
+import android.net.Uri
+import android.os.Message
+import android.view.View
+import android.view.ViewGroup
+import android.webkit.RenderProcessGoneDetail
+import android.webkit.WebChromeClient
+import android.webkit.WebResourceError
+import android.webkit.WebResourceRequest
+import android.webkit.WebResourceResponse
+import android.webkit.WebSettings
+import android.webkit.WebView
+import android.webkit.WebViewClient
+import androidx.core.graphics.Insets
+import androidx.core.view.ViewCompat
+import androidx.core.view.WindowInsetsCompat
+import androidx.webkit.JavaScriptReplyProxy
+import androidx.webkit.ScriptHandler
+import androidx.webkit.WebMessageCompat
+import androidx.webkit.WebViewCompat
+import androidx.webkit.WebViewFeature
+import expo.modules.kotlin.exception.CodedException
+import java.io.ByteArrayInputStream
+
+/** Publish host and manifest map atomically/volatily: main-thread writes race Chromium’s interceptor. */
+private class MobileWebShellServed(
+ val generation: MobileWebShellGeneration,
+ val originHost: String
+)
+
+/** Where a document's reports go: the view showing it, or the spare pool while it is parked. */
+internal interface MobileWebShellDocumentSink {
+ fun documentLoadState(payload: Map)
+ fun documentBridgeMessage(json: String)
+ fun documentExternalNavigation(url: String)
+}
+
+/** One WebView and every fence on it, apart from React. The view hosts it and lays it out. */
+@SuppressLint("SetJavaScriptEnabled")
+internal class MobileWebShellDocument(private val context: Context) {
+ var sink: MobileWebShellDocumentSink? = null
+ private var bridgeInstalled = false
+ private val bridgeGate = MobileWebShellBridgeGate()
+ // The page sends ready before native replies; volatile proxy state crosses interceptor/UI threads.
+ @Volatile private var replyProxy: JavaScriptReplyProxy? = null
+ private var applied: MobileWebShellAppliedProps? = null
+ private val loadState = MobileWebShellLoadStateMachine()
+ // Failure state crosses main-thread callbacks and Chromium’s background interceptor.
+ @Volatile private var documentFailed = false
+ @Volatile private var served: MobileWebShellServed? = null
+ private var blocker: ScriptHandler? = null
+ // Read by the interceptor thread when it reports a failed main-frame load.
+ @Volatile var webView: WebView? = createWebView()
+ private set
+
+ /** Still showable: not torn down, and no terminal load failure or renderer loss. */
+ val isUsable: Boolean get() = webView != null && !loadState.isTerminal
+
+ /** Apply unordered props together; identical triples do not retry. Recovery requires a remount. */
+ fun apply(generationDirectory: String, sessionId: String, bridgeEnabled: Boolean) {
+ val next = MobileWebShellAppliedProps(generationDirectory, sessionId, bridgeEnabled)
+ if (applied?.matches(next) == true) return
+ applied = next
+ documentFailed = false
+ loadState.reset()
+ val view = webView
+ if (view == null) {
+ // A dead renderer requires a remount; changed props must still report failure.
+ emit(loadState.rendererStillGone())
+ return
+ }
+ view.stopLoading()
+ emit(loadState.started())
+
+ val origin = mobileWebShellOrigin(sessionId)
+ val host = mobileWebShellOriginHost(sessionId)
+ if (origin == null || host == null) {
+ // The private origin is the isolation primitive; a malformed session id leaves us without one.
+ failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE)
+ return
+ }
+ val loaded = MobileWebShellGeneration.load(generationDirectory)
+ if (loaded == null) {
+ failPropUpdate(MobileWebShellFailureReason.GENERATION_UNREADABLE)
+ return
+ }
+ blocker?.remove()
+ blocker = installMobileWebShellNetworkApiBlocker(view, origin)
+ if (blocker == null) {
+ failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE)
+ return
+ }
+ if (!applyBridgeListener(view, origin, bridgeEnabled)) {
+ failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE)
+ return
+ }
+ served = MobileWebShellServed(loaded, host)
+ view.visibility = View.VISIBLE
+ view.loadUrl("$origin/")
+ }
+
+ /** Retire the old visible generation even when the replacement fails. */
+ private fun failPropUpdate(reason: MobileWebShellFailureReason) {
+ // Remove the old listener: stopLoading leaves its same-origin document alive and able to rearm replies.
+ removeBridgeListener()
+ served = null
+ webView?.visibility = View.INVISIBLE
+ emit(loadState.failed(reason))
+ }
+
+ /** addWebMessageListener injects before scripts and enforces origins; false means unsupported provider. */
+ private fun applyBridgeListener(view: WebView, origin: String, bridgeEnabled: Boolean): Boolean {
+ removeBridgeListener()
+ val outcome = mobileWebShellBridgeInstall(
+ bridgeEnabled,
+ WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)
+ )
+ if (outcome != MobileWebShellBridgeInstall.INSTALL) {
+ return outcome == MobileWebShellBridgeInstall.SKIP
+ }
+ return runCatching {
+ WebViewCompat.addWebMessageListener(
+ view,
+ MOBILE_WEB_SHELL_BRIDGE_OBJECT,
+ setOf(origin),
+ bridgeListener
+ )
+ bridgeInstalled = true
+ }.isSuccess
+ }
+
+ /** The one way the bridge goes away, so no disable path can leave a listener behind. */
+ private fun removeBridgeListener() {
+ val view = webView
+ if (bridgeInstalled && view != null) {
+ WebViewCompat.removeWebMessageListener(view, MOBILE_WEB_SHELL_BRIDGE_OBJECT)
+ }
+ bridgeInstalled = false
+ replyProxy = null
+ }
+
+ /** Chromium calls this on the UI thread, which is also the only thread that may reply. */
+ private val bridgeListener = WebViewCompat.WebMessageListener {
+ _, message, _, isMainFrame, proxy ->
+ val isStringMessage = message.type == WebMessageCompat.TYPE_STRING
+ val json = if (isStringMessage) message.data else null
+ if (
+ acceptsMobileWebShellBridgeFrame(
+ isMainFrame,
+ isStringMessage,
+ loadState.hasCommittedDocument
+ ) && json != null &&
+ bridgeGate.accepts(json.toByteArray(Charsets.UTF_8).size)
+ ) {
+ replyProxy = proxy
+ sink?.documentBridgeMessage(json)
+ }
+ }
+
+ /** Throw so a host chunking bug rejects rather than leaving its request unsettled. */
+ fun postBridgeMessage(json: String) {
+ val proxy = replyProxy ?: throw MobileWebShellBridgeUnavailableException()
+ val byteCount = json.toByteArray(Charsets.UTF_8).size
+ if (!acceptsMobileWebShellBridgeByteCount(byteCount)) {
+ throw MobileWebShellBridgeMessageTooLargeException(byteCount)
+ }
+ proxy.postMessage(json)
+ }
+
+ /** A frame from the shell itself, to the frame that spoke. */
+ fun postHostFrame(json: String) {
+ replyProxy?.postMessage(json)
+ }
+
+ /** The view's attach and detach: off-window, the page reads hidden, as a buried WKWebView does on iOS. */
+ fun resume() {
+ webView?.onResume()
+ }
+
+ fun pause() {
+ webView?.onPause()
+ }
+
+ /** The view is done with it, or onRenderProcessGone. */
+ fun destroyWebView() {
+ val view = webView ?: return
+ removeBridgeListener()
+ loadState.documentEnded()
+ webView = null
+ blocker?.remove()
+ blocker = null
+ served = null
+ documentFailed = false
+ view.stopLoading()
+ (view.parent as? ViewGroup)?.removeView(view)
+ view.destroy()
+ }
+
+ // Keep explicit settings for the Chromium 83 floor, even where newer WebViews ignore deprecated options.
+ // B4 requires device proofs: no network, persistent state, file/content access, cleartext or navigation escape.
+ @Suppress("DEPRECATION")
+ private fun createWebView(): WebView {
+ val view = MobileWebShellSelectionView(context)
+ view.setBackgroundColor(Color.TRANSPARENT)
+ view.settings.apply {
+ javaScriptEnabled = true
+ domStorageEnabled = false
+ databaseEnabled = false
+ allowFileAccess = false
+ allowFileAccessFromFileURLs = false
+ allowUniversalAccessFromFileURLs = false
+ allowContentAccess = false
+ javaScriptCanOpenWindowsAutomatically = false
+ setSupportMultipleWindows(false)
+ mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
+ cacheMode = WebSettings.LOAD_NO_CACHE
+ blockNetworkLoads = true
+ mediaPlaybackRequiresUserGesture = true
+ setGeolocationEnabled(false)
+ }
+ // clearCache(true) is process-global, including terminals; use per-view LOAD_NO_CACHE and no-store.
+ view.webViewClient = ShellWebViewClient()
+ view.webChromeClient = object : WebChromeClient() {
+ override fun onCreateWindow(
+ view: WebView?,
+ isDialog: Boolean,
+ isUserGesture: Boolean,
+ resultMsg: Message?
+ ): Boolean = false
+ }
+ view.setDownloadListener { _, _, _, _, _ -> }
+ // Replace WebView inset handling on P–R/S+; forward zeroed insets for S+ parity.
+ ViewCompat.setOnApplyWindowInsetsListener(view) { target, insets ->
+ ViewCompat.onApplyWindowInsets(target, insetsForShellPage(insets))
+ }
+ return view
+ }
+
+ private fun emit(emission: MobileWebShellLoadEmission?) {
+ if (emission != null) sink?.documentLoadState(emission.toPayload())
+ }
+
+ /** Post hiding past Chromium’s error-document commit; interception may also run off the main thread. */
+ private fun reportDocumentFailure() {
+ replyProxy = null
+ // Drop replies synchronously before Chromium’s error document commits and the posted hide runs.
+ loadState.documentEnded()
+ // Set before posting: intervening onPageFinished must not restore ready or expose the error page.
+ documentFailed = true
+ val epoch = loadState.epoch
+ // The WebView's queue, like the view it sits in: a detached document reports once it attaches.
+ webView?.post {
+ if (!documentFailed) return@post
+ val emission = loadState.failedDuring(
+ epoch,
+ MobileWebShellFailureReason.DOCUMENT_LOAD_FAILED
+ ) ?: return@post
+ webView?.visibility = View.INVISIBLE
+ emit(emission)
+ }
+ }
+
+ private fun isDocumentUrl(url: Uri): Boolean {
+ val host = served?.originHost ?: return false
+ return resolveMobileWebShellRequestPath(requestParts(url), host) == "/"
+ }
+
+ private fun requestParts(
+ url: Uri,
+ method: String = "GET",
+ hasRangeHeader: Boolean = false
+ ): MobileWebShellRequestParts = MobileWebShellRequestParts(
+ method = method,
+ hasRangeHeader = hasRangeHeader,
+ scheme = url.scheme,
+ host = url.host,
+ port = url.port,
+ userInfo = url.userInfo,
+ query = url.query,
+ fragment = url.fragment,
+ encodedPath = url.encodedPath,
+ urlLength = url.toString().length
+ )
+
+ private fun serveRequest(request: WebResourceRequest): WebResourceResponse? {
+ val current = served ?: return null
+ val parts = requestParts(
+ request.url,
+ method = request.method,
+ hasRangeHeader = request.requestHeaders.keys.any { it.equals("Range", ignoreCase = true) }
+ )
+ val path = resolveMobileWebShellRequestPath(parts, current.originHost) ?: return null
+ val asset = current.generation.entries[path] ?: return null
+ val bytes = runCatching { asset.file.readBytes() }.getOrNull() ?: return null
+ val headers = mobileWebShellResponseHeaders(path, bytes.size)
+ val (mimeType, charset) = splitMobileWebShellContentType(asset.contentType)
+ return WebResourceResponse(mimeType, charset, 200, "OK", headers, ByteArrayInputStream(bytes))
+ }
+
+ private fun refusedResponse(): WebResourceResponse = WebResourceResponse(
+ MOBILE_WEB_SHELL_REFUSAL_MIME_TYPE,
+ MOBILE_WEB_SHELL_REFUSAL_CHARSET,
+ MOBILE_WEB_SHELL_REFUSAL_STATUS,
+ MOBILE_WEB_SHELL_REFUSAL_REASON,
+ MOBILE_WEB_SHELL_REFUSAL_HEADERS,
+ ByteArrayInputStream(mobileWebShellRefusalBody())
+ )
+
+ private inner class ShellWebViewClient : WebViewClient() {
+ /** Never null, so no request can fall through to the network. */
+ override fun shouldInterceptRequest(
+ view: WebView,
+ request: WebResourceRequest
+ ): WebResourceResponse {
+ val response = serveRequest(request)
+ if (response != null) return response
+ if (request.isForMainFrame) reportDocumentFailure()
+ return refusedResponse()
+ }
+
+ override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
+ // hasGesture gates only opener offers: human requests may omit it and subframes can target top without it.
+ val verdict = mobileWebShellNavigationVerdict(
+ url = request.url?.toString(),
+ isForMainFrame = request.isForMainFrame,
+ // Not reported here, unlike WKNavigationAction.sourceFrame on iOS.
+ isFromSubframe = false,
+ isDocumentUrl = !mobileWebShellDropsNavigation(
+ requestParts(request.url),
+ served?.originHost,
+ request.isForMainFrame
+ ),
+ // loadUrl bypasses this callback by WebViewClient contract; no callback action is our own load.
+ isShellLoad = false,
+ hasGesture = request.hasGesture(),
+ isDownload = false
+ )
+ if (verdict is MobileWebShellNavigationVerdict.CancelAndOffer) {
+ sink?.documentExternalNavigation(verdict.url)
+ }
+ return verdict !is MobileWebShellNavigationVerdict.Allow
+ }
+
+ override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
+ // Discard the replaced document’s reply proxy; the next page must send ready.
+ replyProxy = null
+ loadState.documentEnded()
+ if (documentFailed || !isDocumentUrl(Uri.parse(url))) return
+ // Arm at commit before page script runs.
+ loadState.committed()
+ emit(loadState.started())
+ }
+
+ // history.replaceState changes the document path before finish; commit state identifies the load.
+ override fun onPageFinished(view: WebView, url: String) {
+ if (documentFailed || !loadState.hasCommittedDocument) return
+ view.visibility = View.VISIBLE
+ // Remove history so the page cannot return to a replaced document.
+ view.clearHistory()
+ emit(loadState.finished())
+ }
+
+ override fun onReceivedError(
+ view: WebView,
+ request: WebResourceRequest,
+ error: WebResourceError
+ ) {
+ if (request.isForMainFrame) reportDocumentFailure()
+ }
+
+ override fun onReceivedHttpError(
+ view: WebView,
+ request: WebResourceRequest,
+ errorResponse: WebResourceResponse
+ ) {
+ if (request.isForMainFrame) reportDocumentFailure()
+ }
+
+ /** Return true to avoid killing the app; destroy the dead WebView and leave retry policy to the caller. */
+ override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
+ // Android ends every WebView's renderer together; off-screen or low-memory losses are the OS's doing, not the page's.
+ val host = view.parent as? View ?: view
+ val background = !host.isShown || host.windowVisibility != View.VISIBLE
+ destroyWebView()
+ emit(loadState.rendererGone(background, detail.didCrash()))
+ return true
+ }
+ }
+}
+
+internal class MobileWebShellBridgeUnavailableException :
+ CodedException("The mobile web shell bridge is not installed on this view")
+
+internal class MobileWebShellBridgeMessageTooLargeException(byteCount: Int) : CodedException(
+ "A bridge message of $byteCount bytes exceeds the " +
+ "$MOBILE_WEB_SHELL_BRIDGE_MAX_MESSAGE_BYTES byte cap"
+)
+
+/** The shell already pads bars/keyboard; zero (never consume) insets to prevent WebView M144+ bar and M139+ IME double-padding. */
+private fun insetsForShellPage(insets: WindowInsetsCompat): WindowInsetsCompat =
+ WindowInsetsCompat.Builder(insets)
+ .setInsets(SHELL_OWNED_INSET_TYPES, Insets.NONE)
+ .build()
+
+private val SHELL_OWNED_INSET_TYPES =
+ WindowInsetsCompat.Type.systemBars() or
+ WindowInsetsCompat.Type.displayCutout() or
+ WindowInsetsCompat.Type.ime()
diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt
index 493e50b9b5b..93737f6dd66 100644
--- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt
+++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt
@@ -26,6 +26,7 @@ internal data class MobileWebShellLoadEmission(
/** Failure is terminal and duplicate reports are dropped: late error-document/rule-list callbacks must never restore ready. Cross-thread readers require volatile state. */
internal class MobileWebShellLoadStateMachine {
private var terminal = false
+ val isTerminal: Boolean get() = terminal
private var last: MobileWebShellLoadEmission? = null
private var rendererLoss: Pair? = null
diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellSparePool.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellSparePool.kt
new file mode 100644
index 00000000000..791dbba21cf
--- /dev/null
+++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellSparePool.kt
@@ -0,0 +1,169 @@
+package expo.modules.orcamobilewebshell
+
+import android.app.Activity
+import android.app.ActivityManager
+import android.content.Context
+import android.os.Handler
+import android.os.Looper
+import android.view.MotionEvent
+import android.view.View
+import android.view.ViewGroup
+import android.widget.FrameLayout
+import java.util.Collections
+import java.util.WeakHashMap
+
+/** More than 3 GiB can only come from a phone with 4 GB or more; those report about 3.5 to 3.9 GiB. */
+private const val MINIMUM_TOTAL_MEMORY_BYTES = 3L shl 30
+
+/** A claim is adopted on the claiming screen's first commit; this only bounds a screen that never mounts. */
+private const val CLAIM_EXPIRY_MS = 10_000L
+
+/** Holds a parked WebView under the app's content: invisible, untouchable and out of accessibility. */
+private class MobileWebShellParking(context: Context) : FrameLayout(context) {
+ init {
+ alpha = 0f
+ isFocusable = false
+ descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS
+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
+ }
+
+ override fun dispatchTouchEvent(event: MotionEvent): Boolean = false
+}
+
+/**
+ * A booted document waiting for a screen. It keeps what the page reported, and the page's ready, for
+ * the view that adopts it: a parked page stops asking for init, so its ready is answered from here.
+ */
+internal class MobileWebShellSpare(
+ activity: Activity,
+ val directory: String,
+ val sessionId: String
+) : MobileWebShellDocumentSink {
+ val document = MobileWebShellDocument(activity)
+ val parking: ViewGroup = MobileWebShellParking(activity)
+ private val loadStates = mutableListOf