Merge origin/main into brennanb2025/usage-limit-continue-1108

This commit is contained in:
Brennan Benson
2026-11-08 23:22:49 -08:00
1702 changed files with 28733 additions and 42385 deletions
+7 -1
View File
@@ -109,7 +109,7 @@ feedback, Vitest can select tests affected by your edits:
```bash
pnpm test:changed src/main/runtime --maxWorkers=2
pnpm test --changed=origin/main --maxWorkers=2
pnpm test src/shared/automations/scheduling/automation-cron-dialect.test.ts --maxWorkers=2
pnpm test src/shared/automations/scheduling/automation-cron-input-validation.test.ts --maxWorkers=2
```
`test:changed` considers staged, unstaged, and untracked files. `--changed=origin/main`
@@ -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:
@@ -31,7 +31,6 @@ on:
- 'src/main/usage/jsonl-file-reader.test.ts'
- 'src/main/usage/jsonl-file-snapshot.test.ts'
- 'src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-queue-retention.test.ts'
- 'src/renderer/src/store/diagnostics/store-identity-churn-probe.test.ts'
- 'src/main/claude-usage/scanner-incremental-append.test.ts'
- 'src/main/claude-usage/store-checkpoint-persistence.test.ts'
- 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx'
-7
View File
@@ -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 }}"
@@ -865,7 +859,6 @@ jobs:
src/main/startup/shell-probe-terminal-detach.live-shell.test.ts \
src/main/startup/shell-probe-lifetime.live-shell.test.ts \
src/renderer/src/components/terminal-pane/pty-connection/emulation/fish-color-scheme-child-stdin.node-pty.test.ts \
src/shared/fish-query-reply-child-stdin.node-pty.test.ts \
src/shared/fish-wsl-cwd-report.node-pty.test.ts \
src/main/wsl/filesystem/wsl-sh-cwd-report.node-pty.test.ts \
src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts \
@@ -90,7 +90,7 @@ jobs:
no-cache: true
- name: Verify read-only credentials and account changes
if: ${{ !cancelled() && steps.scope.outputs.account == 'true' && steps.dependencies.outcome == 'success' && steps.bun.outcome == 'success' }}
run: pnpm test src/main/zcode/zcode-v2-plan-credentials.test.ts src/main/zcode/zcode-v2-personal-overlay-raw-json.test.ts src/main/rate-limits/service-zcode-usage.test.ts src/shared/file-content/node-bounded-file-reader-sync.test.ts
run: pnpm test src/main/zcode/zcode-v2-plan-credentials.test.ts src/main/zcode/zcode-v2-personal-overlay-raw-json.test.ts src/main/rate-limits/service/service-zcode-usage.test.ts src/shared/file-content/node-bounded-file-reader-sync.test.ts
- name: Verify rollback and secure storage
if: ${{ !cancelled() && steps.scope.outputs.credentials == 'true' && steps.dependencies.outcome == 'success' && steps.bun.outcome == 'success' }}
run: pnpm test src/main/zcode/zcode-plan-api-key-store.test.ts src/main/zcode/zcode-plan-api-key-store-plaintext-rollback.test.ts src/shared/secure-storage/secure-file.test.ts
+1
View File
@@ -11,6 +11,7 @@
".github/actions/cloud-sql-rollout-lease/**",
".anti-slop-plugin/**",
"src/main/runtime/__fixtures__/*.timing.json",
"src/shared/workspace-setup/__fixtures__/setup-script-imports/**",
"resources/skills/released-digests.json",
"resources/plugins/declarative/*.mjs",
"resources/plugins/declarative/orca.d.ts",
@@ -1,170 +0,0 @@
import { afterEach, expect, it, vi } from 'vitest'
import { DurablePushStore } from './durable-push-store.js'
import type { PushDatabase } from './push-database.js'
import {
cleanupDurablePushFixtures,
fixture,
notification
} from './durable-push-store.test-fixture.js'
afterEach(async () => {
vi.restoreAllMocks()
await cleanupDurablePushFixtures()
})
function captureDatabaseErrors(database: PushDatabase, errors: unknown[]): PushDatabase {
return {
dialect: database.dialect,
query: async (sql, params) => {
try {
return await database.query(sql, params)
} catch (error) {
errors.push(error)
throw error
}
},
transaction: (run) => database.transaction((tx) => run(captureDatabaseErrors(tx, errors))),
lockQuotaScope: (key) => database.lockQuotaScope(key),
tryLockScope: (key) => database.tryLockScope(key),
tryLockSharedScope: (key) => database.tryLockSharedScope(key),
close: () => database.close()
}
}
it('parses each leased row once and preserves its complete serialized payload', async () => {
const { db, store } = await fixture()
const input = {
...notification(1),
body: 'Unicode: 🐋\ud800',
extra: { first: [null, false, 3], next: { z: 'last', a: 'first' } }
}
await store.accept('host', 'phone', input)
const [row] = await db.query('SELECT * FROM push_delivery_batches')
if (!row) {
throw new Error('Missing delivery row')
}
const payload = String(row.payload_json)
const parse = vi.spyOn(JSON, 'parse')
const delivery = await store.claim()
expect(delivery).toEqual({
id: row.batch_id,
registrationId: 'phone',
hostFingerprint: 'host',
notification: input,
expiresAt: 1_300_000,
lease: expect.any(String),
attempts: 1
})
expect(JSON.stringify(delivery?.notification)).toBe(payload)
expect(parse.mock.calls.filter(([value]) => value === payload)).toHaveLength(1)
})
it('reads changed retry bytes and a later writer update without carrying a parsed result across calls', async () => {
const { db, store, advance } = await fixture()
await store.accept('host', 'phone', notification(1))
const first = await store.claim()
if (!first) {
throw new Error('Missing first delivery')
}
first.notification.body = 'provider changed this retry'
await store.finish(first, 1000)
advance(1000)
const retriedPayload = JSON.stringify(first.notification)
const parse = vi.spyOn(JSON, 'parse')
const retry = await store.claim()
expect(retry).toEqual({ ...first, lease: expect.any(String), attempts: 2 })
expect(retry?.lease).not.toBe(first.lease)
expect(retry?.notification).not.toBe(first.notification)
expect(JSON.stringify(retry?.notification)).toBe(retriedPayload)
const retryParses = parse.mock.calls.filter(([value]) => value === retriedPayload).length
if (!retry) {
throw new Error('Missing retry delivery')
}
await store.finish(retry, 1000)
const changed = { ...notification(1), body: 'fresh database row', title: 'Changed' }
const changedPayload = JSON.stringify(changed)
await db.query('UPDATE push_delivery_batches SET payload_json = ? WHERE batch_id = ?', [
changedPayload,
first.id
])
advance(1000)
const fresh = await store.claim()
expect(fresh).toEqual({ ...retry, notification: changed, lease: expect.any(String), attempts: 3 })
expect(JSON.stringify(fresh?.notification)).toBe(changedPayload)
expect(retry.notification.body).toBe('provider changed this retry')
expect(retryParses).toBe(1)
expect(parse.mock.calls.filter(([value]) => value === changedPayload)).toHaveLength(1)
})
it.each(['not JSON', 'undefined', 'null', '[]'])(
'preserves invalid payload rejection and rolls back the lease for %s',
async (payload) => {
const { db, store } = await fixture()
await store.accept('host', 'phone', notification(1))
await db.query('UPDATE push_delivery_batches SET payload_json = ?', [payload])
const [before] = await db.query('SELECT * FROM push_delivery_batches')
const parse = vi.spyOn(JSON, 'parse')
let caught: unknown
try {
await store.claim()
} catch (error) {
caught = error
}
expect(caught).toBeInstanceOf(Error)
const index = parse.mock.calls.findIndex(([value]) => value === payload)
expect(index).toBeGreaterThanOrEqual(0)
if (payload === 'not JSON' || payload === 'undefined') {
expect(caught).toBe(parse.mock.results[index]?.value)
expect(caught).toBeInstanceOf(SyntaxError)
} else {
expect(caught).toMatchObject({ message: 'invalid_push_delivery_payload' })
}
expect(await db.query('SELECT * FROM push_delivery_batches')).toEqual([before])
expect(parse.mock.calls.filter(([value]) => value === payload)).toHaveLength(1)
}
)
it('preserves the exact database UPDATE error and retries with a fresh payload after rollback', async () => {
const { db, store, clock } = await fixture()
await store.accept('host', 'phone', notification(1))
const [before] = await db.query('SELECT * FROM push_delivery_batches')
if (!before) {
throw new Error('Missing delivery row')
}
const originalQuery = db.query.bind(db)
const errors: unknown[] = []
// SQLite raises a native error in the real transaction; PostgreSQL uses its real constraint.
await originalQuery(
db.dialect === 'sqlite'
? "CREATE TRIGGER deny_lease BEFORE UPDATE ON push_delivery_batches BEGIN SELECT RAISE(FAIL, 'deny_lease'); END"
: 'ALTER TABLE push_delivery_batches ADD CONSTRAINT deny_lease CHECK (lease_until = 0)'
)
const owner = new DurablePushStore(captureDatabaseErrors(db, errors), clock)
const parse = vi.spyOn(JSON, 'parse')
let caught: unknown
try {
await owner.claim()
} catch (error) {
caught = error
}
expect(errors).toHaveLength(1)
expect(caught).toBe(errors[0])
expect(await originalQuery('SELECT * FROM push_delivery_batches')).toEqual([before])
expect(parse.mock.calls.filter(([value]) => value === String(before.payload_json))).toHaveLength(
1
)
await originalQuery(
db.dialect === 'sqlite'
? 'DROP TRIGGER deny_lease'
: 'ALTER TABLE push_delivery_batches DROP CONSTRAINT deny_lease'
)
const fresh = await owner.claim()
expect(fresh?.notification).toEqual(notification(1))
expect(fresh?.attempts).toBe(1)
})
@@ -163,23 +163,6 @@ it('does not resurrect an in-flight alert after a dismissal and transient provid
expect(await store.pendingCount('phone')).toBe(0)
})
it.each([false, true])(
'normalizes default alert kind (explicit first: %s)',
async (explicitFirst) => {
const { db, store } = await fixture()
const { kind: _kind, ...implicit } = notification(1)
const explicit = { kind: 'alert' as const, ...implicit }
for (const event of explicitFirst ? [explicit, implicit] : [implicit, explicit]) {
expect(await store.accept('host', 'phone', event)).toBe('queued')
}
expect(await store.pendingCount('phone')).toBe(1)
expect(await db.query('SELECT event_id FROM push_events')).toHaveLength(1)
expect(await store.accept('host', 'phone', { ...explicit, body: 'changed' })).toBe('error')
expect(await store.accept('host', 'phone', { ...implicit, kind: 'dismiss' })).toBe('queued')
expect(await db.query('SELECT event_id FROM push_events')).toHaveLength(2)
}
)
it('fences late renew and finish after an expired claim is dismissed', async () => {
const { db, store, advance } = await fixture()
const alert = notification(1)
+1 -113
View File
@@ -8,7 +8,7 @@ import { PushDeviceRegistryStore } from './device-registry-store.js'
import { openInMemoryPushDatabase } from './push-database.js'
import type { PushDelivery } from './push-delivery-message.js'
import type { PushProviderOutcome } from './push-provider-outcome.js'
import { WORKER_DRAINS } from './push-worker-concurrency.js'
import { pauseAfter, within } from './durable-push-store.test-fixture.js'
const cleanups: (() => Promise<void>)[] = []
@@ -69,59 +69,6 @@ async function fixture() {
}
}
it('sends every burst event immediately with its original content and identity', async () => {
const h = await fixture()
await h.accept(note(1))
await h.accept(
note(2, { agentState: 'needs-input', title: 'Answer needed', body: 'Please respond' })
)
await h.worker.runDue()
expect(h.send).toHaveBeenCalledTimes(2)
const first = h.send.mock.calls.find(([delivery]) => delivery.orca.notificationSeq === 1)![0]
const second = h.send.mock.calls.find(([delivery]) => delivery.orca.notificationSeq === 2)![0]
expect(first).toMatchObject({
title: 'Done',
body: 'Finished task',
orca: {
notificationId: 'note-1',
notificationSeq: 1
}
})
expect(second).toMatchObject({
title: 'Answer needed',
body: 'Please respond',
orca: { notificationId: 'note-2', notificationSeq: 2 }
})
expect(first.collapseId).not.toBe(second.collapseId)
expect(h.send.mock.calls.every(([delivery]) => !('coalescedCount' in delivery.orca))).toBe(true)
expect(h.send.mock.calls.every(([delivery]) => !('summaryMembers' in delivery.orca))).toBe(true)
expect(h.onRetry).not.toHaveBeenCalled()
})
it('keeps untrackable bells and per-phone deliveries individually replaceable', async () => {
const h = await fixture()
const other = await h.devices.upsert({
hostFingerprint: 'host',
deviceId: 'phone2',
platform: 'android',
token: 'other-token'
})
if (!other.ok) throw new Error('registration failed')
await h.accept(note(1, { notificationId: undefined, source: 'terminal-bell', agentState: null }))
await h.accept(note(2))
await h.accept(note(3))
await h.store.accept('host', other.registrationId, note(2))
await h.worker.runDue()
expect(h.send).toHaveBeenCalledTimes(4)
const deliveries = h.send.mock.calls.map(([delivery]) => delivery)
const primary = deliveries.filter((delivery) => delivery.registrationId === h.registrationId)
expect(primary).toHaveLength(3)
expect(new Set(primary.map((delivery) => delivery.collapseId)).size).toBe(3)
expect(
deliveries.find((delivery) => delivery.registrationId === other.registrationId)
).toMatchObject({ orca: { notificationId: 'note-2', notificationSeq: 2 } })
})
it('preserves provider retry delay when waking a restarted worker', async () => {
const h = await fixture()
vi.useFakeTimers()
@@ -302,62 +249,3 @@ it('claims new devices while an earlier provider response is still pending', asy
await h.worker.stop()
}
})
it('coalesces wakes arriving after every active drain found an empty queue', async () => {
const h = await fixture()
vi.useFakeTimers()
const entered = Promise.withResolvers<void>()
const release = Promise.withResolvers<void>()
const claim = h.store.claim.bind(h.store)
let empty = 0
let holding = true
vi.spyOn(h.store, 'claim').mockImplementation(async () => {
const delivery = await claim()
if (!delivery && holding) {
if (++empty === WORKER_DRAINS) entered.resolve()
await release.promise
}
return delivery
})
h.worker.start()
const startedAt = Date.now()
const pending = h.worker.runDue()
try {
await entered.promise
await h.accept(note(1))
for (let count = 0; count < 10; count++) h.worker.wake()
expect(h.store.claim).toHaveBeenCalledTimes(WORKER_DRAINS)
holding = false
release.resolve()
await pending
await vi.waitFor(() => expect(h.send).toHaveBeenCalledOnce())
await vi.waitFor(() => expect(h.store.claim).toHaveBeenCalledTimes(WORKER_DRAINS + 2))
expect(Date.now() - startedAt).toBeLessThan(1000)
expect(h.send.mock.calls[0]?.[0].orca.notificationSeq).toBe(1)
} finally {
holding = false
release.resolve()
}
})
it('recovers from a failed automatic wake without leaving another timer', async () => {
const h = await fixture()
vi.useFakeTimers()
vi.spyOn(h.store, 'claim').mockRejectedValueOnce(new Error('database unavailable'))
h.worker.start()
h.worker.wake()
await vi.waitFor(() =>
expect(console.warn).toHaveBeenCalledWith(JSON.stringify({ event: 'orca_push_worker_failed' }))
)
await h.accept(note(1))
h.worker.wake()
await vi.waitFor(() => expect(h.send).toHaveBeenCalledOnce())
await h.worker.stop()
expect(vi.getTimerCount()).toBe(0)
})
@@ -75,14 +75,5 @@ describe('push host challenge store', () => {
})
})
it('rejects an unknown challenge id and a malformed public key', async () => {
await expect(store.verify('missing', Buffer.alloc(32, 9).toString('base64'))).resolves.toEqual({
ok: false,
reason: 'unknown_challenge'
})
await expect(store.issue('not-base64!!')).resolves.toBeNull()
await expect(store.issue(Buffer.alloc(31, 1).toString('base64'))).resolves.toBeNull()
})
})
-1
View File
@@ -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.
@@ -10,6 +10,7 @@ export const CLI_MAIN_ENTRY_NAMES = [
'skills/bundled-skill-install/bundled-skill-installation',
'filesystem/macos-tree-clone',
'orcad/orcad-stale-lock-reclaim',
'orcad/orcad-host-identity-reset',
'plugins/plugin-authoring-checks',
...[
'access',
@@ -20,6 +20,7 @@ export const MAIN_BUILD_ENTRY_POINTS: Record<string, string> = {
),
'stt-worker': resolve('src/main/speech/stt-worker.ts'),
'warp-theme-parser-worker': resolve('src/main/warp-themes/warp-theme-parser-worker.ts'),
'session-search-worker-entry': resolve('src/main/ai-vault-search/session-search-worker-entry.ts'),
'foreign-sqlite-reader-entry': resolve(
'src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry.ts'
),
+1 -14
View File
@@ -1,3 +1,4 @@
import { WORKER_THREAD_ENTRY_NAMES } from './worker-thread-entry-names'
import { spawn } from 'node:child_process'
import { isBuiltin } from 'node:module'
import { join } from 'node:path'
@@ -28,20 +29,6 @@ const PLAIN_NODE_ENTRY_NAMES = [
...CLI_MAIN_ENTRY_NAMES
] as const
// Electron is unavailable in main-process worker threads too (verified Electron 43); scan their graphs rather than trusting entry comments.
const WORKER_THREAD_ENTRY_NAMES = [
'warp-theme-parser-worker',
'foreign-sqlite-reader-entry',
'main-thread-hang-watchdog-entry',
'port-scan-command-worker-entry',
'command-path-directory-worker-entry',
'worker-thread-child-process-entry',
...(['usage-scan', 'workspace-space-scan'] as const).map((n) => `${n}-worker-entry` as const),
'claude-profile-setup-worker-entry',
...(['backup', 'writer'] as const).map((kind) => `profile-state-${kind}-worker-entry` as const),
'plugin-source-transpile-worker-entry'
] as const
export const GUARDED_ENTRY_NAMES = [
...PLAIN_NODE_ENTRY_NAMES,
...WORKER_THREAD_ENTRY_NAMES
+47
View File
@@ -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()]
}
}
@@ -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
}
}
@@ -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
}
}
}
]
}
@@ -0,0 +1,14 @@
// Electron is unavailable in main-process worker threads too (verified Electron 43); scan their graphs rather than trusting entry comments.
export const WORKER_THREAD_ENTRY_NAMES = [
'warp-theme-parser-worker',
'foreign-sqlite-reader-entry',
'session-search-worker-entry',
'main-thread-hang-watchdog-entry',
'port-scan-command-worker-entry',
'command-path-directory-worker-entry',
'worker-thread-child-process-entry',
...(['usage-scan', 'workspace-space-scan'] as const).map((n) => `${n}-worker-entry` as const),
'claude-profile-setup-worker-entry',
...(['backup', 'writer'] as const).map((kind) => `profile-state-${kind}-worker-entry` as const),
'plugin-source-transpile-worker-entry'
] as const
+2
View File
@@ -368,12 +368,14 @@ module.exports = {
'out/main/session-scanner-service-entry.js',
'out/main/wsl-transcript-fs-process-entry.js',
'out/main/foreign-sqlite-reader-entry.js',
'out/main/session-search-worker-entry.js',
'out/main/plugin-host-entry.js',
'out/main/browser-extension-native-host-supervisor-entry.js',
'out/main/computer-sidecar.js',
'out/main/parcel-watcher-process-entry.js',
'out/main/orcad/orcad-local-serve-selection-entry.js',
'out/main/orcad/orcad-stale-lock-reclaim.js',
'out/main/orcad/orcad-host-identity-reset.js',
'out/main/chunks/**',
'out/renderer/**',
'out/mobile-web/**',
+5 -10
View File
@@ -79,8 +79,6 @@
1 test-no-polling-loop:src/renderer/src/components/terminal-pane/pty-connection/emulation/fish-color-scheme-child-stdin.node-pty.test.ts
2 test-no-polling-loop:src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts
1 test-no-polling-loop:src/shared/darwin-terminal-names-real-ps.test.ts
1 test-no-polling-loop:src/shared/fish-query-reply-child-stdin.node-pty.test.ts
1 test-no-polling-loop:src/shared/remote-runtime/control/remote-runtime-shared-control-standing-intent.test.ts
1 test-no-polling-loop:src/shared/startup-command-staging.node-pty.test.ts
1 test-no-polling-loop:src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts
1 test-no-polling-loop:tests/e2e/agent-session-live-force-exit-resume.spec.ts
@@ -288,10 +286,8 @@
1 test-no-real-time-wait:src/shared/darwin-process-table-capture.test.ts
1 test-no-real-time-wait:src/shared/darwin-terminal-names-real-ps.test.ts
1 test-no-real-time-wait:src/shared/darwin-terminal-names.test.ts
5 test-no-real-time-wait:src/shared/fish-query-reply-child-stdin.node-pty.test.ts
1 test-no-real-time-wait:src/shared/git/status/git-branch-line-total-soft-deadline.test.ts
2 test-no-real-time-wait:src/shared/remote-runtime/control/remote-runtime-shared-control-auth-refusal.test.ts
1 test-no-real-time-wait:src/shared/remote-runtime/control/remote-runtime-shared-control-standing-intent.test.ts
2 test-no-real-time-wait:src/shared/startup-command-staging.node-pty.test.ts
4 test-no-real-time-wait:src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts
1 test-no-real-time-wait:src/wsl-guest/agent-hook-canonical-status.test.ts
@@ -569,11 +565,11 @@
1 test-no-wall-clock:src/main/pty/history/terminal-history-gc-fs-call-count.test.ts
2 test-no-wall-clock:src/main/pty/process-retirement/posix-pty-process-groups.integration.test.ts
4 test-no-wall-clock:src/main/pty/process-retirement/windows-live-tree-kill.win32.test.ts
17 test-no-wall-clock:src/main/rate-limits/service-account-target-selection.test.ts
1 test-no-wall-clock:src/main/rate-limits/service-cursor-usage.test.ts
3 test-no-wall-clock:src/main/rate-limits/service-minimax-usage.test.ts
3 test-no-wall-clock:src/main/rate-limits/service-refresh-orchestration.test.ts
3 test-no-wall-clock:src/main/rate-limits/service-zcode-usage.test.ts
17 test-no-wall-clock:src/main/rate-limits/service/service-account-target-selection.test.ts
1 test-no-wall-clock:src/main/rate-limits/service/service-cursor-usage.test.ts
3 test-no-wall-clock:src/main/rate-limits/service/service-minimax-usage.test.ts
3 test-no-wall-clock:src/main/rate-limits/service/service-refresh-orchestration.test.ts
3 test-no-wall-clock:src/main/rate-limits/service/service-zcode-usage.test.ts
1 test-no-wall-clock:src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts
2 test-no-wall-clock:src/main/runtime/agent-session/structured-agent-session-held-signal.test.ts
1 test-no-wall-clock:src/main/runtime/agent-session/structured-child-records-switch.test.ts
@@ -678,7 +674,6 @@
7 test-no-wall-clock:src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts
1 test-no-wall-clock:src/shared/agent-hook-listener/transport/agent-hook-spool-drain.test.ts
1 test-no-wall-clock:src/shared/agent-hook-listener/transport/agent-hook-spool-read.test.ts
2 test-no-wall-clock:src/shared/fish-query-reply-child-stdin.node-pty.test.ts
1 test-no-wall-clock:src/shared/mobile-push-contract.test.ts
2 test-no-wall-clock:src/shared/startup-command-staging.node-pty.test.ts
1 test-no-wall-clock:src/shared/startup-command-staging.test.ts
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+19 -5
View File
@@ -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,
+10 -11
View File
@@ -8,14 +8,13 @@
11 src/main/agent-hooks/installation/configuration/hooks-json-write.ts
6 src/main/agent-hooks/installation/scripts/locked-executable-rename.ts
9 src/main/agent-hooks/installation/scripts/managed-hook-script-write.ts
2 src/main/agent-hooks/server/last-status-legacy-file.ts
1 src/main/agent-hooks/server/last-status-saved-rows.ts
1 src/main/agent-hooks/wsl-relay/wsl-hook-relay-deps.ts
3 src/main/agent-hooks/wsl-relay/wsl-hook-relay-launch.ts
1 src/main/agent-launch/trust/agent-trust-ownership-ledger.ts
14 src/main/agent-launch/trust/agent-trust-presets.ts
2 src/main/agent-launch/trust/antigravity-workspace-trust-ownership.ts
1 src/main/agent-launch/trust/execution-host-workspace-trust.ts
1 src/main/ai-vault-search/session-search-worker-client.ts
4 src/main/ai-vault/parse-cache/session-parse-cache-legacy-json.ts
2 src/main/ai-vault/scan-service/session-scanner-service-entry-path.ts
1 src/main/ai-vault/scan-service/session-scanner-service-spawn.ts
@@ -355,6 +354,7 @@
3 src/main/orcad/orcad-data-root-privacy.ts
4 src/main/orcad/orcad-host-account-launch-env-store.ts
1 src/main/orcad/orcad-host-adapters.ts
1 src/main/orcad/orcad-host-identity-reset.ts
2 src/main/orcad/orcad-idle-stop-record.ts
3 src/main/orcad/orcad-instance-lock-hold.ts
16 src/main/orcad/orcad-instance-lock-reclaim.ts
@@ -373,8 +373,6 @@
2 src/main/orcad/orcad-wsl-host-claude-profile-refresh.ts
1 src/main/orcad/serve-profile-ssh-targets.ts
6 src/main/persistence/atomic-snapshot-writer.ts
1 src/main/persistence/loading-store/github-cache-sidecar.ts
1 src/main/persistence/loading-store/github-cache-startup-read.ts
5 src/main/persistence/loading-store/user-data-path.ts
9 src/main/persistence/migrating-orcad-catalog/migration-journal-directory.ts
4 src/main/persistence/migrating-orcad-catalog/orcad-migration-blob-installers.ts
@@ -463,17 +461,18 @@
6 src/main/pty/shell-startup/zsh-startup-hook-pty-harness.ts
2 src/main/pty/shell-startup/zsh-wrapper-dir-ownership.ts
1 src/main/qoder/workspace-trust.ts
4 src/main/rate-limits/cursor-auth.ts
2 src/main/rate-limits/grok-auth.ts
3 src/main/rate-limits/hidden-probe-cwd.ts
2 src/main/rate-limits/opencode-go-api-key-source.ts
1 src/main/rate-limits/zcode-usage-credentials.ts
4 src/main/rate-limits/providers/cursor/cursor-auth.ts
2 src/main/rate-limits/providers/grok/grok-auth.ts
3 src/main/lib/hidden-probe-cwd.ts
2 src/main/rate-limits/providers/opencode-go/opencode-go-api-key-source.ts
1 src/main/rate-limits/providers/zcode/zcode-usage-credentials.ts
3 src/main/ripgrep/bundled-ripgrep-path.ts
8 src/main/runtime/agent-session/ownership/agent-session-claim-identity.ts
1 src/main/runtime/agent-session/records/agent-session-record-store-slot.ts
7 src/main/runtime/agent-session/records/agent-session-runtime-end-record.ts
1 src/main/runtime/agent-session/structured-agent-session-attachment-wiring.ts
1 src/main/runtime/client/navigation/desktop-chat-creation-history.ts
9 src/main/runtime/host-instance-identity.ts
4 src/main/runtime/hosts/platform-probe/host-descriptor.ts
5 src/main/runtime/mobile-cloud-relay/relay-region-preference.ts
2 src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts
@@ -501,8 +500,8 @@
1 src/main/speech/stt-worker-model-config.ts
2 src/main/speech/stt-worker-paths.ts
2 src/main/sqlite/harden-database-files.ts
1 src/main/sqlite/keyed-json-row-cache.ts
5 src/main/sqlite/legacy-json-source.ts
1 src/main/sqlite/row-cache/keyed-json-row-cache.ts
2 src/main/sqlite/row-cache/legacy-json-source.ts
1 src/main/sqlite/sync-database.ts
2 src/main/sqlite/versioned-cache-database.ts
1 src/main/ssh/authentication/ssh-auth-resolution.ts
-1
View File
@@ -3,7 +3,6 @@ import original from '../mobile/vitest.config.ts'
// Keep real process, native, and runtime-specific contracts on Node.
const nodeFiles = [
'src/components/WorktreeAgentList.runtime-lineage.test.tsx',
'scripts/check-tests-typecheck-incremental-cache.test.ts',
'src/mock-server-key-pair.test.ts',
'src/mobile-release/prepare-android-release-script.test.ts',
-1
View File
@@ -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
@@ -86,7 +86,7 @@ src/main/providers/macos-login-session-pty-probe.ts
src/main/providers/process-cwd.ts
src/main/pty/process-retirement/pty-descendant-fresh-table.ts
src/main/pty/environment/windows-environment-path.ts
src/main/rate-limits/gemini-cli-oauth-extractor.ts
src/main/rate-limits/providers/gemini/gemini-cli-oauth-extractor.ts
src/main/runtime/rpc/server/pairing/network/windows-default-route-interfaces.ts
src/main/runtime/rpc/server/pairing/network/windows-mobile-firewall.ts
src/main/ssh/connection/ssh-connection.ts
+7 -7
View File
@@ -309,7 +309,7 @@
1 src/renderer/src/components/right-sidebar/ai-vault/panel/AiVaultPanel.tsx
2 src/renderer/src/components/right-sidebar/ai-vault/scanning/AiVaultScanProgressStrip.tsx
1 src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-association-observation.ts
9 src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-session-refresh.ts
8 src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-session-refresh.ts
1 src/renderer/src/components/right-sidebar/ai-vault/search/AiVaultPanelSearch.tsx
1 src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.ts
2 src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-delete-action.ts
@@ -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
@@ -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
File diff suppressed because one or more lines are too long
@@ -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/)
})
})
})
@@ -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('<!doctype html>\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 })
}
})
})
@@ -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')
})
})
@@ -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 })
}
})
})
@@ -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,
@@ -39,7 +39,6 @@ export const UNIT_EXCLUDE = [
'src/main/startup/shell-probe-terminal-detach.live-shell.test.ts',
'src/main/startup/shell-probe-lifetime.live-shell.test.ts',
'src/renderer/src/components/terminal-pane/pty-connection/emulation/fish-color-scheme-child-stdin.node-pty.test.ts',
'src/shared/fish-query-reply-child-stdin.node-pty.test.ts',
'src/shared/fish-wsl-cwd-report.node-pty.test.ts',
'src/main/wsl/filesystem/wsl-sh-cwd-report.node-pty.test.ts',
'src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts',
@@ -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 <button>Ready</button> }\n'
const indexKeyComponent =
'export default function App() { return <div>{["one"].map((text, index) => <span key={index}>{text}</span>)}</div> }\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 })
}
@@ -1,7 +1,7 @@
import { cp, mkdir, mkdtemp, readFile, readdir, stat, writeFile } from 'node:fs/promises'
import { mkdir, mkdtemp, readFile, readdir, writeFile } from 'node:fs/promises'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { delimiter, dirname, join } from 'node:path'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { removeTree } from '../../../../src/shared/windows-transient-lock-removal.ts'
@@ -14,31 +14,6 @@ const {
} = require('../../../packaged-runtime-node-modules.cjs')
describe('packaged runtime resources', () => {
it('verifies packaged main runtime deps from Windows-style asar entries', async () => {
const resourcesDir = await mkdtemp(join(tmpdir(), 'orca-runtime-deps-'))
try {
await writeFile(join(resourcesDir, 'app.asar'), '', 'utf8')
await mkdir(join(resourcesDir, 'node_modules', 'yaml'), { recursive: true })
await mkdir(join(resourcesDir, 'node_modules', 'zod'), { recursive: true })
const sources = new Map([
['out\\main\\index.js', 'const z = require("zod")'],
[
'out\\main\\agent-hooks\\installation\\managed-agent-hook-controls.js',
'const YAML = require("yaml")'
]
])
const asar = {
listPackage: () => [...sources.keys()].map((entry) => `\\${entry}`),
extractFile: (_asarPath, internalPath) => Buffer.from(sources.get(internalPath), 'utf8')
}
expect(() => verifyPackagedMainRuntimeDeps(resourcesDir, asar)).not.toThrow()
} finally {
await removeTree(resourcesDir)
}
})
it('verifies literal dynamic imports from the packaged main bundle', async () => {
const resourcesDir = await mkdtemp(join(tmpdir(), 'orca-runtime-dynamic-imports-'))
try {
@@ -144,61 +119,6 @@ describe('packaged runtime resources', () => {
}
})
it('ignores member calls onto Orca methods that are themselves named require', async () => {
const resourcesDir = await mkdtemp(join(tmpdir(), 'orca-runtime-member-require-'))
try {
await writeFile(join(resourcesDir, 'app.asar'), '', 'utf8')
// Registry require(key) members are not packaged bare-module imports, even with literal keys.
const sources = new Map([
['out/main/index.js', 'registry.require("public-a");grants.require(`host-key`)'],
[
'out/main/agent-hooks/installation/managed-agent-hook-controls.js',
'state.import("android-sdk")'
]
])
const asar = {
listPackage: () => [...sources.keys()].map((entry) => `/${entry}`),
extractFile: (_asarPath, internalPath) => Buffer.from(sources.get(internalPath), 'utf8')
}
expect(() => verifyPackagedMainRuntimeDeps(resourcesDir, asar)).not.toThrow()
} finally {
await removeTree(resourcesDir)
}
})
it('prunes non-target node-pty architecture outputs from packaged runtime resources', async () => {
const resourcesDir = await mkdtemp(join(tmpdir(), 'orca-node-pty-prune-'))
try {
const nodePtyDir = join(resourcesDir, 'node_modules', 'node-pty')
const prebuildsDir = join(nodePtyDir, 'prebuilds')
const binDir = join(nodePtyDir, 'bin')
await mkdir(join(prebuildsDir, 'darwin-arm64'), { recursive: true })
await mkdir(join(prebuildsDir, 'darwin-x64'), { recursive: true })
await mkdir(join(prebuildsDir, 'linux-x64'), { recursive: true })
await mkdir(join(prebuildsDir, 'win32-x64'), { recursive: true })
await mkdir(join(binDir, 'darwin-arm64-148'), { recursive: true })
await mkdir(join(binDir, 'darwin-x64-148'), { recursive: true })
await mkdir(join(nodePtyDir, 'third_party', 'conpty'), {
recursive: true
})
await mkdir(join(nodePtyDir, 'deps', 'winpty'), { recursive: true })
prunePackagedNodePty(resourcesDir, 'darwin', 3)
await expect(readdir(prebuildsDir)).resolves.toEqual(['darwin-arm64'])
await expect(readdir(binDir)).resolves.toEqual(['darwin-arm64-148'])
await expect(readdir(join(nodePtyDir, 'third_party'))).resolves.toEqual([])
await expect(readdir(join(nodePtyDir, 'deps'))).resolves.toEqual([])
expect(() => prunePackagedNodePty(resourcesDir, 'darwin', 4)).toThrow(
'Unsupported packaged runtime architecture: 4'
)
} finally {
await removeTree(resourcesDir)
}
})
it('copies the Windows node-pty ConPTY runtime beside the rebuilt addon', async () => {
for (const [arch, electronArch] of [
['x64', 1],
@@ -236,31 +156,6 @@ describe('packaged runtime resources', () => {
}
})
it('prunes non-target @parcel/watcher architecture subpackages', async () => {
const resourcesDir = await mkdtemp(join(tmpdir(), 'orca-parcel-watcher-prune-'))
try {
const parcelDir = join(resourcesDir, 'node_modules', '@parcel')
await mkdir(join(parcelDir, 'watcher'), { recursive: true })
await mkdir(join(parcelDir, 'watcher-darwin-arm64'), { recursive: true })
await mkdir(join(parcelDir, 'watcher-darwin-x64'), { recursive: true })
await mkdir(join(parcelDir, 'watcher-linux-x64-glibc'), { recursive: true })
await mkdir(join(parcelDir, 'watcher-linux-arm64-glibc'), { recursive: true })
await mkdir(join(parcelDir, 'watcher-win32-x64'), { recursive: true })
prunePackagedParcelWatcher(resourcesDir, 'linux', 'arm64')
await expect(readdir(parcelDir).then((entries) => entries.sort())).resolves.toEqual([
'watcher',
'watcher-linux-arm64-glibc'
])
expect(() => prunePackagedParcelWatcher(resourcesDir, 'linux', 'universal')).toThrow(
'Unsupported packaged runtime architecture: universal'
)
} finally {
await removeTree(resourcesDir)
}
})
it('leaves unrelated @parcel/* runtime deps untouched when pruning the watcher', async () => {
const resourcesDir = await mkdtemp(join(tmpdir(), 'orca-parcel-watcher-prune-unrelated-'))
try {
@@ -296,113 +191,4 @@ describe('packaged runtime resources', () => {
await removeTree(root)
}
})
it.skipIf(process.platform === 'win32')(
'prunes non-target native packages before the Linux glibc gate',
async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-after-pack-prune-order-'))
const previousPath = process.env.PATH
try {
const appOutDir = join(root, 'linux-unpacked')
const resourcesDir = join(appOutDir, 'resources')
await cp(join(process.cwd(), 'resources', 'plugins'), join(resourcesDir, 'plugins'), {
recursive: true
})
await seedBundledRipgrep(resourcesDir)
await seedPackagedServePayload(resourcesDir)
const unpackedMainDir = join(resourcesDir, 'app.asar.unpacked', 'out', 'main')
await mkdir(unpackedMainDir, { recursive: true })
await writeFile(join(unpackedMainDir, 'daemon-entry.js'), '', 'utf8')
await writeFile(
join(resourcesDir, 'app.asar.unpacked', 'out', 'package.json'),
`${JSON.stringify({ name: 'orca-compiled-output', type: 'commonjs', private: true })}\n`,
'utf8'
)
const unpackedCliDir = join(resourcesDir, 'app.asar.unpacked', 'out', 'cli')
await mkdir(join(unpackedCliDir, 'handlers'), { recursive: true })
await writeFile(join(unpackedCliDir, 'handlers', 'skills.js'), '', 'utf8')
await writeFile(join(unpackedCliDir, 'index.js'), '', 'utf8')
const target =
process.arch === 'x64'
? { electronArch: 3, machine: 0xb7, nonTarget: 'x64' }
: { electronArch: 1, machine: 0x3e, nonTarget: 'arm64' }
const wrongArchPackage = join(
resourcesDir,
'node_modules',
'@parcel',
`watcher-linux-${target.nonTarget}-glibc`
)
await mkdir(wrongArchPackage, { recursive: true })
const wrongArchElf = Buffer.alloc(20)
wrongArchElf.set([0x7f, 0x45, 0x4c, 0x46])
wrongArchElf[5] = 1
wrongArchElf.writeUInt16LE(target.machine, 18)
await writeFile(join(wrongArchPackage, 'watcher.node'), wrongArchElf)
await seedClipboardPublisher(resourcesDir, target.machine)
await stubObjdump(root)
await expect(
electronBuilderConfig.afterPack({
appOutDir,
electronPlatformName: 'linux',
arch: target.electronArch,
packager: { appInfo: { version: '9.9.9' } }
})
).resolves.toBeUndefined()
await expect(stat(wrongArchPackage)).rejects.toMatchObject({ code: 'ENOENT' })
} finally {
process.env.PATH = previousPath
await removeTree(root)
}
}
)
})
// Headers model architecture; objdump is stubbed for these packaging-layout tests.
async function seedClipboardPublisher(resourcesDir, machine) {
const binDir = join(resourcesDir, 'bin')
await mkdir(binDir, { recursive: true })
const elf = Buffer.alloc(64)
elf.set([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1])
elf.writeUInt16LE(2, 16)
elf.writeUInt16LE(machine, 18)
elf.writeUInt32LE(1, 20)
elf.writeUInt16LE(64, 52)
await writeFile(join(binDir, 'orca-wayland-clipboard'), elf)
}
async function stubObjdump(root) {
const directory = join(root, 'bin')
await mkdir(directory)
await writeFile(join(directory, 'objdump'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
process.env.PATH = `${directory}${delimiter}${process.env.PATH ?? ''}`
}
async function seedPackagedServePayload(resourcesDir) {
const { SERVE_SELECTION_ENTRY } = require('./verify-packaged-serve-payload.cjs')
const entry = join(resourcesDir, 'app.asar.unpacked', 'out', ...SERVE_SELECTION_ENTRY.split('/'))
await mkdir(dirname(entry), { recursive: true })
await writeFile(entry, '')
const webDir = join(resourcesDir, 'app.asar.unpacked', 'out', 'renderer')
await mkdir(join(webDir, 'assets'), { recursive: true })
await mkdir(join(resourcesDir, 'app.asar.unpacked', 'out', 'cli'), { recursive: true })
await writeFile(join(webDir, 'web-index.html'), '<script src="./assets/web.js"></script>')
await writeFile(join(webDir, 'assets', 'web.js'), '')
await writeFile(
join(webDir, '.orca-web-client-files.json'),
JSON.stringify(['web-index.html', 'assets/web.js'])
)
}
async function seedBundledRipgrep(resourcesDir) {
const { BUNDLED_RIPGREP_PLATFORMS } = require('../../../bundled-ripgrep-resources.cjs')
for (const platform of BUNDLED_RIPGREP_PLATFORMS) {
const dir = join(resourcesDir, 'ripgrep', platform)
await mkdir(dir, { recursive: true })
await writeFile(join(dir, platform.startsWith('win32-') ? 'rg.exe' : 'rg'), '', 'utf8')
}
}
@@ -56,7 +56,6 @@ describe.skipIf(process.platform === 'win32')('terminal host round trip', () =>
}
return {
error,
elapsedMs: Date.now() - startedAt,
daemonAlive,
scratchDirs: readdirSync(root).filter((name) => name.startsWith('oth-'))
}
@@ -108,29 +107,4 @@ describe.skipIf(process.platform === 'win32')('terminal host round trip', () =>
})
expect(messages[2].payload.cwd.startsWith(join(root, 'oth-'))).toBe(true)
})
it('rejects by the deadline and cleans up when the daemon never answers the hello', async () => {
const result = await roundTrip(fakeDaemon('() => {}'), 1_500)
expect(result.error?.message).toMatch(/timed out waiting for the control hello reply/)
expect(result.elapsedMs).toBeLessThan(1_500 + 5_000)
expect(result.daemonAlive).toBe(false)
expect(result.scratchDirs).toEqual([])
})
it('rejects at once and cleans up when the daemon closes the connection', async () => {
const result = await roundTrip(fakeDaemon('(socket) => socket.destroy()'), 10_000)
// A destroyed socket may report a clean close, a reset, or a write after close.
expect(result.error?.message).toMatch(/closed the control connection|ECONNRESET|EPIPE/)
expect(result.elapsedMs).toBeLessThan(10_000)
expect(result.daemonAlive).toBe(false)
expect(result.scratchDirs).toEqual([])
})
it('rejects and cleans up when the daemon replies with malformed JSON', async () => {
const result = await roundTrip(fakeDaemon("(socket) => socket.write('{not json\\n')"), 10_000)
expect(result.error?.message).toMatch(/non-JSON control line: \{not json/)
expect(result.elapsedMs).toBeLessThan(10_000)
expect(result.daemonAlive).toBe(false)
expect(result.scratchDirs).toEqual([])
})
})
@@ -1,243 +0,0 @@
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { chromium } from 'playwright-core'
import { buildMobileWebAppBundle } from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs'
import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-dependencies.mjs'
import {
REPEAT_KEY_LABEL,
commandDockProbeRouteSource
} from '../preview/mobile-web-app-held-press-probe-routes.mjs'
import { MOBILE_WEB_APP_ROUTE_ROOT } from '../mobile-web-app-route-manifest.mjs'
import {
createBundleServer,
installShellDouble,
projectDir,
readBridgeFaultGrant,
readBridgeProtocolVersion,
readShellCsp
} from '../preview/mobile-web-app-render-harness.mjs'
import { LAYOUT_SOURCE } from '../preview/mobile-web-app-terminal-probe-route.mjs'
const ROUTES = {
keys: `/${MOBILE_WEB_APP_ROUTE_ROOT}/command-dock-probe`
}
const bundles = mobileWebAppDependenciesPresent()
const describeRender = bundles ? describe : describe.skip
let browser = null
let origin = null
let scratch = null
let server = null
let bridgeVersion = null
let faultGrant = null
beforeAll(async () => {
if (!bundles) {
return
}
const sessionDir = join(projectDir, 'mobile', 'src', 'session')
const terminalDir = join(projectDir, 'mobile', 'src', 'terminal')
const cspHeader = await readShellCsp()
bridgeVersion = await readBridgeProtocolVersion()
faultGrant = await readBridgeFaultGrant()
scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-held-press-'))
const appDir = join(scratch, 'app')
const routeDir = join(appDir, MOBILE_WEB_APP_ROUTE_ROOT)
await mkdir(routeDir, { recursive: true })
await writeFile(join(routeDir, '_layout.tsx'), LAYOUT_SOURCE)
await writeFile(
join(routeDir, 'command-dock-probe.tsx'),
commandDockProbeRouteSource({
commandDockModule: join(sessionDir, 'MobileSessionCommandDock'),
keyDefinitionsModule: join(terminalDir, 'terminal-key-definitions'),
accessorySelectionModule: join(
terminalDir,
'session',
'use-mobile-session-accessory-selection'
),
dockKeysModule: join(terminalDir, 'session', 'use-terminal-dock-keys'),
liveInputCaptureModule: join(terminalDir, 'session', 'live-input-capture')
})
)
const built = await buildMobileWebAppBundle({
appDir,
outDir: join(scratch, 'bundle'),
pageRoutes: Object.values(ROUTES).map((pathname) => ({ pathname, grants: [] }))
})
const served = await createBundleServer({ outDir: built.outDir, cspHeader })
server = served.server
origin = served.origin
const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER
browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) })
}, 600_000)
afterAll(async () => {
await browser?.close()
server?.close()
if (scratch) {
await rm(scratch, { recursive: true, force: true })
}
})
async function openProbe(pathname) {
const page = await browser.newPage({ viewport: { width: 390, height: 844 }, hasTouch: true })
await page.addInitScript(installShellDouble, {
version: bridgeVersion,
sessionId: 'held-press-session',
buildId: 'held-press-build',
route: { pathname, params: {} },
host: { id: 'held-host', name: 'Held Host', endpoint: 'ws://held', lastConnected: 1 },
storage: {},
faultGrant,
grants: [faultGrant],
pageRoutes: Object.values(ROUTES),
replies: {}
})
const errors = []
page.on('pageerror', (error) => errors.push(`${error.name}: ${error.message}`))
await page.goto(`${origin}/`, { waitUntil: 'load' })
await page.waitForFunction(
() =>
globalThis.__orcaHeldPressProbe !== undefined ||
(globalThis.__orcaRenderCheckFaults ?? []).length > 0,
{ timeout: 60_000, polling: 100 }
)
expect(await page.evaluate(() => globalThis.__orcaRenderCheckFaults ?? [])).toEqual([])
await page.clock.install({ time: new Date('2026-01-01T00:00:00Z') })
await page.clock.pauseAt(new Date('2026-01-01T00:00:01Z'))
return { errors, page }
}
async function beginRepeatKeyTouch(page) {
const key = await page.waitForSelector(`[aria-label="${REPEAT_KEY_LABEL}"]`)
await key.scrollIntoViewIfNeeded()
const box = await key.boundingBox()
const point = { x: box.x + box.width / 2, y: box.y + box.height / 2 }
const input = await page.context().newCDPSession(page)
await input.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [point] })
return { input, key, point }
}
const keyScrollOffset = (key) =>
key.evaluate((node) => {
for (let parent = node.parentElement; parent; parent = parent.parentElement) {
if (
parent.scrollWidth > parent.clientWidth &&
getComputedStyle(parent).overflowX !== 'visible'
) {
return parent.scrollLeft
}
}
throw new Error('Key bar does not overflow')
})
describeRender(
'held presses on the page',
() => {
describe('the key bar', () => {
it('sends a repeatable tap once on release without waiting for the hold delay', async () => {
const { errors, page } = await openProbe(ROUTES.keys)
const { input } = await beginRepeatKeyTouch(page)
await page.clock.runFor(100)
expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.sent())).toEqual([])
await input.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] })
await page.clock.runFor(1)
expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.sent())).toEqual([
'\x1b[A'
])
await page.clock.runFor(1000)
expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.sent())).toEqual([
'\x1b[A'
])
expect(errors).toEqual([])
await page.close()
}, 300_000)
it('drops a prepared tap after switching terminals and accepts a new accessibility click', async () => {
const { errors, page } = await openProbe(ROUTES.keys)
const { input, key } = await beginRepeatKeyTouch(page)
await page.clock.runFor(100)
await page.evaluate(() => globalThis.__orcaHeldPressProbe.switchTerminal())
await page.waitForFunction(
() => globalThis.__orcaHeldPressProbe.activeHandle === 'other-terminal'
)
await input.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] })
await page.clock.runFor(1000)
expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.sent())).toEqual([])
await key.evaluate((node) => node.click())
expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.deliveries())).toEqual([
{ bytes: '\x1b[A', target: 'other-terminal' }
])
expect(errors).toEqual([])
await page.close()
}, 300_000)
it.each([
[100, false],
[700, false],
[700, true]
])(
'keeps Enter activation bound to keydown terminal with hold=%sms and switch=%s',
async (holdMs, switchTerminal) => {
const { errors, page } = await openProbe(ROUTES.keys)
const key = await page.waitForSelector(`[aria-label="${REPEAT_KEY_LABEL}"]`)
await key.focus()
await page.keyboard.down('Enter')
await page.clock.runFor(100)
expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.deliveries())).toEqual([
{ bytes: '\x1b[A', target: 'held-press-terminal' }
])
if (switchTerminal) {
await page.evaluate(() => globalThis.__orcaHeldPressProbe.switchTerminal())
await page.waitForFunction(
() => globalThis.__orcaHeldPressProbe.activeHandle === 'other-terminal'
)
}
await page.clock.runFor(holdMs - 100)
const beforeRelease = await page.evaluate(() =>
globalThis.__orcaHeldPressProbe.deliveries()
)
if (holdMs === 100 || switchTerminal) {
expect(beforeRelease).toHaveLength(1)
} else {
expect(beforeRelease.length).toBeGreaterThan(1)
}
expect(beforeRelease).toEqual(
beforeRelease.map(() => ({ bytes: '\x1b[A', target: 'held-press-terminal' }))
)
await page.keyboard.up('Enter')
await page.clock.runFor(1000)
expect(errors).toEqual([])
expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.deliveries())).toEqual(
beforeRelease
)
await page.close()
},
300_000
)
it('scrolls across a repeatable key without sending it', async () => {
const { errors, page } = await openProbe(ROUTES.keys)
const { input, key, point } = await beginRepeatKeyTouch(page)
const before = await keyScrollOffset(key)
await page.clock.runFor(70)
for (let step = 1; step <= 8; step += 1) {
await input.send('Input.dispatchTouchEvent', {
type: 'touchMove',
touchPoints: [{ ...point, x: point.x - step * 20 }]
})
await page.clock.runFor(20)
}
await input.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] })
await page.clock.runFor(1000)
expect(await keyScrollOffset(key)).toBeGreaterThan(before)
expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.sent())).toEqual([])
expect(errors).toEqual([])
await page.close()
}, 300_000)
})
},
900_000
)
@@ -0,0 +1,12 @@
import { expect, it } from 'vitest'
import { ORCAD_ARTIFACTS } from '../../../../src/shared/orcad-artifacts.ts'
import { ORCAD_CHILD_ENTRY_POINTS, orcadChildOutputFilename } from './orcad-entry-build.mjs'
// A child built but not listed never reaches remote hosts, so its client fails there.
it.each(Object.entries(ORCAD_CHILD_ENTRY_POINTS))(
'ships the %s child bundle as an orcad artifact',
(_name, entryPoint) => {
const filenames = ORCAD_ARTIFACTS.map((artifact) => artifact.filename)
expect(filenames).toContain(orcadChildOutputFilename(entryPoint))
}
)
@@ -20,6 +20,7 @@ export const ORCAD_CHILD_ENTRY_POINTS = {
daemon: 'src/main/daemon/daemon-entry.ts',
writer: 'src/main/persistence/profile-state/profile-state-writer-worker-entry.ts',
backup: 'src/main/persistence/profile-state/profile-state-backup-worker-entry.ts',
sessionSearch: 'src/main/ai-vault-search/session-search-worker-entry.ts',
foreignSqliteReader: 'src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry.ts',
portScanCommandWorker: 'src/main/ports/port-scan-command-worker-entry.ts',
commandPathDirectoryWorker: 'src/main/ipc/command-path/command-path-directory-worker-entry.ts',
@@ -53,10 +53,6 @@ const CHUNK_SOURCE = readFileSync(
new URL('../../../../src/main/runtime/rpc/terminal-output-frame-chunks.ts', import.meta.url),
'utf8'
)
const CLIPBOARD_SOURCE = readFileSync(
new URL('../../../../src/shared/clipboard-text.ts', import.meta.url),
'utf8'
)
const UTF8_SOURCE = readFileSync(
new URL('../../../../src/shared/utf8-byte-limits.ts', import.meta.url),
@@ -78,8 +74,7 @@ for (const [source, label, marker] of [
],
[CHUNK_SOURCE, 'terminal-output-frame-chunks.ts', 'const text = data.slice(chunkStart, end)'],
[CHUNK_SOURCE, 'terminal-output-frame-chunks.ts', 'data.charCodeAt(index + 1)'],
[CLIPBOARD_SOURCE, 'clipboard-text.ts', 'export function measureClipboardTextByteLength('],
[CLIPBOARD_SOURCE, 'clipboard-text.ts', 'return measureUtf8ByteLength(text, options)'],
[UTF8_SOURCE, 'utf8-byte-limits.ts', 'export function measureUtf8ByteLength('],
[UTF8_SOURCE, 'utf8-byte-limits.ts', 'const codePoint = readUtf8CodePointAt(text, index)']
]) {
if (!source.includes(marker)) {
@@ -98,8 +93,8 @@ const { TERMINAL_STREAM_CHUNK_BYTES } = await import(
import.meta.url
).href
)
const { measureClipboardTextByteLength } = await import(
new URL('../../../../src/shared/clipboard-text.ts', import.meta.url).href
const { measureUtf8ByteLength } = await import(
new URL('../../../../src/shared/utf8-byte-limits.ts', import.meta.url).href
)
const { TerminalStreamOpcode, encodeTerminalStreamJson, encodeTerminalStreamText } = await import(
new URL('../../../../src/shared/terminal/stream/terminal-stream-protocol.ts', import.meta.url)
@@ -127,10 +122,7 @@ function* iterateBefore(data, meta) {
}
return
}
if (
!measureClipboardTextByteLength(data, { stopAfterBytes: TERMINAL_STREAM_CHUNK_BYTES })
.exceededLimit
) {
if (!measureUtf8ByteLength(data, { stopAfterBytes: TERMINAL_STREAM_CHUNK_BYTES }).exceededLimit) {
yield { bytes: encodeTerminalStreamText(data), seq: meta?.seq }
return
}
@@ -156,7 +148,7 @@ function* iterateBefore(data, meta) {
}
for (const part of data) {
const partBytes = measureClipboardTextByteLength(part).byteLength
const partBytes = measureUtf8ByteLength(part).byteLength
if (chunkBytes > 0 && chunkBytes + partBytes > TERMINAL_STREAM_CHUNK_BYTES) {
const nextChunk = takeChunk()
if (nextChunk) {
@@ -60,8 +60,8 @@ const { TERMINAL_OUTPUT_BATCH_MAX_BYTES, TERMINAL_STREAM_CHUNK_BYTES } = await i
import.meta.url
).href
)
const { measureClipboardTextByteLength } = await import(
new URL('../../../../src/shared/clipboard-text.ts', import.meta.url).href
const { measureUtf8ByteLength } = await import(
new URL('../../../../src/shared/utf8-byte-limits.ts', import.meta.url).href
)
const {
MIN_NATIVE_BYTE_LENGTH_CODE_UNITS,
@@ -107,9 +107,9 @@ function runWithNativeCallCount(fn) {
}
}
const legacyMeasure = measureClipboardTextByteLength
const legacyMeasure = measureUtf8ByteLength
const legacyExceeds = (data, maxBytes) =>
measureClipboardTextByteLength(data, { stopAfterBytes: maxBytes }).exceededLimit
measureUtf8ByteLength(data, { stopAfterBytes: maxBytes }).exceededLimit
function mulberry32(seed) {
let state = seed >>> 0
@@ -1,6 +1,5 @@
#!/usr/bin/env node
// Compare stdout/stderr/exit byte-for-byte across two real CLI emits: current tree and selected files restored from baseline (default HEAD~).
// Full-tree compilation stays outside fast Vitest invariants (runtime-client-deferral.test.ts).
// Usage: node config/scripts/cli-runtime-client-deferral-equivalence.mjs [--baseline <rev>]
import { execFileSync, spawnSync } from 'node:child_process'
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync, readFileSync } from 'node:fs'
@@ -158,7 +157,6 @@ function buildCases(isolatedUserData) {
[['status', '--json'], { ...isolated, ORCA_REMOTE_PAIRING: 'not-a-pairing-code' }],
[['status', '--json'], { ...isolated, ORCA_ENVIRONMENT: 'no-such-environment' }],
// Keep suppression for local-only groups. Do not invoke agent hooks on/off: they modify real ~/.claude configuration outside ORCA_USER_DATA_PATH.
// Constructor-argument assertions in runtime-client-deferral.test.ts cover null/undefined suppression without those side effects.
[['environment', 'list', '--json'], { ...isolated, ORCA_ENVIRONMENT: 'no-such-environment' }],
[['environment', 'list', '--json'], { ...isolated, ORCA_PAIRING_CODE: 'not-a-pairing-code' }],
[['agent-context', '--json'], { ...isolated, ORCA_PAIRING_CODE: 'not-a-pairing-code' }],
@@ -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)
})
@@ -73,47 +73,6 @@ describe('moved-code exemption', () => {
}
})
it('keeps source boundaries across batches, missing files, and multibyte contents', () => {
const repo = mkdtempSync(path.join(tmpdir(), 'changed-code-quality-batch-'))
try {
const git = (...args) => {
const result = runProcessSync({ program: 'git', args, cwd: repo })
expect(result.code, result.stderr).toBe(0)
return result.stdout.trim()
}
git('init', '--quiet')
const files = Array.from({ length: 40 }, (_, index) => `file ${index} é.ts`)
const sources = files.map((_, index) =>
index === 0 ? '' : ` const café${index} = '🐳'\r\n\r\n// missing\nlastLine()`
)
files.forEach((file, index) => writeFileSync(path.join(repo, file), sources[index]))
git('add', '--all')
git(
'-c',
'commit.gpgsign=false',
'-c',
'user.name=t',
'-c',
'user.email=t@example.invalid',
'commit',
'-qm',
'base'
)
const base = git('rev-parse', 'HEAD')
const expected = sources.map((_, index) =>
index === 0 ? [] : [`const café${index} = '🐳'`, '// missing', 'lastLine()']
)
expect(
collectBaseLineBlocks(repo, base, ['missing.ts', ...files, 'also-missing.ts'])
).toEqual(expected)
expect(collectBaseLineBlocks(repo, base, [])).toEqual([])
expect(collectBaseLineBlocks(repo, base, ['missing.ts'])).toEqual([])
expect(collectBaseLineBlocks(path.join(repo, 'absent'), base, files)).toEqual([])
} finally {
rmSync(repo, { recursive: true, force: true })
}
})
it.skipIf(process.platform === 'win32')('reads filenames containing newlines', () => {
const repo = mkdtempSync(path.join(tmpdir(), 'changed-code-quality-newline-'))
try {
@@ -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'
]
@@ -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.
@@ -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
})
@@ -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)
}
})
@@ -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
}
}
@@ -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))
@@ -1,132 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import process from 'node:process'
import {
collectElectronImporters,
collectStructuredChatEntryPoints,
main
} from './check-runtime-electron-ratchet.mjs'
describe('structured chat coverage', () => {
const roots = []
afterEach(() => {
for (const root of roots.splice(0)) {
rmSync(root, { recursive: true, force: true })
}
})
function fixture(files) {
const root = mkdtempSync(path.join(tmpdir(), 'orca-electron-ratchet-'))
roots.push(root)
for (const [file, source] of Object.entries(files)) {
const absolute = path.join(root, file)
mkdirSync(path.dirname(absolute), { recursive: true })
writeFileSync(absolute, source)
}
return root
}
const requiredLanes = {
'src/main/native-chat/reader.ts': 'export {}',
'src/main/claude/claude-session.ts': 'export {}',
'src/main/codex/codex-session.ts': 'export {}',
'src/main/runtime/structured-agent-session-host.ts': 'export {}',
'src/main/provider-process/provider-process-teardown.ts': 'export {}',
'src/main/acp/session/acp-structured-session-adapter.ts': 'export {}',
'src/main/jsonl-rpc/peer.ts': 'export {}',
'src/main/pi/rpc-launch.ts': 'export {}',
'src/shared/agent-session-record.ts': 'export {}',
'src/packages/process-host/src/run-process.ts': 'export {}'
}
it.each([true, false])(
'finds Electron through an unwired lane package (sideEffects=%s)',
async (sideEffects) => {
const root = fixture({
...requiredLanes,
'src/main/acp/adapter.ts': "import 'acp-desktop-package'",
'src/main/provider-process/worker.ts': "import 'provider-desktop-package'",
'src/main/jsonl-rpc/peer.ts': "import 'rpc-desktop-package'",
'src/main/pi/rpc-launch.ts': "import 'pi-desktop-package'",
'node_modules/acp-desktop-package/package.json': JSON.stringify({
main: 'index.js',
sideEffects
}),
'node_modules/acp-desktop-package/index.js': "require('electron')",
'node_modules/provider-desktop-package/package.json': JSON.stringify({
main: 'index.js',
sideEffects
}),
'node_modules/provider-desktop-package/index.js': "require('electron')",
'node_modules/rpc-desktop-package/package.json': JSON.stringify({
main: 'index.js',
sideEffects
}),
'node_modules/rpc-desktop-package/index.js': "require('electron')",
'node_modules/pi-desktop-package/package.json': JSON.stringify({
main: 'index.js',
sideEffects
}),
'node_modules/pi-desktop-package/index.js': "require('electron')"
})
const current = await collectElectronImporters(collectStructuredChatEntryPoints(root))
expect(current.map((file) => file.split('/node_modules/').pop())).toEqual([
'acp-desktop-package/index.js',
'pi-desktop-package/index.js',
'provider-desktop-package/index.js',
'rpc-desktop-package/index.js'
])
}
)
it('checks public workspace imports against source without requiring a built package', async () => {
const root = fixture({ 'entry.ts': "import '@orca/process-host'" })
const target = path.join(process.cwd(), 'src/packages/process-host/src/run-process.ts')
const current = await collectElectronImporters([path.join(root, 'entry.ts')], {
plugins: [
{
name: 'inject-process-host-electron-import',
setup(pluginBuild) {
pluginBuild.onLoad({ filter: /run-process\.ts$/ }, (args) =>
args.path === target ? { contents: "import 'electron'", loader: 'ts' } : undefined
)
}
}
]
})
expect(current).toEqual(['src/packages/process-host/src/run-process.ts'])
})
})
// Why `main`: it is what `pnpm lint` and CI run, so these fail if its entry list drops the lanes.
describe('the command-line check', () => {
afterEach(() => {
vi.restoreAllMocks()
})
// Why a file the runtime doesn't load: only the structured-chat lanes can catch it.
it('fails on Electron in structured-chat code the runtime graph does not reach', async () => {
const target = path.join(
process.cwd(),
'src',
'main',
'native-chat',
'transcript-read-cache.ts'
)
const addElectron = {
name: 'add-electron-import',
setup(pluginBuild) {
pluginBuild.onLoad({ filter: /transcript-read-cache\.ts$/ }, (args) =>
args.path === target
? { contents: `import 'electron'\n${readFileSync(target, 'utf8')}`, loader: 'ts' }
: undefined
)
}
}
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
expect(await main({ plugins: [addElectron] })).toBe(1)
expect(error.mock.calls.join('\n')).toContain('+ src/main/native-chat/transcript-read-cache.ts')
}, 120_000)
})
@@ -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 () => {
@@ -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()]
}
@@ -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 = <Rows list={list} height={list.getTotalSize()} onPick={() => 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])
})
})
@@ -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'])
})
})
@@ -0,0 +1,203 @@
// 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', 'env']
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(async () => {
// Finish background imports while their file's environment and module promises still exist.
await vi.dynamicImportSettled()
// 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)
}
}
}
})
@@ -0,0 +1,86 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { runProcess, runProcessSync } from '@orca/process-host'
import { expect, it } from 'vitest'
import { resolvePinnedBunExecutable } from '../../tool-invocation/pinned-bun-executable.mjs'
const root = fileURLToPath(new URL('../../../..', import.meta.url))
it('restores environment stubs and finishes background imports before the next shared file', async () => {
const cache = join(root, 'node_modules/.cache')
mkdirSync(cache, { recursive: true })
const directory = mkdtempSync(join(cache, 'shared-worker-reset-'))
const write = (name, source) => writeFileSync(join(directory, name), source)
try {
write(
'vitest.config.mjs',
`import { defineConfig } from 'vitest/config'
import { BaseSequencer } from 'vitest/node'
class Ordered extends BaseSequencer {
async sort(specs) { return specs.sort((a, b) => a.moduleId.localeCompare(b.moduleId)) }
}
export default defineConfig({ test: {
root: ${JSON.stringify(directory)},
include: ['*.spec.mjs'], isolate: false, maxWorkers: 1,
setupFiles: ['./assert-import-finished.mjs', ${JSON.stringify(resolve(root, 'config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs'))}],
sequence: { sequencer: Ordered }
} })`
)
write(
'assert-import-finished.mjs',
`import { afterAll, expect } from 'vitest'
import { readFileSync } from 'node:fs'
afterAll(() => expect(readFileSync(new URL('./result', import.meta.url), 'utf8')).toBe('loaded'))`
)
write(
'import-started.mjs',
`export let started
export const ready = new Promise(resolve => { started = resolve })`
)
write(
'background.mjs',
`import { setImmediate } from 'node:timers/promises'
import { writeFileSync } from 'node:fs'
import { started } from './import-started.mjs'
started()
await setImmediate()
writeFileSync(new URL('./result', import.meta.url), 'loaded')`
)
write(
'01-replace-env.spec.mjs',
`import { it } from 'vitest'
import { ready } from './import-started.mjs'
it('replaces env and starts a background import', async () => {
process.env = { ...process.env }
void import('./background.mjs')
await ready
})`
)
write(
'02-stub-env.spec.mjs',
`import { expect, it, vi } from 'vitest'
it('removes an environment override after a previous file replaced env', () => {
vi.stubEnv('ORCA_SHARED_WORKER_OVERRIDE', 'asia-east2')
vi.unstubAllEnvs()
expect(process.env.ORCA_SHARED_WORKER_OVERRIDE).toBeUndefined()
})`
)
const result = await runProcess({
program: resolvePinnedBunExecutable(root, runProcessSync) ?? 'bun',
args: [
'--bun',
resolve(root, 'node_modules/vitest/vitest.mjs'),
'run',
'--config',
join(directory, 'vitest.config.mjs')
],
cwd: root,
env: { ...process.env, ORCA_BACKGROUND_LAUNCH: '1' },
timeoutMs: 30_000
})
expect(result.code, result.stdout + result.stderr).toBe(0)
} finally {
rmSync(directory, { recursive: true, force: true })
}
})
@@ -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('\\', '/'))
}
@@ -55,15 +55,10 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/pi/rpc-session-startup.test.ts',
'src/main/acp/session/acp-structured-omp-recordings.test.ts',
'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-clear-queued-command.test.ts',
'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',
'src/main/acp/journal/acp-structured-child-work-admission.test.ts',
'src/main/acp/session/children/acp-structured-child-work.test.ts',
'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-background-stop-unreadable.test.ts',
'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-exit-delivery.test.ts',
'src/main/runtime/construction/orca-runtime.test.ts',
@@ -108,7 +103,7 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/runtime/workspaces/removal/runtime-failed-local-worktree-removal.test.ts',
'src/main/runtime/workspaces/removal/runtime-interrupted-local-worktree-removal.test.ts',
'src/main/workspaces/removal/local-worktree-removal-recovery-live.test.ts',
'src/main/rate-limits/codex-rpc-worker-backpressure.test.ts',
'src/main/rate-limits/providers/codex/codex-rpc-worker-backpressure.test.ts',
'src/main/computer/macos-native-provider-client.test.ts',
'src/main/ai-vault-search/session-search-schema.test.ts',
'src/main/ai-vault-search/session-search-fts5-contract.test.ts',
@@ -22,10 +22,14 @@ const SQLITE_HARNESSES = new Set([
'terminal-topology-profile-fixture',
'acknowledged-terminal-tab-retirement-fixture',
// Opens the index read-only after the indexer closes; Bun's macOS SQLite refuses a WAL file then.
'session-search-indexer-test-fixture'
'session-search-indexer-test-fixture',
'session-search-index-test-fixture',
'session-search-engine-test-fixture'
])
export const SQLITE_MODULES = [
'src/main/sqlite/sync-database',
'src/main/ai-vault-search/session-search-schema',
'src/main/ai-vault-search/session-search-store',
'src/main/persistence/profile-state/profile-state-sqlite-authority',
'src/main/native-chat/agent-session-journal/database/journal-host-database',
'src/main/runtime/orchestration/db',
@@ -53,7 +53,8 @@ const LAYOUT_ORACLE_PREFIXES = [
'src/renderer/src/store/slices/tabs/recently-closed-tabs.ts',
// The client the oracle reads every view through.
'src/cli/runtime/client.ts',
'src/shared/remote-runtime/remote-runtime-client.ts',
'src/shared/remote-runtime/requests/remote-runtime-request-socket.ts',
'src/shared/remote-runtime/requests/remote-runtime-subscription-contract.ts',
'src/shared/remote-runtime/requests/remote-runtime-subscription-transport.ts',
'src/shared/remote-runtime/pairing/paired-runtime-connection.ts',
'src/shared/remote-runtime/pairing/pairing.ts',
@@ -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',
@@ -178,9 +177,7 @@ export const WINDOWS_BOUNDARY_TESTS = [
'src/main/jcode/hook-gate-script.test.ts',
'src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts',
'src/main/claude/windows-native-hook-registration.test.ts',
'src/main/agent-hooks/installation/commands/windows-cmd-hook-command-unicode.test.ts',
'src/main/agent-hooks/installation/commands/windows-batch-hook-launcher.test.ts',
'src/main/agent-hooks/installation/commands/windows-powershell-hook-launcher.test.ts',
'src/main/claude/claude-status-line-windows.test.ts',
'src/main/codex/hooks/installation/windows-hook-command.test.ts',
'src/main/codex/hooks/installation/hook-service-managed-install.test.ts',
@@ -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])
})
})
+44 -2
View File
@@ -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,
-1
View File
@@ -19,7 +19,6 @@ const contracts = [
'src/main/usage/jsonl-file-reader.test.ts',
'src/main/usage/jsonl-file-snapshot.test.ts',
'src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-queue-retention.test.ts',
'src/renderer/src/store/diagnostics/store-identity-churn-probe.test.ts',
'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs',
'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs',
'src/main/claude-usage/scanner-incremental-append.test.ts',
@@ -0,0 +1,17 @@
# Remote accepted prompt observations
The committed journal acceptance observer in `native-chat-prompt-submissions.ts` owns the evidence. A fresh personal send from a transport-proven desktop or phone retains its device class and consent-owning desktop in memory until provider acceptance. Queue conversion keeps the original draft's provenance. Reservation, handover, rejected sends, withdrawn drafts, conversation commands, unattended sends and operation replay do not emit an accepted prompt observation.
A paired desktop owner always receives its observation through the existing live structured-chat relay on `runtime.clientEvents.subscribe`, even when the execution host also has initialized desktop telemetry. That host's installation and consent do not own the paired desktop's activity. Only sends without a paired desktop owner, such as the local desktop or its directly paired phone, use the host's initialized telemetry client; disabled consent drops them without a relay fallback. The additive `structured-chat-prompt-telemetry-v1` capability isolates the new event from older readers; older hosts simply omit it. Prompt delivery and journal storage are unchanged.
The event contains only `type`, a fresh observation UUID, `agent_kind` and `client` (`desktop` or `mobile`). No prompt text, session/message/request identifiers, paths, fingerprints, timestamps or device identifiers cross this observation channel. The owner routing key stays on the host: a paired desktop uses its authenticated device ID, and a delegated phone uses its authenticated parent desktop ID. Only an authenticated runtime desktop stream with that owner and the new capability receives the event. Another desktop, a phone stream, the CLI or a declared client without proven identity cannot receive it. A phone paired directly to the local desktop follows the existing local telemetry path.
Both shared-control and one-shot subscription transports use the same desktop-main subscription decoder. The decoder checks the current transport generation, strictly validates the event and deduplicates its UUID before calling the consent-owning telemetry client with `runtime: remote`. It never forwards accepted observations to the renderer. The UUID is not an analytics property. The existing protected milestone admission preserves first-interaction/day ordering, installation attribution, consent and sampling behavior. UUID deduplication retains the newest 1,024 observations across desktop subscriptions; the existing per-install milestone cursor provides additional milestone deduplication.
## Deliberate undercount limits
- The relay is live and best effort, matching the existing agent-start observation channel. Provider acceptance while the desktop is disconnected or before its event stream opens is missed. Reconnect registers a new listener and does not backfill historical acceptance, retry prompt delivery or infer success from send receipts. Desktop restart also clears received UUIDs, but the host does not replay observations.
- Pending prompt provenance is keyed by the live journal object and capped at 256 entries per journal. Host restart or journal replacement loses it. A queued draft or an unaccepted submission persisted before restart may later be accepted without earning a milestone; operation replay and history reads cannot restore its provenance. Older pending entries evicted at the cap also undercount.
- Persisting provenance or recovering disconnected acceptance would require a separate design for durable owner identity, acceptance ordering, retention, consent changes and reader compatibility. This change deliberately adds no outbox, journal annotation or history-derived inference. A later fresh, proven send can still earn the missing milestone.
These limits prefer missing an observation over attributing automation, replay or an unproven user action to an installation.
+4 -4
View File
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="113" height="20" role="img" aria-label="downloads: 159m">
<title>downloads: 159m</title>
<svg xmlns="http://www.w3.org/2000/svg" width="113" height="20" role="img" aria-label="downloads: 160m">
<title>downloads: 160m</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
@@ -15,7 +15,7 @@
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="11">
<text x="37" y="15" fill="#010101" fill-opacity=".3">downloads</text>
<text x="37" y="14">downloads</text>
<text x="93.5" y="15" fill="#010101" fill-opacity=".3">159m</text>
<text x="93.5" y="14">159m</text>
<text x="93.5" y="15" fill="#010101" fill-opacity=".3">160m</text>
<text x="93.5" y="14">160m</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 943 B

After

Width:  |  Height:  |  Size: 943 B

@@ -14,11 +14,11 @@ Accounts are optional: without any, Orca uses your normal Codex login (**System
## Swap accounts
Click the Codex chip in the status bar to open the account switcher, or pick an account in Settings. Any new Codex session launched after that uses it. Sessions already running keep their original account until restarted.
Click the Codex chip in the status bar to open the account switcher, or pick an account in Settings. Any new Codex session launched after that uses it, and open Codex chats move to it before their next message (a reply already running finishes first). Terminal sessions already running keep their original account until restarted.
## Running accounts side by side
Because each added account has its own isolated home, two Codex sessions can run under different accounts at the same time: start one, switch accounts, start the next. Each session keeps the account it launched with. Usage still counts against each account's own plan; Orca does not pool quota across accounts.
Because each added account has its own isolated home, two Codex terminal sessions can run under different accounts at the same time: start one, switch accounts, start the next. Each terminal session keeps the account it launched with; chats always follow the selected account. Usage still counts against each account's own plan; Orca does not pool quota across accounts.
## System default
@@ -31,7 +31,7 @@ For managed Codex accounts, Orca mirrors settings from your real `~/.codex/confi
## Rules & gotchas
- Swapping does not re-authenticate; Orca launches new sessions in the selected account's home.
- Existing Codex processes keep their current account until restart.
- Existing Codex terminal processes keep their current account until restart. Chats switch on their next message.
- Usage readouts in the status bar follow the currently-active account.
- The restart chip preserves the active account at the time of restart.
- Accounts belong to the machine that runs the agent. On a [Remote Orca Server](/docs/remote-servers), add them on that server.
+1 -1
View File
@@ -20,7 +20,7 @@ Many Codex users run multiple accounts to stretch rate limits. Orca's account sw
## System default vs extra accounts
**System default** uses your real `~/.codex` login (the same home a bare `codex` outside Orca would use). Extra accounts Orca manages get their own home under Orca's account data so credentials and rollouts stay isolated. New Codex launches follow the active account; already-running sessions keep the home they started with until you restart them.
**System default** uses your real `~/.codex` login (the same home a bare `codex` outside Orca would use). Extra accounts Orca manages get their own home under Orca's account data so credentials and rollouts stay isolated. New Codex launches follow the active account. Open Codex chats move to it before their next message; already-running terminal sessions keep the home they started with until you restart them.
## Wrapper scripts that set `CODEX_HOME`
+11
View File
@@ -217,6 +217,17 @@ orca-ide serve --pairing-address 100.64.1.20
This only stops Orca from turning the GPU off. Chromium may still render in software on Orca's own Xvfb, which has no GPU of its own; open `chrome://gpu` in a browser pane to check, and point `DISPLAY` at a GPU-backed X server if it reports software rendering. If you installed the server with `orca serve service install`, add the variable to the service unit yourself. If the server stops starting or browser panes crash with it set, unset it to go back to software rendering.
### Copies of a machine image
Copies of a machine image share the server identity: the pairing key, the paired devices, and the installation id. Revoking a device on one copy leaves it working on the others, and the desktop app treats all copies as one server. Set `ORCA_INSTANCE_ID` per instance (for example the cloud-init instance id) in the environment that starts `orca serve`, or run `orca serve reset-identity` on each copy.
- With `ORCA_INSTANCE_ID` set, Orca records the value with the server identity. If a later start sees a different value, Orca creates a new identity and removes all paired devices on that copy, so clients pair with it again.
- The first value Orca sees on an existing server is only recorded, so setting the variable later keeps existing pairings. Use a value that stays the same across restarts of one instance; a value that changes on every boot forces a new pairing each time.
- When `ORCA_INSTANCE_ID` is not set, Orca never changes the identity on its own.
- If Orca cannot write the new identity (for example on a full or read-only disk), it keeps serving the current one unchanged, logs an error, and tries again on the next start.
- `orca serve reset-identity` does the same reset on demand. Stop Orca on that machine first; the command asks for confirmation, or pass `--yes`.
- Each reset moves the replaced files into a new folder under `orca-identity-backups` in the Orca data directory (the five most recent are kept). To undo an unwanted reset, stop Orca and copy the files from that folder back into the data directory.
### Mobile from a headless server
For the Orca mobile app, request a mobile-scoped QR code and link:
+1 -1
View File
@@ -125,7 +125,7 @@ Settings are grouped into panes. Everything here is searchable with `Cmd-,` then
- **Parakeet TDT-CTC JA** — Japanese.
- **SenseVoice** — ZH / EN / JA / KO / Cantonese with auto language detection.
- **Whisper Tiny** — 90+ languages, lower accuracy.
- **GPT-4o mini / GPT-4o Transcribe** — cloud; needs OpenAI key under the same pane.
- **GPT Transcribe** — cloud; needs OpenAI key under the same pane. A saved GPT-4o mini or GPT-4o Transcribe choice moves to it, since OpenAI shuts those down on 2027-02-26.
- While listening, a **Listening…** pill shows a **Stop** control; in toggle mode the tooltip also shows the dictation shortcut.
## SSH
+1
View File
@@ -23,6 +23,7 @@ The categories of behavior we observe:
- **Agent Dashboard** — when the board opens and whether it is visible during a UTC day, labeled as in-window or pop-out. Visible-use observations are limited to one per day per surface across app restarts, so a board left visible across days is counted each day. Hidden or minimized windows pause these observations. This measures visible-use days, not time spent or human attention; no card or agent contents are included.
- **Repos and workspaces** — when you add a repo or create a workspace. We record _how_ you did it (e.g. folder picker vs. clone URL; command palette vs. drag-and-drop), never the repo name, URL, path, branch name, or any free-form text. For a workspace create we also record how long it took and how that time split across its steps, whether a checkout Orca had prepared in advance was reused (and if so, what reset it needed, what prepared it, how long it took to prepare and how long it waited unused; if not, a fixed reason code), for a failed create which step it stopped in, plus coarse context: whether it came from the Orca window or from the CLI, phone or agent interface, whether Git ran locally, in WSL or over SSH, a bucketed worktree count, a bucketed count of the files the repo tracks, how many other creates and prepared-checkout jobs were running, and whether the repo has a post-checkout hook (never its contents).
- **Agents** — which agents you use and their token counts. Never prompts or agent output.
- **Activation and active days** — once per install profile, that a first prompt or message to an agent was observed (which agent kind and which surface: an Orca send, chat, the phone, or a prompt seen by agent hooks), and at most once per UTC day, that you took an explicit action such as launching an agent, sending a message, creating a workspace, or typing in a terminal (only which kind of action came first). Whether the profile was new when this was first recorded is included. Never the prompt, message, or anything typed.
- **Agent errors** — a coarse error category and which agent kind was involved. We never see raw error messages or stack traces; per-incident detail stays in a local diagnostic trace file on your machine and only reaches Orca if you explicitly share a diagnostic bundle.
- **Settings** — when you toggle one of a small whitelisted set of feature-flag or UX preferences. We record which preference changed and whether it's a boolean or an enum, never the raw value of any free-form setting.
- **Tab actions** — for a consistent 10% sample of anonymous installs, the first time per app session you choose “Close Tabs To The Left” or “Close Tabs To The Right,” limited to two events per session across all windows. For that first request in each direction, we record the selected tab's type, whether it is in a workspace or floating panel, how many unpinned tabs are eligible to close, and the sampling rate. The app-open event includes sample membership so we can measure the share of sampled sessions that use each command. Repeat requests are not recorded, so these events do not measure click frequency, overall usage by tab type or panel, or total tabs closed. This counts the request, including when you cancel a save prompt; never tab titles, file paths, or workspace identifiers.
+1 -1
View File
@@ -51,7 +51,7 @@ Tooltips exist to _name_ a control whose meaning isn't obvious from its appearan
- **Use a tooltip when:** an icon-only button or compact chip needs a label. Toolbar icons, badges with abbreviations, truncated paths.
- **Don't use a tooltip when:** the control already has a visible label, the content is interactive (links, buttons), or the message is critical (errors, blocking warnings — those go inline).
- **Mounting:** the global `<TooltipProvider delayDuration={400}>` lives at the App root. Don't nest a second `TooltipProvider` unless you need a different delay for a tightly-scoped surface.
- **Mounting:** the global `<TooltipProvider>` lives at the App root. Tooltips wait 600 ms on each hover; don't nest a second `TooltipProvider` unless a tightly-scoped surface needs a longer delay.
- **Trigger pattern:** wrap the trigger element with `<TooltipTrigger asChild>` so the tooltip's accessibility props attach to the button (not a wrapper span). This is required for keyboard focus to surface the tooltip.
- **Placement:** default `side="top" sideOffset={4}` — match the toolbar pattern in `sidebar/SidebarToolbar.tsx`. Pick a different side only when the default would clip against the viewport.
- **Shortcut chips inside tooltips:** if the action has a keyboard shortcut, append `<ShortcutKeyCombo />` rather than baking the keys into the label string. The chips render correctly per platform; baked-in strings drift.
+2 -1
View File
@@ -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()
@@ -1,6 +1,6 @@
import { withWorkspaceRoute } from '../../../../src/navigation/workspace-route'
import { useLocalSearchParams } from 'expo-router'
import { MobileSourceControlPanel } from '../../../../src/source-control/MobileSourceControlPanel'
import { MobileSourceControlRoutePanel } from '../../../../src/source-control/MobileSourceControlRoutePanel'
import { firstParam } from '../../../../src/navigation/route-param-reader'
import { parseSourceControlHubTab } from '../../../../src/source-control/mobile-source-control-hub-tab'
@@ -16,7 +16,7 @@ export default withWorkspaceRoute(function MobileSourceControlScreen() {
const hostId = firstParam(params.hostId)
const worktreeId = firstParam(params.worktreeId)
return (
<MobileSourceControlPanel
<MobileSourceControlRoutePanel
hostId={hostId}
worktreeId={worktreeId}
name={firstParam(params.name)}
@@ -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
@@ -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<String, Any>)
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()
@@ -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<Boolean, Boolean>? = null
@@ -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<Map<String, Any>>()
private var ready: String? = null
init {
document.sink = this
}
override fun documentLoadState(payload: Map<String, Any>) {
loadStates += payload
if (payload["state"] == "failed") MobileWebShellSparePool.discard(this)
}
/** Before init a page only sends ready, from its first document or one it reloaded. */
override fun documentBridgeMessage(json: String) {
ready = json
document.postHostFrame(MOBILE_WEB_SHELL_PARKED_FRAME)
}
// A parked page has no screen to have been tapped on.
override fun documentExternalNavigation(url: String) = Unit
/** The adopting view sees what a fresh document would have reported, ready last. */
fun handOver(sink: MobileWebShellDocumentSink) {
document.sink = sink
loadStates.forEach(sink::documentLoadState)
ready?.let(sink::documentBridgeMessage)
}
fun destroy() {
document.destroyWebView()
(parking.parent as? ViewGroup)?.removeView(parking)
}
}
/**
* At most one document booted ahead of its screen, only while no page document is shown. Main thread only.
* Parked attached under the content, not detached: a detached WebView took 0.3–1.9 s to paint after 30 s, vs 0.2 s.
*/
internal object MobileWebShellSparePool {
private val main = Handler(Looper.getMainLooper())
private var parked: MobileWebShellSpare? = null
private var claimed: MobileWebShellSpare? = null
private val shown: MutableSet<MobileWebShellDocument> =
Collections.newSetFromMap(WeakHashMap())
/** Whether a spare for [directory] is parked after the call; never on a small phone or beside a page. */
fun prepare(activity: Activity, directory: String, sessionId: String): Boolean {
if (!inForeground() || cannotAffordSpare(activity) || shown.any { it.webView != null }) return false
val current = parked
if (current != null && current.directory == directory && current.document.isUsable) return true
val decor = activity.window?.decorView as? ViewGroup ?: return false
// A claim no view adopted was abandoned; it must not outlive the spare that replaces it.
discardAll()
val spare = MobileWebShellSpare(activity, directory, sessionId)
val webView = spare.document.webView ?: return false
spare.parking.addView(webView, FrameLayout.LayoutParams(MATCH, MATCH))
decor.addView(spare.parking, 0, FrameLayout.LayoutParams(MATCH, MATCH))
parked = spare
spare.document.apply(directory, sessionId, bridgeEnabled = true)
// A load that failed at once has already discarded it.
return parked === spare
}
/** The parked spare's session id for a screen opening [directory], handed out once. */
fun claim(directory: String): String? {
val spare = parked ?: return null
if (spare.directory != directory || !spare.document.isUsable) return null
parked = null
claimed = spare
main.postDelayed({ if (claimed === spare) discard(spare) }, CLAIM_EXPIRY_MS)
return spare.sessionId
}
/** The claimed spare when [sessionId] names it, else a fresh document, which leaves no room for a spare. */
fun document(
context: Context,
sessionId: String,
sink: MobileWebShellDocumentSink
): MobileWebShellDocument {
val spare = claimed
val document = if (spare != null && spare.sessionId == sessionId && spare.document.isUsable) {
claimed = null
spare.document.webView?.let { spare.parking.removeView(it) }
(spare.parking.parent as? ViewGroup)?.removeView(spare.parking)
spare.handOver(sink)
spare.document
} else {
discardAll()
MobileWebShellDocument(context).also { it.sink = sink }
}
shown += document
return document
}
/** Memory pressure, the app leaving the foreground, files going away, or Home without a claim. */
fun discardAll() {
listOfNotNull(parked, claimed).forEach(MobileWebShellSpare::destroy)
parked = null
claimed = null
}
fun discard(spare: MobileWebShellSpare) {
when {
parked === spare -> parked = null
claimed === spare -> claimed = null
else -> return
}
spare.destroy()
}
/** React Native keeps its activity after it stops, so ask the process's own importance. */
private fun inForeground(): Boolean {
val state = ActivityManager.RunningAppProcessInfo()
ActivityManager.getMyMemoryState(state)
return state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
}
private fun cannotAffordSpare(activity: Activity): Boolean {
val manager = activity.getSystemService(ActivityManager::class.java) ?: return true
val memory = ActivityManager.MemoryInfo().also(manager::getMemoryInfo)
// Android 14 stopped sending RUNNING_LOW trims to foreground apps, so check pressure before booting.
return manager.isLowRamDevice || memory.totalMem <= MINIMUM_TOTAL_MEMORY_BYTES || memory.lowMemory
}
}
private const val MATCH = ViewGroup.LayoutParams.MATCH_PARENT
@@ -2,44 +2,16 @@ 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.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.AppContext
import expo.modules.kotlin.exception.CodedException
import expo.modules.kotlin.viewevent.EventDispatcher
import expo.modules.kotlin.views.ExpoView
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
)
@SuppressLint("ViewConstructor", "SetJavaScriptEnabled")
/** React Native's handle on one document: it lays the WebView out and forwards what it reports. */
@SuppressLint("ViewConstructor")
internal class OrcaMobileWebShellView(
context: Context,
appContext: AppContext
) : ExpoView(context, appContext) {
) : ExpoView(context, appContext), MobileWebShellDocumentSink {
private val onLoadState by EventDispatcher<Map<String, Any>>()
private val onBridgeMessage by EventDispatcher<Map<String, Any>>()
private val onExternalNavigation by EventDispatcher<Map<String, Any>>()
@@ -47,23 +19,8 @@ internal class OrcaMobileWebShellView(
private var generationDirectory = ""
private var sessionId = ""
private var bridgeEnabled = false
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
private var webView: WebView? = createWebView()
init {
addView(webView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
// Why: Chromium reports an unpaused, never-attached WebView as visible, and a screen pushed under another never attaches.
webView?.onPause()
}
/** Taken on the first prop commit, not in init: the session id says whether a spare was booted for it. */
private var document: MobileWebShellDocument? = null
fun setGenerationDirectory(value: String) {
generationDirectory = value
@@ -77,348 +34,43 @@ internal class OrcaMobileWebShellView(
bridgeEnabled = value
}
/** Apply unordered props together; identical triples do not retry. Recovery requires a remount. */
fun propsDidUpdate() {
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)) {
failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE)
return
}
served = MobileWebShellServed(loaded, host)
view.visibility = View.VISIBLE
view.loadUrl("$origin/")
val current = document ?: hostDocument().also { document = it }
current.apply(generationDirectory, sessionId, bridgeEnabled)
}
/** 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))
private fun hostDocument(): MobileWebShellDocument {
val document = MobileWebShellSparePool.document(context, sessionId, this)
addView(document.webView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
// Why: Chromium reports an unpaused, never-attached WebView as visible, and a screen pushed under another never attaches.
if (!isAttachedToWindow) document.pause()
return document
}
/** addWebMessageListener injects before scripts and enforces origins; false means unsupported provider. */
private fun applyBridgeListener(view: WebView, origin: String): 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
onBridgeMessage(mapOf("json" to 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)
val current = document ?: throw MobileWebShellBridgeUnavailableException()
current.postBridgeMessage(json)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
webView?.onResume()
document?.resume()
}
// Stay paused whenever off-window so the page reads hidden, as a buried WKWebView does on iOS.
override fun onDetachedFromWindow() {
webView?.onPause()
document?.pause()
super.onDetachedFromWindow()
}
/** Expo calls this once React Native is done with the view, and onRenderProcessGone calls it. */
/** Expo calls this once React Native is done with the view. */
fun destroyWebView() {
val view = webView ?: return
removeBridgeListener()
loadState.documentEnded()
webView = null
blocker?.remove()
blocker = null
served = null
documentFailed = false
view.stopLoading()
removeView(view)
view.destroy()
document?.destroyWebView()
}
// 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
}
override fun documentLoadState(payload: Map<String, Any>) = onLoadState(payload)
private fun emit(emission: MobileWebShellLoadEmission?) {
if (emission != null) onLoadState(emission.toPayload())
}
override fun documentBridgeMessage(json: String) = onBridgeMessage(mapOf("json" to json))
/** 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
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) {
onExternalNavigation(mapOf("url" to 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 background = !isShown || windowVisibility != View.VISIBLE
destroyWebView()
emit(loadState.rendererGone(background, detail.didCrash()))
return true
}
}
override fun documentExternalNavigation(url: String) = onExternalNavigation(mapOf("url" to url))
}
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()
@@ -1,17 +1,75 @@
package expo.modules.orcamobilewebshell
import android.content.ActivityNotFoundException
import android.content.ComponentCallbacks2
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.net.Uri
import android.os.Handler
import android.os.Looper
import expo.modules.kotlin.exception.CodedException
import expo.modules.kotlin.exception.Exceptions
import expo.modules.kotlin.functions.Queues
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class OrcaMobileWebShellModule : Module() {
private val main = Handler(Looper.getMainLooper())
// Kept so teardown unregisters from the same context after React has let go of it.
private var callbacksContext: Context? = null
// A spare is the first thing to give back: nothing is shown by it. UI_HIDDEN, above RUNNING_LOW, is
// the app leaving the foreground; an activity pause is not, since a notification tap or deep link
// pauses it on the way to the screen that would claim the spare.
private val memoryCallbacks = object : ComponentCallbacks2 {
override fun onTrimMemory(level: Int) {
if (level >= ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW) discardSpare()
}
override fun onConfigurationChanged(newConfig: Configuration) = Unit
@Deprecated("Deprecated in Java")
override fun onLowMemory() = discardSpare()
}
// Callbacks and OnDestroy can run off the main thread, and the pool's WebViews must not.
private fun discardSpare() {
main.post { MobileWebShellSparePool.discardAll() }
}
override fun definition() = ModuleDefinition {
Name("OrcaMobileWebShell")
OnCreate {
callbacksContext = appContext.reactContext?.applicationContext?.also {
it.registerComponentCallbacks(memoryCallbacks)
}
}
OnDestroy {
callbacksContext?.unregisterComponentCallbacks(memoryCallbacks)
callbacksContext = null
discardSpare()
}
OnActivityDestroys {
discardSpare()
}
AsyncFunction("prepareSpareDocument") { directory: String, sessionId: String ->
val activity = appContext.currentActivity ?: return@AsyncFunction false
MobileWebShellSparePool.prepare(activity, directory, sessionId)
}.runOnQueue(Queues.MAIN)
AsyncFunction("claimSpareDocument") { directory: String ->
MobileWebShellSparePool.claim(directory)
}.runOnQueue(Queues.MAIN)
AsyncFunction("discardSpareDocument") {
MobileWebShellSparePool.discardAll()
}.runOnQueue(Queues.MAIN)
// Takes a FileProvider content:// URI; the grant lets the chosen viewer read Orca's cache file.
AsyncFunction("presentPdf") { uri: String ->
val activity = appContext.currentActivity ?: throw Exceptions.MissingActivity()
@@ -5,6 +5,9 @@ enum MobileWebShellBridge {
/// Use the same injected global/handler name on Android and iOS.
static let handlerName = "orcaBridge"
/// Tells a page booted ahead of its screen to stop asking for init; the screen that adopts it answers.
static let parkedFrame = #"{"v":1,"type":"parked"}"#
/// Enforce the shared UTF-8 JSON byte ceiling natively, before parsing.
static let maxMessageByteCount = 640 * 1024
@@ -0,0 +1,606 @@
import ExpoModulesCore
import WebKit
private let networkBlockIdentifier = "dev.orca.mobile-web-shell.network-block-v1"
/// Block http(s)/ws(s) beneath CSP; compilation failure is terminal and must load nothing.
private let networkBlockRules = """
[
{ "trigger": { "url-filter": "^https?://" }, "action": { "type": "block" } },
{ "trigger": { "url-filter": "^wss?://" }, "action": { "type": "block" } }
]
"""
/// Compiled once per launch and shared by every view, so later mounts load without waiting; main thread only.
private enum NetworkBlockRuleList {
private static var compiled: WKContentRuleList?
/// Synchronous once compiled in this process; nil means isolation is unavailable.
static func load(_ completion: @escaping (WKContentRuleList?) -> Void) {
if let compiled {
completion(compiled)
return
}
// Optional chaining would skip completion when the store is absent, leaving loading forever; fail closed instead.
guard let store = WKContentRuleListStore.default() else {
completion(nil)
return
}
store.compileContentRuleList(
forIdentifier: networkBlockIdentifier,
encodedContentRuleList: networkBlockRules
) { ruleList, _ in
DispatchQueue.main.async {
if let ruleList {
compiled = ruleList
}
completion(ruleList)
}
}
}
}
/// CSP fences fetch/XHR; document-start script blocks unobservable WebSocket and service-worker APIs.
/// Match Android; both non-configurable and non-writable prevent page replacement.
private let networkApiBlocker = """
(function(){
var deny=function(){throw new TypeError('Network access is disabled')};
try{Object.defineProperty(globalThis,'WebSocket',{value:deny,configurable:false,writable:false})}catch(_){}
try{Object.defineProperty(Navigator.prototype,'serviceWorker',{get:function(){return undefined},configurable:false})}catch(_){}
try{Object.defineProperty(navigator,'serviceWorker',{value:undefined,configurable:false,writable:false})}catch(_){}
})();
"""
/// Inject the same orcaBridge surface as Android before scripts, alongside the network blocker.
/// Capture the sink so deleting window.webkit cannot break it; freeze properties against replacement.
private let bridgeInstaller = """
(function(){
var sink=window.webkit.messageHandlers.orcaBridge;
var handler=null;
var bridge={};
Object.defineProperty(bridge,'postMessage',{value:function(json){
if(typeof json!=='string'){throw new TypeError('orcaBridge.postMessage expects a string')}
sink.postMessage(json)},configurable:false,writable:false,enumerable:true});
Object.defineProperty(bridge,'onmessage',{get:function(){return handler},
set:function(value){handler=typeof value==='function'?value:null},configurable:false,enumerable:true});
Object.defineProperty(bridge,'__deliver',{value:function(json){if(handler){handler({data:json})}},
configurable:false,writable:false,enumerable:false});
Object.defineProperty(globalThis,'orcaBridge',{value:bridge,configurable:false,writable:false,enumerable:true});
})();
"""
/// Bind payload as JS value m, never script text. A missing installer must throw to reject undelivered posts.
private let bridgeDeliver = """
globalThis.orcaBridge.__deliver(m)
"""
private final class MobileWebShellSchemeHandler: NSObject, WKURLSchemeHandler {
/// Read up-to-10-MiB assets off WebKit’s main-thread scheme callbacks.
private let readQueue = DispatchQueue(label: "dev.orca.mobile-web-shell.read")
/// Main-thread live-task set prevents stopped-task delivery’s uncatchable Objective-C exception.
private var liveTasks: Set<ObjectIdentifier> = []
var sessionId: String?
var generation: MobileWebShellGeneration?
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
let key = ObjectIdentifier(urlSchemeTask)
liveTasks.insert(key)
guard
let sessionId,
let generation,
let url = urlSchemeTask.request.url,
let parts = MobileWebShellRequestParts(request: urlSchemeTask.request),
let path = MobileWebShellOrigin.resolveRequestPath(parts, sessionId: sessionId),
let asset = generation.entries[path]
else {
fail(urlSchemeTask, key)
return
}
readQueue.async { [weak self] in
let data = try? Data(contentsOf: asset.file)
DispatchQueue.main.async {
guard let self, self.liveTasks.contains(key) else { return }
guard
let data,
let response = Self.makeResponse(
url: url,
asset: asset,
byteCount: data.count,
path: path
)
else {
self.fail(urlSchemeTask, key)
return
}
self.liveTasks.remove(key)
urlSchemeTask.didReceive(response)
urlSchemeTask.didReceive(data)
urlSchemeTask.didFinish()
}
}
}
func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
liveTasks.remove(ObjectIdentifier(urlSchemeTask))
}
private func fail(_ urlSchemeTask: WKURLSchemeTask, _ key: ObjectIdentifier) {
guard liveTasks.remove(key) != nil else { return }
urlSchemeTask.didFailWithError(URLError(.resourceUnavailable))
}
private static func makeResponse(
url: URL,
asset: MobileWebShellAsset,
byteCount: Int,
path: String
) -> HTTPURLResponse? {
HTTPURLResponse(
url: url,
statusCode: 200,
httpVersion: "HTTP/1.1",
headerFields: MobileWebShellResponseHeaders.forPath(
path,
contentType: asset.contentType,
byteCount: byteCount
)
)
}
}
/// WKUserContentController retains handlers; a weak document reference prevents a React-unmount leak.
private final class MobileWebShellBridgeReceiver: NSObject, WKScriptMessageHandler {
weak var document: MobileWebShellDocument?
func userContentController(
_ controller: WKUserContentController,
didReceive message: WKScriptMessage
) {
document?.receiveBridgeMessage(message)
}
}
/// The RN host sees this, never the page: it is the difference between a request that failed and
/// one that never settles.
internal final class MobileWebShellBridgeDeliveryFailedException: GenericException<String>,
@unchecked Sendable {
override var reason: String {
"The mobile web shell bridge could not deliver a message: \(param)"
}
}
internal final class MobileWebShellBridgeUnavailableException: Exception, @unchecked Sendable {
override var reason: String {
"The mobile web shell bridge is not installed on this view"
}
}
/// Throw so a host chunking bug rejects rather than leaving its request unsettled.
internal final class MobileWebShellBridgeMessageTooLargeException: GenericException<Int>,
@unchecked Sendable {
override var reason: String {
"A bridge message of \(param) bytes exceeds the \(MobileWebShellBridge.maxMessageByteCount) byte cap"
}
}
/// Where a document's reports go: the view showing it, or the spare pool while it is parked.
protocol MobileWebShellDocumentSink: AnyObject {
func documentLoadState(_ payload: [String: Any])
func documentBridgeMessage(_ json: String)
func documentExternalNavigation(_ url: String)
}
/// One WKWebView and every fence on it, apart from React. The view hosts it and lays it out.
final class MobileWebShellDocument: NSObject, WKNavigationDelegate, WKUIDelegate {
weak var sink: MobileWebShellDocumentSink?
let webView: WKWebView
private let schemeHandler = MobileWebShellSchemeHandler()
private let bridgeReceiver = MobileWebShellBridgeReceiver()
private let bridgeGate = MobileWebShellBridgeGate()
private var bridgeInstalled = false
private var bridgeTarget = MobileWebShellBridgeTarget<WKFrameInfo>()
private var applied: MobileWebShellAppliedProps?
private var appliedSessionId: String? { applied?.sessionId }
private var pendingDocumentUrl: URL?
private var isolationReady = false
private var isolationFailed = false
private var destroyed = false
private let loadState = MobileWebShellLoadStateMachine()
private var keyboardPreparationPending = false
private var windowObservers: [NSObjectProtocol] = []
override init() {
let configuration = WKWebViewConfiguration()
configuration.allowsInlineMediaPlayback = true
configuration.mediaTypesRequiringUserActionForPlayback = .all
// WebKit cannot disable DOM storage/databases; isolate with a non-persistent store, per-session origin and unmount destruction.
configuration.websiteDataStore = .nonPersistent()
configuration.preferences.javaScriptCanOpenWindowsAutomatically = false
// Disabling text interaction suppresses text after keydown; page user-select handles long-press selection.
configuration.setURLSchemeHandler(schemeHandler, forURLScheme: MobileWebShellOrigin.scheme)
configuration.userContentController.addUserScript(Self.makeBlockerScript())
webView = WKWebView(frame: .zero, configuration: configuration)
super.init()
bridgeReceiver.document = self
webView.navigationDelegate = self
webView.uiDelegate = self
webView.allowsBackForwardNavigationGestures = false
// WKWebView’s opaque white default flashes during dark-page boot; transparency exposes the shell’s themed frame.
webView.isOpaque = false
webView.backgroundColor = .clear
webView.scrollView.backgroundColor = .clear
webView.scrollView.contentInsetAdjustmentBehavior = .never
hideKeyboardAccessoryBar(of: webView)
ignoreKeyboardNotifications(in: webView)
for name in [
UIWindow.didBecomeKeyNotification, UIScene.didActivateNotification,
UIApplication.didBecomeActiveNotification,
UIResponder.keyboardDidHideNotification, UITextField.textDidEndEditingNotification,
UITextView.textDidEndEditingNotification
] {
windowObservers.append(NotificationCenter.default.addObserver(
forName: name, object: nil, queue: .main
) { [weak self] _ in
self?.loadWhenIsolated()
})
}
installNetworkBlock(into: configuration.userContentController)
}
deinit {
for observer in windowObservers {
NotificationCenter.default.removeObserver(observer)
}
}
/// Still showable: not torn down, and no terminal load failure or content-process loss.
var isUsable: Bool { !destroyed && !loadState.isTerminal }
/// The spare pool's teardown; the content process goes with the last reference.
func destroy() {
destroyed = true
sink = nil
clearBridgeTarget()
pendingDocumentUrl = nil
webView.stopLoading()
webView.removeFromSuperview()
}
/// Apply unordered props together; identical triples do not retry (remount required).
/// Include bridgeEnabled: document-start scripts require a reload to change.
func apply(generationDirectory: String, sessionId: String, bridgeEnabled: Bool) {
let next = MobileWebShellAppliedProps(
generationDirectory: generationDirectory,
sessionId: sessionId,
bridgeEnabled: bridgeEnabled
)
guard applied?.matches(next) != true else { return }
applied = next
clearBridgeTarget()
loadState.reset()
pendingDocumentUrl = nil
webView.stopLoading()
webView.isHidden = false
emit(loadState.started())
guard
MobileWebShellOrigin.isValidSessionId(sessionId),
let documentUrl = MobileWebShellOrigin.documentUrl(sessionId: sessionId)
else {
// The private origin is the isolation primitive; a malformed session id leaves us without one.
failPropUpdate(.isolationUnavailable)
return
}
guard
let generation = try? MobileWebShellGeneration.load(directoryPath: generationDirectory)
else {
failPropUpdate(.generationUnreadable)
return
}
schemeHandler.sessionId = sessionId
schemeHandler.generation = generation
applyBridgeInstallation(bridgeEnabled)
if isolationFailed {
failPropUpdate(.isolationUnavailable)
return
}
pendingDocumentUrl = documentUrl
loadWhenIsolated()
}
/// Retire the old visible generation even when the replacement fails.
private func failPropUpdate(_ reason: MobileWebShellFailureReason) {
clearBridgeTarget()
schemeHandler.sessionId = nil
schemeHandler.generation = nil
pendingDocumentUrl = nil
webView.stopLoading()
webView.isHidden = true
emit(loadState.failed(reason))
}
/// removeAllUserScripts is WebKit’s only removal API, so disabling the bridge must reinstall the blocker.
private static func makeBlockerScript() -> WKUserScript {
WKUserScript(
source: networkApiBlocker,
injectionTime: .atDocumentStart,
forMainFrameOnly: false
)
}
/// Nothing here runs while the prop stays false, which is what keeps Phase B byte-identical.
private func applyBridgeInstallation(_ bridgeEnabled: Bool) {
guard bridgeEnabled != bridgeInstalled else { return }
clearBridgeTarget()
let controller = webView.configuration.userContentController
if bridgeEnabled {
controller.add(bridgeReceiver, name: MobileWebShellBridge.handlerName)
controller.addUserScript(
WKUserScript(
source: bridgeInstaller,
injectionTime: .atDocumentStart,
// Main-frame injection is convenience; accepts must still refuse subframes that reach the handler.
forMainFrameOnly: true
)
)
} else {
controller.removeScriptMessageHandler(forName: MobileWebShellBridge.handlerName)
controller.removeAllUserScripts()
controller.addUserScript(Self.makeBlockerScript())
}
bridgeInstalled = bridgeEnabled
}
/// Use the loaded session, not latest props; the replaced same-origin document survives until commit.
fileprivate func receiveBridgeMessage(_ message: WKScriptMessage) {
guard bridgeInstalled, let json = message.body as? String else { return }
let origin = message.frameInfo.securityOrigin
let source = MobileWebShellBridgeSource(
isOurWebView: message.webView === webView,
isMainFrame: message.frameInfo.isMainFrame,
hasCommittedDocument: loadState.hasCommittedDocument,
originProtocol: origin.`protocol`,
originHost: origin.host
)
guard
MobileWebShellBridge.accepts(source, sessionId: appliedSessionId ?? ""),
bridgeGate.accepts(byteCount: json.utf8.count)
else { return }
bridgeTarget.arm(frame: message.frameInfo, originHost: origin.host)
sink?.documentBridgeMessage(json)
}
/// Anything that ends the document the page spoke from ends the only target native has.
private func clearBridgeTarget() {
bridgeTarget.clear()
}
/// Reject posts without a live committed frame that spoke; resolve only after page execution so host requests cannot hang.
func postBridgeMessage(_ json: String, promise: Promise) throws {
guard
MobileWebShellBridge.canPost(
toFrameOriginHost: bridgeTarget.originHost,
sessionId: appliedSessionId ?? "",
hasCommittedDocument: loadState.hasCommittedDocument
),
let frame = bridgeTarget.frame
else {
throw MobileWebShellBridgeUnavailableException()
}
let byteCount = json.utf8.count
guard MobileWebShellBridge.acceptsByteCount(byteCount) else {
throw MobileWebShellBridgeMessageTooLargeException(byteCount)
}
// Use the two in: labels plus completionHandler to select the callback overload and reply to the frame that spoke.
webView.callAsyncJavaScript(
bridgeDeliver,
arguments: ["m": json],
in: frame,
in: .page
) { result in
switch result {
case .success:
promise.resolve()
case .failure(let error):
promise.reject(MobileWebShellBridgeDeliveryFailedException(error.localizedDescription))
}
}
}
/// A frame from the shell itself, to the frame that spoke; nothing waits on its delivery.
func postHostFrame(_ json: String) {
guard let frame = bridgeTarget.frame else { return }
webView.callAsyncJavaScript(bridgeDeliver, arguments: ["m": json], in: frame, in: .page) { _ in }
}
private func installNetworkBlock(into controller: WKUserContentController) {
NetworkBlockRuleList.load { [weak self] ruleList in
guard let self else { return }
guard let ruleList else {
self.isolationFailed = true
self.pendingDocumentUrl = nil
// Rule compilation can finish after refusal; the state machine prevents a second terminal reason.
if self.appliedSessionId != nil {
self.failPropUpdate(.isolationUnavailable)
}
return
}
controller.add(ruleList)
self.isolationReady = true
self.loadWhenIsolated()
}
}
/// Load only in a foreground-active key window; the view calls this again when it moves to one.
func loadWhenIsolated() {
guard isolationReady, pendingDocumentUrl != nil, !keyboardPreparationPending,
let window = webView.window, window.isKeyWindow,
window.windowScene?.activationState == .foregroundActive else { return }
keyboardPreparationPending = true
DispatchQueue.main.async { [weak self, weak window] in
guard let self else { return }
guard let window, self.webView.window === window, window.isKeyWindow,
window.windowScene?.activationState == .foregroundActive else {
self.keyboardPreparationPending = false
self.loadWhenIsolated()
return
}
let delay: TimeInterval
switch MobileWebShellKeyboardWarmup.prepare(in: window) {
case .ready(let remainingDelay):
delay = remainingDelay
case .waitingForTextInput:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in
guard let self else { return }
self.keyboardPreparationPending = false
self.loadWhenIsolated()
}
return
case .failed:
self.keyboardPreparationPending = false
self.failPropUpdate(.documentLoadFailed)
return
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self, weak window] in
guard let self else { return }
self.keyboardPreparationPending = false
guard let window, self.webView.window === window, window.isKeyWindow,
window.windowScene?.activationState == .foregroundActive else {
self.loadWhenIsolated()
return
}
guard self.isolationReady, let url = self.pendingDocumentUrl else { return }
self.pendingDocumentUrl = nil
self.loadState.shellLoadStarted()
self.webView.load(URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData))
}
}
}
private func emit(_ emission: MobileWebShellLoadEmission?) {
guard let emission else { return }
sink?.documentLoadState(emission.payload)
}
private func reportDocumentFailure() {
clearBridgeTarget()
emit(loadState.failed(.documentLoadFailed))
}
/// A cancelled navigation is our own doing, not the document's; see MobileWebShellNavigationError.
private func reportNavigationFailure(_ error: Error) {
let error = error as NSError
guard !MobileWebShellNavigationError.isIgnorable(domain: error.domain, code: error.code) else {
return
}
reportDocumentFailure()
}
private func isDocumentUrl(_ url: URL?) -> Bool {
guard let url, let parts = MobileWebShellRequestParts(url: url) else { return false }
return MobileWebShellOrigin.resolveRequestPath(parts, sessionId: appliedSessionId ?? "") == "/"
}
func webView(
_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
) {
var isDownload = false
if #available(iOS 14.5, *) {
isDownload = navigationAction.shouldPerformDownload
}
let isMainFrame = navigationAction.targetFrame?.isMainFrame == true
// linkActivated gates only opener offers; gesture-free subframe top navigation must never authorize a load.
let verdict = MobileWebShellNavigationPolicy.verdict(
url: navigationAction.request.url?.absoluteString,
isMainFrame: isMainFrame,
isDocumentUrl: isDocumentUrl(navigationAction.request.url),
isShellLoad: loadState.isShellLoad,
hasGesture: navigationAction.navigationType == .linkActivated,
isDownload: isDownload
)
if case let .cancelAndOffer(url) = verdict {
sink?.documentExternalNavigation(url)
}
if verdict == .allow && isMainFrame {
// Spend before handing back the decision so another main-frame action cannot reuse the allowance.
loadState.shellLoadConsumed()
}
decisionHandler(verdict == .allow ? .allow : .cancel)
}
func webView(
_ webView: WKWebView,
decidePolicyFor navigationResponse: WKNavigationResponse,
decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void
) {
// Only srcdoc subframes pass the action policy; refusing one must not fail the shell document.
guard navigationResponse.isForMainFrame else {
let url = navigationResponse.response.url?.absoluteString
decisionHandler(url == MobileWebShellNavigationPolicy.inlineDocumentUrl ? .allow : .cancel)
return
}
let allowed = navigationResponse.canShowMIMEType &&
isDocumentUrl(navigationResponse.response.url)
if !allowed {
reportDocumentFailure()
}
decisionHandler(allowed ? .allow : .cancel)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
// Clear replies and acceptance when the document is replaced; its successor must commit and send ready.
clearBridgeTarget()
loadState.documentEnded()
guard appliedSessionId != nil else { return }
emit(loadState.started())
}
/// Arm at commit, before document-start messages and didFinish.
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
guard isDocumentUrl(webView.url) else { return }
// Commit rearms acceptance, so clear the replaced frame here as well as at provisional start.
clearBridgeTarget()
loadState.committed()
}
/// history.replaceState changes the path before finish; finished() uses commit state instead of URL equality.
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
MobileWebShellWarmUp.release()
emit(loadState.finished())
}
func webView(
_ webView: WKWebView,
didFailProvisionalNavigation navigation: WKNavigation!,
withError error: Error
) {
MobileWebShellWarmUp.release()
reportNavigationFailure(error)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
MobileWebShellWarmUp.release()
reportNavigationFailure(error)
}
/// Report renderer death; memory pressure/provider updates look alike, so the caller owns retry policy.
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
MobileWebShellWarmUp.release()
clearBridgeTarget()
// Jetsam takes WebContent while Orca is backgrounded; the report can arrive as the app resumes, before it is active.
let background = webView.window == nil || UIApplication.shared.applicationState != .active
emit(loadState.failed(.renderProcessGone, background: background))
}
func webView(
_ webView: WKWebView,
createWebViewWith configuration: WKWebViewConfiguration,
for navigationAction: WKNavigationAction,
windowFeatures: WKWindowFeatures
) -> WKWebView? {
nil
}
}
@@ -28,7 +28,7 @@ struct MobileWebShellLoadEmission: Equatable {
/// Failure is terminal and duplicate reports are dropped: late error-document/rule-list callbacks must never restore ready.
final class MobileWebShellLoadStateMachine {
private var isTerminal = false
private(set) var isTerminal = false
private var last: MobileWebShellLoadEmission?
/// Accept messages only after the current props’ document commits; the replaced same-origin document can still speak before then.
@@ -0,0 +1,150 @@
import UIKit
import WebKit
/// 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 let minimumPhysicalMemory: UInt64 = 3 << 30
/// A claim is adopted on the claiming screen's first commit; this only bounds a screen that never mounts.
private let claimExpirySeconds: TimeInterval = 10
/// 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.
final class MobileWebShellSpare: MobileWebShellDocumentSink {
let document = MobileWebShellDocument()
let directory: String
let sessionId: String
private var loadStates: [[String: Any]] = []
private var ready: String?
init(directory: String, sessionId: String) {
self.directory = directory
self.sessionId = sessionId
document.sink = self
}
func documentLoadState(_ payload: [String: Any]) {
loadStates.append(payload)
if payload["state"] as? String == "failed" {
MobileWebShellSparePool.shared.discard(self)
}
}
/// Before init a page only sends ready, from its first document or one it reloaded.
func documentBridgeMessage(_ json: String) {
ready = json
document.postHostFrame(MobileWebShellBridge.parkedFrame)
}
/// A parked page has no screen to have been tapped on.
func documentExternalNavigation(_ url: String) {}
/// The adopting view sees what a fresh document would have reported, ready last.
func handOver(to sink: MobileWebShellDocumentSink) {
document.sink = sink
loadStates.forEach(sink.documentLoadState)
if let ready {
sink.documentBridgeMessage(ready)
}
}
}
/// At most one document booted ahead of its screen, only while no page document is shown. Main thread only.
/// Parked in the key window at alpha 0: WebKit suspends an off-window view (0.5–1.3 s to paint after 30 s, vs 0.1 s).
final class MobileWebShellSparePool {
static let shared = MobileWebShellSparePool()
private var parked: MobileWebShellSpare?
private var claimed: MobileWebShellSpare?
private let shown = NSHashTable<MobileWebShellDocument>.weakObjects()
/// Whether a spare for `directory` is parked after the call; never on a small phone, inactive app or shown page.
func prepare(directory: String, sessionId: String) -> Bool {
guard
ProcessInfo.processInfo.physicalMemory > minimumPhysicalMemory,
UIApplication.shared.applicationState == .active,
shown.allObjects.isEmpty,
let window = keyWindow()
else { return false }
if let parked, parked.directory == directory, parked.document.isUsable {
return true
}
// A claim no view adopted was abandoned; it must not outlive the spare that replaces it.
discardAll()
let spare = MobileWebShellSpare(directory: directory, sessionId: sessionId)
let webView = spare.document.webView
webView.alpha = 0
webView.isUserInteractionEnabled = false
webView.accessibilityElementsHidden = true
webView.frame = window.bounds
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
window.insertSubview(webView, at: 0)
parked = spare
spare.document.apply(generationDirectory: directory, sessionId: sessionId, bridgeEnabled: true)
// A load that failed at once has already discarded it.
return parked === spare
}
/// The parked spare's session id for a screen opening `directory`, handed out once.
func claim(directory: String) -> String? {
guard let spare = parked, spare.directory == directory, spare.document.isUsable else {
return nil
}
parked = nil
claimed = spare
DispatchQueue.main.asyncAfter(deadline: .now() + claimExpirySeconds) { [weak self, weak spare] in
if let self, let spare, self.claimed === spare {
self.discard(spare)
}
}
return spare.sessionId
}
/// The claimed spare when `sessionId` names it, else a fresh document, which leaves no room for a spare.
func document(for sessionId: String, sink: MobileWebShellDocumentSink) -> MobileWebShellDocument {
let document: MobileWebShellDocument
if let spare = claimed, spare.sessionId == sessionId, spare.document.isUsable {
claimed = nil
document = spare.document
let webView = document.webView
webView.removeFromSuperview()
webView.alpha = 1
webView.isUserInteractionEnabled = true
webView.accessibilityElementsHidden = false
webView.autoresizingMask = []
spare.handOver(to: sink)
} else {
discardAll()
document = MobileWebShellDocument()
document.sink = sink
}
shown.add(document)
return document
}
/// Memory pressure, the app leaving the foreground, files going away, or Home without a claim.
func discardAll() {
for spare in [parked, claimed].compactMap({ $0 }) {
spare.document.destroy()
}
parked = nil
claimed = nil
}
fileprivate func discard(_ spare: MobileWebShellSpare) {
if parked === spare {
parked = nil
} else if claimed === spare {
claimed = nil
} else {
return
}
spare.document.destroy()
}
private func keyWindow() -> UIWindow? {
UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.flatMap(\.windows)
.first(where: \.isKeyWindow)
}
}
@@ -1,190 +1,8 @@
import ExpoModulesCore
import WebKit
private let networkBlockIdentifier = "dev.orca.mobile-web-shell.network-block-v1"
/// Block http(s)/ws(s) beneath CSP; compilation failure is terminal and must load nothing.
private let networkBlockRules = """
[
{ "trigger": { "url-filter": "^https?://" }, "action": { "type": "block" } },
{ "trigger": { "url-filter": "^wss?://" }, "action": { "type": "block" } }
]
"""
/// Compiled once per launch and shared by every view, so later mounts load without waiting; main thread only.
private enum NetworkBlockRuleList {
private static var compiled: WKContentRuleList?
/// Synchronous once compiled in this process; nil means isolation is unavailable.
static func load(_ completion: @escaping (WKContentRuleList?) -> Void) {
if let compiled {
completion(compiled)
return
}
// Optional chaining would skip completion when the store is absent, leaving loading forever; fail closed instead.
guard let store = WKContentRuleListStore.default() else {
completion(nil)
return
}
store.compileContentRuleList(
forIdentifier: networkBlockIdentifier,
encodedContentRuleList: networkBlockRules
) { ruleList, _ in
DispatchQueue.main.async {
if let ruleList {
compiled = ruleList
}
completion(ruleList)
}
}
}
}
/// CSP fences fetch/XHR; document-start script blocks unobservable WebSocket and service-worker APIs.
/// Match Android; both non-configurable and non-writable prevent page replacement.
private let networkApiBlocker = """
(function(){
var deny=function(){throw new TypeError('Network access is disabled')};
try{Object.defineProperty(globalThis,'WebSocket',{value:deny,configurable:false,writable:false})}catch(_){}
try{Object.defineProperty(Navigator.prototype,'serviceWorker',{get:function(){return undefined},configurable:false})}catch(_){}
try{Object.defineProperty(navigator,'serviceWorker',{value:undefined,configurable:false,writable:false})}catch(_){}
})();
"""
/// Inject the same orcaBridge surface as Android before scripts, alongside the network blocker.
/// Capture the sink so deleting window.webkit cannot break it; freeze properties against replacement.
private let bridgeInstaller = """
(function(){
var sink=window.webkit.messageHandlers.orcaBridge;
var handler=null;
var bridge={};
Object.defineProperty(bridge,'postMessage',{value:function(json){
if(typeof json!=='string'){throw new TypeError('orcaBridge.postMessage expects a string')}
sink.postMessage(json)},configurable:false,writable:false,enumerable:true});
Object.defineProperty(bridge,'onmessage',{get:function(){return handler},
set:function(value){handler=typeof value==='function'?value:null},configurable:false,enumerable:true});
Object.defineProperty(bridge,'__deliver',{value:function(json){if(handler){handler({data:json})}},
configurable:false,writable:false,enumerable:false});
Object.defineProperty(globalThis,'orcaBridge',{value:bridge,configurable:false,writable:false,enumerable:true});
})();
"""
/// Bind payload as JS value m, never script text. A missing installer must throw to reject undelivered posts.
private let bridgeDeliver = """
globalThis.orcaBridge.__deliver(m)
"""
private final class MobileWebShellSchemeHandler: NSObject, WKURLSchemeHandler {
/// Read up-to-10-MiB assets off WebKit’s main-thread scheme callbacks.
private let readQueue = DispatchQueue(label: "dev.orca.mobile-web-shell.read")
/// Main-thread live-task set prevents stopped-task delivery’s uncatchable Objective-C exception.
private var liveTasks: Set<ObjectIdentifier> = []
var sessionId: String?
var generation: MobileWebShellGeneration?
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
let key = ObjectIdentifier(urlSchemeTask)
liveTasks.insert(key)
guard
let sessionId,
let generation,
let url = urlSchemeTask.request.url,
let parts = MobileWebShellRequestParts(request: urlSchemeTask.request),
let path = MobileWebShellOrigin.resolveRequestPath(parts, sessionId: sessionId),
let asset = generation.entries[path]
else {
fail(urlSchemeTask, key)
return
}
readQueue.async { [weak self] in
let data = try? Data(contentsOf: asset.file)
DispatchQueue.main.async {
guard let self, self.liveTasks.contains(key) else { return }
guard
let data,
let response = Self.makeResponse(
url: url,
asset: asset,
byteCount: data.count,
path: path
)
else {
self.fail(urlSchemeTask, key)
return
}
self.liveTasks.remove(key)
urlSchemeTask.didReceive(response)
urlSchemeTask.didReceive(data)
urlSchemeTask.didFinish()
}
}
}
func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
liveTasks.remove(ObjectIdentifier(urlSchemeTask))
}
private func fail(_ urlSchemeTask: WKURLSchemeTask, _ key: ObjectIdentifier) {
guard liveTasks.remove(key) != nil else { return }
urlSchemeTask.didFailWithError(URLError(.resourceUnavailable))
}
private static func makeResponse(
url: URL,
asset: MobileWebShellAsset,
byteCount: Int,
path: String
) -> HTTPURLResponse? {
HTTPURLResponse(
url: url,
statusCode: 200,
httpVersion: "HTTP/1.1",
headerFields: MobileWebShellResponseHeaders.forPath(
path,
contentType: asset.contentType,
byteCount: byteCount
)
)
}
}
/// WKUserContentController retains handlers; a weak view reference prevents a React-unmount leak.
private final class MobileWebShellBridgeReceiver: NSObject, WKScriptMessageHandler {
weak var view: OrcaMobileWebShellView?
func userContentController(
_ controller: WKUserContentController,
didReceive message: WKScriptMessage
) {
view?.receiveBridgeMessage(message)
}
}
/// The RN host sees this, never the page: it is the difference between a request that failed and
/// one that never settles.
internal final class MobileWebShellBridgeDeliveryFailedException: GenericException<String>,
@unchecked Sendable {
override var reason: String {
"The mobile web shell bridge could not deliver a message: \(param)"
}
}
internal final class MobileWebShellBridgeUnavailableException: Exception, @unchecked Sendable {
override var reason: String {
"The mobile web shell bridge is not installed on this view"
}
}
/// Throw so a host chunking bug rejects rather than leaving its request unsettled.
internal final class MobileWebShellBridgeMessageTooLargeException: GenericException<Int>,
@unchecked Sendable {
override var reason: String {
"A bridge message of \(param) bytes exceeds the \(MobileWebShellBridge.maxMessageByteCount) byte cap"
}
}
final class OrcaMobileWebShellView: ExpoView, WKNavigationDelegate, WKUIDelegate,
/// React Native's handle on one document: it lays the WebView out and owns the back-edge swipe.
final class OrcaMobileWebShellView: ExpoView, MobileWebShellDocumentSink,
UIGestureRecognizerDelegate {
let onLoadState = EventDispatcher()
let onBridgeMessage = EventDispatcher()
@@ -193,58 +11,28 @@ final class OrcaMobileWebShellView: ExpoView, WKNavigationDelegate, WKUIDelegate
// The page's own Back: the stack's swipe is off while the page claims Back, and a strip overlay would eat taps.
private let backEdgePan = UIPanGestureRecognizer()
private let schemeHandler = MobileWebShellSchemeHandler()
private let bridgeReceiver = MobileWebShellBridgeReceiver()
private let bridgeGate = MobileWebShellBridgeGate()
private var bridgeEnabled = false
private var bridgeInstalled = false
private var bridgeTarget = MobileWebShellBridgeTarget<WKFrameInfo>()
private var webView: WKWebView!
/// Taken on the first prop commit, not in init: the session id says whether a spare was booted for it.
private var document: MobileWebShellDocument?
private var generationDirectory = ""
private var sessionId = ""
private var applied: MobileWebShellAppliedProps?
private var appliedSessionId: String? { applied?.sessionId }
private var pendingDocumentUrl: URL?
private var isolationReady = false
private var isolationFailed = false
private let loadState = MobileWebShellLoadStateMachine()
private var keyboardPreparationPending = false
private var windowObservers: [NSObjectProtocol] = []
private var bridgeEnabled = false
override func didMoveToWindow() {
super.didMoveToWindow()
loadWhenIsolated()
}
deinit {
for observer in windowObservers {
NotificationCenter.default.removeObserver(observer)
}
document?.loadWhenIsolated()
}
required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
let configuration = WKWebViewConfiguration()
configuration.allowsInlineMediaPlayback = true
configuration.mediaTypesRequiringUserActionForPlayback = .all
// WebKit cannot disable DOM storage/databases; isolate with a non-persistent store, per-session origin and unmount destruction.
configuration.websiteDataStore = .nonPersistent()
configuration.preferences.javaScriptCanOpenWindowsAutomatically = false
// Disabling text interaction suppresses text after keydown; page user-select handles long-press selection.
configuration.setURLSchemeHandler(schemeHandler, forURLScheme: MobileWebShellOrigin.scheme)
configuration.userContentController.addUserScript(Self.makeBlockerScript())
bridgeReceiver.view = self
webView = WKWebView(frame: bounds, configuration: configuration)
webView.navigationDelegate = self
webView.uiDelegate = self
webView.allowsBackForwardNavigationGestures = false
// WKWebView’s opaque white default flashes during dark-page boot; transparency exposes the shell’s themed frame.
webView.isOpaque = false
webView.backgroundColor = .clear
webView.scrollView.backgroundColor = .clear
webView.scrollView.contentInsetAdjustmentBehavior = .never
hideKeyboardAccessoryBar(of: webView)
ignoreKeyboardNotifications(in: webView)
backEdgePan.isEnabled = false
backEdgePan.addTarget(self, action: #selector(handleBackEdgePan(_:)))
backEdgePan.delegate = self
addGestureRecognizer(backEdgePan)
}
private func hostDocument() -> MobileWebShellDocument {
let document = MobileWebShellSparePool.shared.document(for: sessionId, sink: self)
let webView = document.webView
webView.translatesAutoresizingMaskIntoConstraints = false
addSubview(webView)
NSLayoutConstraint.activate([
@@ -253,24 +41,8 @@ final class OrcaMobileWebShellView: ExpoView, WKNavigationDelegate, WKUIDelegate
webView.leadingAnchor.constraint(equalTo: leadingAnchor),
webView.trailingAnchor.constraint(equalTo: trailingAnchor)
])
for name in [
UIWindow.didBecomeKeyNotification, UIScene.didActivateNotification,
UIApplication.didBecomeActiveNotification,
UIResponder.keyboardDidHideNotification, UITextField.textDidEndEditingNotification,
UITextView.textDidEndEditingNotification
] {
windowObservers.append(NotificationCenter.default.addObserver(
forName: name, object: nil, queue: .main
) { [weak self] _ in
self?.loadWhenIsolated()
})
}
installNetworkBlock(into: configuration.userContentController)
backEdgePan.isEnabled = false
backEdgePan.addTarget(self, action: #selector(handleBackEdgePan(_:)))
backEdgePan.delegate = self
addGestureRecognizer(backEdgePan)
webView.scrollView.panGestureRecognizer.require(toFail: backEdgePan)
return document
}
func setBackEdgeSwipe(_ value: Bool) {
@@ -310,332 +82,30 @@ final class OrcaMobileWebShellView: ExpoView, WKNavigationDelegate, WKUIDelegate
bridgeEnabled = value
}
/// Apply unordered props together; identical triples do not retry (remount required).
/// Include bridgeEnabled: document-start scripts require a reload to change.
func propsDidUpdate() {
let next = MobileWebShellAppliedProps(
let document = self.document ?? hostDocument()
self.document = document
document.apply(
generationDirectory: generationDirectory,
sessionId: sessionId,
bridgeEnabled: bridgeEnabled
)
guard applied?.matches(next) != true else { return }
applied = next
clearBridgeTarget()
loadState.reset()
pendingDocumentUrl = nil
webView.stopLoading()
webView.isHidden = false
emit(loadState.started())
guard
MobileWebShellOrigin.isValidSessionId(sessionId),
let documentUrl = MobileWebShellOrigin.documentUrl(sessionId: sessionId)
else {
// The private origin is the isolation primitive; a malformed session id leaves us without one.
failPropUpdate(.isolationUnavailable)
return
}
guard
let generation = try? MobileWebShellGeneration.load(directoryPath: generationDirectory)
else {
failPropUpdate(.generationUnreadable)
return
}
schemeHandler.sessionId = sessionId
schemeHandler.generation = generation
applyBridgeInstallation()
if isolationFailed {
failPropUpdate(.isolationUnavailable)
return
}
pendingDocumentUrl = documentUrl
loadWhenIsolated()
}
/// Retire the old visible generation even when the replacement fails.
private func failPropUpdate(_ reason: MobileWebShellFailureReason) {
clearBridgeTarget()
schemeHandler.sessionId = nil
schemeHandler.generation = nil
pendingDocumentUrl = nil
webView.stopLoading()
webView.isHidden = true
emit(loadState.failed(reason))
func postBridgeMessage(_ json: String, promise: Promise) throws {
guard let document else { throw MobileWebShellBridgeUnavailableException() }
try document.postBridgeMessage(json, promise: promise)
}
/// removeAllUserScripts is WebKit’s only removal API, so disabling the bridge must reinstall the blocker.
private static func makeBlockerScript() -> WKUserScript {
WKUserScript(
source: networkApiBlocker,
injectionTime: .atDocumentStart,
forMainFrameOnly: false
)
func documentLoadState(_ payload: [String: Any]) {
onLoadState(payload)
}
/// Nothing here runs while the prop stays false, which is what keeps Phase B byte-identical.
private func applyBridgeInstallation() {
guard bridgeEnabled != bridgeInstalled else { return }
clearBridgeTarget()
let controller = webView.configuration.userContentController
if bridgeEnabled {
controller.add(bridgeReceiver, name: MobileWebShellBridge.handlerName)
controller.addUserScript(
WKUserScript(
source: bridgeInstaller,
injectionTime: .atDocumentStart,
// Main-frame injection is convenience; accepts must still refuse subframes that reach the handler.
forMainFrameOnly: true
)
)
} else {
controller.removeScriptMessageHandler(forName: MobileWebShellBridge.handlerName)
controller.removeAllUserScripts()
controller.addUserScript(Self.makeBlockerScript())
}
bridgeInstalled = bridgeEnabled
}
/// Use the loaded session, not latest props; the replaced same-origin document survives until commit.
fileprivate func receiveBridgeMessage(_ message: WKScriptMessage) {
guard bridgeInstalled, let json = message.body as? String else { return }
let origin = message.frameInfo.securityOrigin
let source = MobileWebShellBridgeSource(
isOurWebView: message.webView === webView,
isMainFrame: message.frameInfo.isMainFrame,
hasCommittedDocument: loadState.hasCommittedDocument,
originProtocol: origin.`protocol`,
originHost: origin.host
)
guard
MobileWebShellBridge.accepts(source, sessionId: appliedSessionId ?? ""),
bridgeGate.accepts(byteCount: json.utf8.count)
else { return }
bridgeTarget.arm(frame: message.frameInfo, originHost: origin.host)
func documentBridgeMessage(_ json: String) {
onBridgeMessage(["json": json])
}
/// Anything that ends the document the page spoke from ends the only target native has.
private func clearBridgeTarget() {
bridgeTarget.clear()
}
/// Reject posts without a live committed frame that spoke; resolve only after page execution so host requests cannot hang.
func postBridgeMessage(_ json: String, promise: Promise) throws {
guard
MobileWebShellBridge.canPost(
toFrameOriginHost: bridgeTarget.originHost,
sessionId: appliedSessionId ?? "",
hasCommittedDocument: loadState.hasCommittedDocument
),
let frame = bridgeTarget.frame
else {
throw MobileWebShellBridgeUnavailableException()
}
let byteCount = json.utf8.count
guard MobileWebShellBridge.acceptsByteCount(byteCount) else {
throw MobileWebShellBridgeMessageTooLargeException(byteCount)
}
// Use the two in: labels plus completionHandler to select the callback overload and reply to the frame that spoke.
webView.callAsyncJavaScript(
bridgeDeliver,
arguments: ["m": json],
in: frame,
in: .page
) { result in
switch result {
case .success:
promise.resolve()
case .failure(let error):
promise.reject(MobileWebShellBridgeDeliveryFailedException(error.localizedDescription))
}
}
}
private func installNetworkBlock(into controller: WKUserContentController) {
NetworkBlockRuleList.load { [weak self] ruleList in
guard let self else { return }
guard let ruleList else {
self.isolationFailed = true
self.pendingDocumentUrl = nil
// Rule compilation can finish after refusal; the state machine prevents a second terminal reason.
if self.appliedSessionId != nil {
self.failPropUpdate(.isolationUnavailable)
}
return
}
controller.add(ruleList)
self.isolationReady = true
self.loadWhenIsolated()
}
}
private func loadWhenIsolated() {
guard isolationReady, pendingDocumentUrl != nil, !keyboardPreparationPending,
let window, window.isKeyWindow,
window.windowScene?.activationState == .foregroundActive else { return }
keyboardPreparationPending = true
DispatchQueue.main.async { [weak self, weak window] in
guard let self else { return }
guard let window, self.window === window, window.isKeyWindow,
window.windowScene?.activationState == .foregroundActive else {
self.keyboardPreparationPending = false
self.loadWhenIsolated()
return
}
let delay: TimeInterval
switch MobileWebShellKeyboardWarmup.prepare(in: window) {
case .ready(let remainingDelay):
delay = remainingDelay
case .waitingForTextInput:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in
guard let self else { return }
self.keyboardPreparationPending = false
self.loadWhenIsolated()
}
return
case .failed:
self.keyboardPreparationPending = false
self.failPropUpdate(.documentLoadFailed)
return
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self, weak window] in
guard let self else { return }
self.keyboardPreparationPending = false
guard let window, self.window === window, window.isKeyWindow,
window.windowScene?.activationState == .foregroundActive else {
self.loadWhenIsolated()
return
}
guard self.isolationReady, let url = self.pendingDocumentUrl else { return }
self.pendingDocumentUrl = nil
self.loadState.shellLoadStarted()
self.webView.load(URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData))
}
}
}
private func emit(_ emission: MobileWebShellLoadEmission?) {
guard let emission else { return }
onLoadState(emission.payload)
}
private func reportDocumentFailure() {
clearBridgeTarget()
emit(loadState.failed(.documentLoadFailed))
}
/// A cancelled navigation is our own doing, not the document's; see MobileWebShellNavigationError.
private func reportNavigationFailure(_ error: Error) {
let error = error as NSError
guard !MobileWebShellNavigationError.isIgnorable(domain: error.domain, code: error.code) else {
return
}
reportDocumentFailure()
}
private func isDocumentUrl(_ url: URL?) -> Bool {
guard let url, let parts = MobileWebShellRequestParts(url: url) else { return false }
return MobileWebShellOrigin.resolveRequestPath(parts, sessionId: sessionId) == "/"
}
func webView(
_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
) {
var isDownload = false
if #available(iOS 14.5, *) {
isDownload = navigationAction.shouldPerformDownload
}
let isMainFrame = navigationAction.targetFrame?.isMainFrame == true
// linkActivated gates only opener offers; gesture-free subframe top navigation must never authorize a load.
let verdict = MobileWebShellNavigationPolicy.verdict(
url: navigationAction.request.url?.absoluteString,
isMainFrame: isMainFrame,
isDocumentUrl: isDocumentUrl(navigationAction.request.url),
isShellLoad: loadState.isShellLoad,
hasGesture: navigationAction.navigationType == .linkActivated,
isDownload: isDownload
)
if case let .cancelAndOffer(url) = verdict {
onExternalNavigation(["url": url])
}
if verdict == .allow && isMainFrame {
// Spend before handing back the decision so another main-frame action cannot reuse the allowance.
loadState.shellLoadConsumed()
}
decisionHandler(verdict == .allow ? .allow : .cancel)
}
func webView(
_ webView: WKWebView,
decidePolicyFor navigationResponse: WKNavigationResponse,
decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void
) {
// Only srcdoc subframes pass the action policy; refusing one must not fail the shell document.
guard navigationResponse.isForMainFrame else {
let url = navigationResponse.response.url?.absoluteString
decisionHandler(url == MobileWebShellNavigationPolicy.inlineDocumentUrl ? .allow : .cancel)
return
}
let allowed = navigationResponse.canShowMIMEType &&
isDocumentUrl(navigationResponse.response.url)
if !allowed {
reportDocumentFailure()
}
decisionHandler(allowed ? .allow : .cancel)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
// Clear replies and acceptance when the document is replaced; its successor must commit and send ready.
clearBridgeTarget()
loadState.documentEnded()
guard appliedSessionId != nil else { return }
emit(loadState.started())
}
/// Arm at commit, before document-start messages and didFinish.
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
guard isDocumentUrl(webView.url) else { return }
// Commit rearms acceptance, so clear the replaced frame here as well as at provisional start.
clearBridgeTarget()
loadState.committed()
}
/// history.replaceState changes the path before finish; finished() uses commit state instead of URL equality.
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
MobileWebShellWarmUp.release()
emit(loadState.finished())
}
func webView(
_ webView: WKWebView,
didFailProvisionalNavigation navigation: WKNavigation!,
withError error: Error
) {
MobileWebShellWarmUp.release()
reportNavigationFailure(error)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
MobileWebShellWarmUp.release()
reportNavigationFailure(error)
}
/// Report renderer death; memory pressure/provider updates look alike, so the caller owns retry policy.
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
MobileWebShellWarmUp.release()
clearBridgeTarget()
// Jetsam takes WebContent while Orca is backgrounded; the report can arrive as the app resumes, before it is active.
let background = window == nil || UIApplication.shared.applicationState != .active
emit(loadState.failed(.renderProcessGone, background: background))
}
func webView(
_ webView: WKWebView,
createWebViewWith configuration: WKWebViewConfiguration,
for navigationAction: WKNavigationAction,
windowFeatures: WKWindowFeatures
) -> WKWebView? {
nil
func documentExternalNavigation(_ url: String) {
onExternalNavigation(["url": url])
}
}
@@ -1,12 +1,53 @@
import ExpoModulesCore
import QuickLook
import UIKit
public class OrcaMobileWebShellModule: Module {
private var pdfPreview: MobileWebShellPdfPreview?
private var memoryWarningObserver: NSObjectProtocol?
public func definition() -> ModuleDefinition {
Name("OrcaMobileWebShell")
// A spare is the first thing to give back: nothing is shown by it.
OnCreate {
memoryWarningObserver = NotificationCenter.default.addObserver(
forName: UIApplication.didReceiveMemoryWarningNotification,
object: nil,
queue: .main
) { _ in
MobileWebShellSparePool.shared.discardAll()
}
}
OnDestroy {
if let memoryWarningObserver {
NotificationCenter.default.removeObserver(memoryWarningObserver)
}
DispatchQueue.main.async {
MobileWebShellSparePool.shared.discardAll()
}
}
// Home boots the next one after its next foreground idle.
OnAppEntersBackground {
DispatchQueue.main.async {
MobileWebShellSparePool.shared.discardAll()
}
}
AsyncFunction("prepareSpareDocument") { (directory: String, sessionId: String) -> Bool in
MobileWebShellSparePool.shared.prepare(directory: directory, sessionId: sessionId)
}.runOnQueue(.main)
AsyncFunction("claimSpareDocument") { (directory: String) -> String? in
MobileWebShellSparePool.shared.claim(directory: directory)
}.runOnQueue(.main)
AsyncFunction("discardSpareDocument") {
MobileWebShellSparePool.shared.discardAll()
}.runOnQueue(.main)
// Home calls this once it has a paired host, so a user with nothing to open pays nothing.
Function("warmUp") {
// A second's delay keeps the warm-up off the launch's first frames.
@@ -0,0 +1,27 @@
import { requireOptionalNativeModule } from 'expo-modules-core'
type SpareDocumentModule = {
prepareSpareDocument?: (directory: string, sessionId: string) => Promise<boolean>
claimSpareDocument?: (directory: string) => Promise<string | null>
discardSpareDocument?: () => Promise<void>
}
// A binary built before the spare existed has the module without these functions.
const spareModule = (): SpareDocumentModule | null =>
requireOptionalNativeModule<SpareDocumentModule>('OrcaMobileWebShell')
// Boot a page from `directory` under `sessionId` and park it, invisible, until a screen claims it.
// False when native declined: a phone under 4 GB, the app not active, or a page document shown.
export async function prepareSpareDocument(directory: string, sessionId: string): Promise<boolean> {
return (await spareModule()?.prepareSpareDocument?.(directory, sessionId)) ?? false
}
// The parked spare's session id when it was booted from `directory`, handed out once. The view
// mounted under that id adopts the booted page.
export async function claimSpareDocument(directory: string): Promise<string | null> {
return (await spareModule()?.claimSpareDocument?.(directory)) ?? null
}
export async function discardSpareDocument(): Promise<void> {
await spareModule()?.discardSpareDocument?.()
}
@@ -35,17 +35,6 @@
"ordinal": 9,
"json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"ssh.listTargetSummaries\"}"
},
"18c2b8e092d7": {
"name": "streams-registered-at-teardown",
"ordinal": 26,
"value": [
{
"cancelled": true,
"method": "runtime.clientEvents.subscribe",
"payload": "runtime.clientEvents.subscribe#1"
}
]
},
"20200b8feac4": {
"name": "host.platform#1",
"ordinal": 6,
@@ -106,6 +95,17 @@
"startedAt": 0
}
},
"44eb39507b75": {
"name": "streams-registered-at-teardown",
"ordinal": 23,
"value": [
{
"cancelled": true,
"method": "runtime.clientEvents.subscribe",
"payload": "runtime.clientEvents.subscribe#1"
}
]
},
"564f54c8d902": {
"name": "host.platform#1",
"ordinal": 6,
@@ -137,11 +137,6 @@
"ordinal": 13,
"value": [["ssh:ssh-1", "SSH"]]
},
"59ab92fbdbc0": {
"name": "hostPlatform",
"ordinal": 25,
"value": "linux"
},
"6770aa1912e4": {
"name": "repo.list#2",
"ordinal": 15,
@@ -411,11 +406,6 @@
"status": "pending",
"startedAt": 0
},
"9c290301a4bc": {
"name": "hostHealthById",
"ordinal": 23,
"value": []
},
"b2746491ac07": {
"name": "repo.list#1",
"ordinal": 2,
@@ -642,11 +632,6 @@
"name": "hostPlatform",
"ordinal": 14,
"value": "linux"
},
"fb797b9761e1": {
"name": "hostLabelById",
"ordinal": 24,
"value": [["ssh:ssh-1", "SSH"]]
}
},
"recording": {
@@ -795,10 +780,7 @@
"8cfdd18c5fe6",
"84c1dde54c62",
"56ab81cb67dc",
"f9193cae5824",
"9c290301a4bc",
"fb797b9761e1",
"59ab92fbdbc0"
"f9193cae5824"
]
}
},
@@ -838,10 +820,7 @@
"84c1dde54c62",
"56ab81cb67dc",
"f9193cae5824",
"9c290301a4bc",
"fb797b9761e1",
"59ab92fbdbc0",
"18c2b8e092d7"
"44eb39507b75"
]
}
}
@@ -14,12 +14,7 @@ const ERROR_LINE = /^(\S.*?)\(\d+,\d+\): error TS\d+:/
// Tests outside the RN program. Checked transfers are the roots of tsconfig.test.node.json and must pass
// that strict program; the rest are legacy runtime-only allowances whose bodies nothing typechecks.
export const TESTS_OUTSIDE_PROGRAM = new Map([
[
'src/components/WorktreeAgentList.runtime-lineage.test.tsx',
'Legacy runtime-only: the test body is not typechecked anywhere; it imports the desktop SQLite assignment projection, which does not check against RN libs, and its implementation sources keep their normal checks'
]
])
export const TESTS_OUTSIDE_PROGRAM = new Map([])
// Normalize tsc’s host separators to POSIX baseline paths or Windows reports every entry stale and added.
const toPosix = (filePath) => filePath.replaceAll('\\', '/')
@@ -59,15 +59,6 @@ describe('the @ts-nocheck guard', () => {
})
describe('checked transfers', () => {
it('accepts an empty checked cohort while retaining legacy runtime allowances', () => {
expect(
checkTransfers(
{ ok: true, expected: [], programTestFiles: [], failures: [], problems: [] },
new Map([['legacy.test.ts', 'Legacy runtime-only: no checked transfer']])
)
).toEqual([])
})
it('rejects a declared checked transfer missing from the configured roots', () => {
expect(
checkTransfers(
@@ -1,253 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ConfirmModal } from '../components/ConfirmModal'
import { MobileAccountsScreen } from './MobileAccountsScreen'
const dependencies = vi.hoisted(() => ({
back: vi.fn(),
loadHosts: vi.fn(),
uuid: vi.fn<() => string>(),
resetRequest: vi.fn(),
selectRequest: vi.fn(),
statusCapabilities: vi.fn(),
subscriptionListeners: new Array<(payload: unknown) => void>()
}))
vi.mock('react-native', () => ({
ActivityIndicator: 'ActivityIndicator',
Animated: { View: 'View' },
AppState: { currentState: 'active', addEventListener: () => ({ remove: () => {} }) },
Platform: { OS: 'ios' },
Pressable: 'Pressable',
RefreshControl: 'RefreshControl',
ScrollView: 'ScrollView',
StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 },
Text: 'Text',
View: 'View'
}))
vi.mock('react-native-safe-area-context', () => ({
SafeAreaView: 'SafeAreaView',
useSafeAreaInsets: () => ({ bottom: 0, left: 0, right: 0, top: 0 })
}))
vi.mock('expo-router', async () => {
const React = await import('react')
return {
useFocusEffect(effect: () => void | (() => void)): void {
React.useEffect(effect, [effect])
},
useLocalSearchParams: () => ({ hostId: 'host-1' })
}
})
// The page's Back: the handoff pops the shell's stack, where expo-router's own `back()` goes nowhere.
vi.mock('../navigation/route-handoff', () => ({
useRouteHandoff: () => ({ back: dependencies.back })
}))
// The dialogs are read off `ConfirmModal`'s props; the drawer under them needs a native runtime.
vi.mock('../components/bottom-drawer/BottomDrawer', () => ({ BottomDrawer: () => null }))
vi.mock('../platform/random-v4-uuid', () => ({ randomV4Uuid: dependencies.uuid }))
vi.mock('lucide-react-native', () => ({
Check: 'Check',
ChevronLeft: 'ChevronLeft',
RefreshCw: 'RefreshCw',
RotateCcw: 'RotateCcw',
User: 'User'
}))
vi.mock('../transport/hosts/host-store', () => ({
loadHosts: dependencies.loadHosts,
peekHosts: () => null
}))
vi.mock('../transport/connection/host-client-hooks', () => {
const client = {
sendRequest: async (method: string, params?: unknown, options?: unknown) => {
if (method === 'status.get') {
return {
id: 'status',
ok: true,
result: { capabilities: dependencies.statusCapabilities() },
_meta: { runtimeId: 'runtime-1' }
}
}
if (method === 'accounts.consumeCodexResetCredit') {
return dependencies.resetRequest(params, options)
}
if (
method === 'accounts.selectCodex' ||
method === 'accounts.selectCodexForTarget' ||
method === 'accounts.selectClaude'
) {
return dependencies.selectRequest(method, params)
}
if (method === 'accounts.list') {
return { id: 'list', ok: true, result: AVAILABLE_SNAPSHOT }
}
throw new Error(`Unexpected request: ${method}`)
},
subscribe: (_method: string, _params: unknown, onData: (payload: unknown) => void) => {
dependencies.subscriptionListeners.push(onData)
onData({ type: 'ready', snapshot: AVAILABLE_SNAPSHOT })
return vi.fn()
}
}
return {
useForceReconnect: () => null,
useHostClient: () => ({ client, state: 'connected' })
}
})
vi.mock('../components/AgentIcons', () => ({
ClaudeIcon: 'ClaudeIcon',
OpenAIIcon: 'OpenAIIcon'
}))
const AVAILABLE_SNAPSHOT = {
claude: { accounts: [], activeAccountId: null },
codex: {
accounts: [
{
id: 'codex-1',
email: 'dev@example.com',
managedHomeRuntime: 'host',
wslDistro: null,
updatedAt: 10
}
],
activeAccountId: 'codex-1',
activeAccountIdsByRuntime: { host: 'codex-1', wsl: {} }
},
rateLimits: {
claude: null,
codex: {
provider: 'codex',
session: {
usedPercent: 100,
windowMinutes: 300,
resetsAt: 2_000_000_000_000,
resetDescription: null
},
weekly: null,
rateLimitResetCredits: { availableCount: 1, nextExpiresAt: null },
updatedAt: 100,
error: null,
status: 'ok'
},
claudeTarget: { runtime: 'host', wslDistro: null },
codexTarget: { runtime: 'host', wslDistro: null },
inactiveClaudeAccounts: [],
inactiveCodexAccounts: []
}
} as const
const RESET_SNAPSHOT = {
...AVAILABLE_SNAPSHOT,
rateLimits: {
...AVAILABLE_SNAPSHOT.rateLimits,
codex: {
...AVAILABLE_SNAPSHOT.rateLimits.codex,
session: { ...AVAILABLE_SNAPSHOT.rateLimits.codex.session, usedPercent: 0 },
rateLimitResetCredits: { availableCount: 0, nextExpiresAt: null },
updatedAt: 101
}
}
} as const
async function renderAccountsRoute(): Promise<ReactTestRenderer> {
let renderer: ReactTestRenderer | null = null
await act(async () => {
renderer = create(createElement(MobileAccountsScreen))
await Promise.resolve()
})
if (!renderer) {
throw new Error('Accounts route did not render')
}
return renderer
}
/** Host components are strings under the mock above, so they are found by what they carry. */
function pressables(renderer: ReactTestRenderer, label: string) {
return renderer.root.findAll(
(node) => String(node.type) === 'Pressable' && node.props.accessibilityLabel === label
)
}
function resetButtons(renderer: ReactTestRenderer) {
return pressables(renderer, 'Use Codex rate-limit reset')
}
async function findResetButton(renderer: ReactTestRenderer) {
await vi.waitFor(() => expect(resetButtons(renderer)).toHaveLength(1))
return resetButtons(renderer)[0]!
}
/** The open dialog, read off `ConfirmModal` the way a user reads the drawer. */
function openDialog(renderer: ReactTestRenderer) {
const open = renderer.root
.findAllByType(ConfirmModal)
.map((node) => node.props)
.filter((props) => props.visible)
if (open.length > 1) {
throw new Error(`expected at most one open dialog, found ${open.length}`)
}
return open[0] ?? null
}
/** Presses the dialog's confirm button, which closes it after its action as `ConfirmContent` does. */
const KEY = '11111111-1111-4111-8111-111111111111'
describe('accounts route Codex reset credit', () => {
beforeEach(() => {
dependencies.loadHosts.mockReset().mockResolvedValue([
{
id: 'host-1',
name: 'Desk',
endpoint: 'ws://127.0.0.1:6768',
deviceToken: 'token',
publicKeyB64: 'public-key',
lastConnected: 1
}
])
dependencies.uuid.mockReset().mockReturnValue(KEY)
dependencies.back.mockReset()
dependencies.statusCapabilities.mockReset().mockReturnValue(['accounts.codex-reset-credit.v1'])
dependencies.resetRequest.mockReset().mockImplementation((params) => ({
id: 'reset',
ok: true,
result: {
outcome: 'reset',
scope: (params as { expectedScope: unknown }).expectedScope,
snapshot: RESET_SNAPSHOT
},
_meta: { runtimeId: 'runtime-1' }
}))
dependencies.selectRequest.mockReset().mockResolvedValue({
id: 'select',
ok: true,
result: AVAILABLE_SNAPSHOT.codex
})
dependencies.subscriptionListeners.length = 0
})
afterEach(() => {
vi.restoreAllMocks()
})
it('sends nothing when the confirmation is cancelled', async () => {
const renderer = await renderAccountsRoute()
const button = await findResetButton(renderer)
await act(async () => button.props.onPress())
act(() => openDialog(renderer)?.onCancel())
expect(openDialog(renderer)).toBeNull()
expect(dependencies.resetRequest).not.toHaveBeenCalled()
act(() => renderer.unmount())
})
})
@@ -1,26 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
deriveMobileAiVaultScopePaths,
mobileAiVaultScanScopeArgs
} from './agent-history-scope-paths'
const worktree = (worktreeId: string, path: string) => ({ worktreeId, path, repoId: 'repo-1' })
describe('mobile AI Vault scope paths', () => {
const active = worktree('w1', '/Users/ada/repo/app')
const siblings = Array.from({ length: 200 }, (_, index) =>
worktree(`w-sib-${index}`, `/Users/ada/repo/app-${index}`)
)
it('caps only the scan hints, so an older host accepts them and Project still shows every sibling', () => {
const scopePaths = deriveMobileAiVaultScopePaths('project', active, [active, ...siblings])
const scan = mobileAiVaultScanScopeArgs('project', scopePaths)
expect(scopePaths).toHaveLength(201)
expect(scan.scopePaths).toHaveLength(64)
// Active worktree is seeded first, so it survives truncation.
expect(scan.scopePaths?.[0]).toBe('/Users/ada/repo/app')
// A capped scope can't answer alone, so the host keeps its recency scan.
expect(scan.scopeOnly).toBeUndefined()
})
})
@@ -84,15 +84,6 @@ describe('app update checker', () => {
expect(h.checker.getSnapshot().checking).toBe(false)
})
it('joins a manual check to one already in flight', async () => {
const h = harness({ stored: { lastCheckedAt: T0 }, replies: [{ kind: 'current' }] })
h.checker.start()
await vi.advanceTimersByTimeAsync(0)
const [first, second] = [h.checker.checkNow(), h.checker.checkNow()]
await expect(Promise.all([first, second])).resolves.toEqual(['up-to-date', 'up-to-date'])
expect(checks(h)).toBe(1)
})
it('keeps the 1 h retry for a manual check that fails while the store is still loading', async () => {
let finishLoad: () => void = () => {}
const h = harness({
@@ -112,15 +103,6 @@ describe('app update checker', () => {
expect(checks(h)).toBe(2)
})
it('applies one load and runs one check across a StrictMode-style double start', async () => {
const h = harness({})
h.checker.start()()
h.checker.start()
await vi.advanceTimersByTimeAsync(0)
expect(h.deps.loadPreferences).toHaveBeenCalledTimes(1)
expect(checks(h)).toBe(1)
})
function deferredReply() {
let answer: (result: AppUpdateCheckResult) => void = () => {}
const reply = new Promise<AppUpdateCheckResult>((resolve) => {
@@ -1,88 +0,0 @@
import { describe, expect, it } from 'vitest'
import { utf8ByteLength } from '../mobile-web-shell/bridge/bridge-caps'
import { clientFrame } from '../mobile-web-shell/bridge-host-test-fakes'
import { harness, ID } from '../mobile-web-shell/bridge-host-test-harness'
import { BrowserScreencastOpcode, type BrowserScreencastFrame } from './browser-screencast-protocol'
import {
binaryEventEnvelopeBytes,
mobileBrowserFrameAreaBudget,
WORST_CASE_JPEG_BYTES_PER_PIXEL
} from './browser-screencast-request.web'
// Use all nine Chromium metadata fields and real epoch/microsecond timestamp; toy integer understates envelope width.
const CDP_METADATA = {
offsetTop: 0,
pageScaleFactor: 1,
deviceWidth: 390,
deviceHeight: 712,
imageWidth: 780,
imageHeight: 1424,
scrollOffsetX: 0,
scrollOffsetY: 2048.5,
timestamp: 1_758_326_400.123456
}
// Deterministic unstructured noise exercises JPEG worst case reproducibly.
function noise(byteLength: number): Uint8Array {
const bytes = new Uint8Array(byteLength)
let state = 0x9e37_79b9
for (let index = 0; index < byteLength; index += 1) {
state = (Math.imul(state, 1_664_525) + 1_013_904_223) >>> 0
bytes[index] = (state >>> 24) & 0xff
}
return bytes
}
function screencastFrame(image: Uint8Array): BrowserScreencastFrame {
return {
opcode: BrowserScreencastOpcode.Frame,
seq: FRAME_SEQ,
format: 'jpeg',
metadata: CDP_METADATA,
image
}
}
// Exercise a noninitial screencast frame counter.
const FRAME_SEQ = 4_096
/** The one frame the shell posted for this image, and what it cost besides the image. */
function postedFrame(image: Uint8Array): { bytes: number; envelope: number; posts: number } {
const bridge = harness({ ready: true })
bridge.host.receive(
clientFrame({
type: 'subscribe',
id: ID,
method: 'browser.screencast',
params: { worktree: 'id:w', page: 'p' },
wantsBinary: true
})
)
const before = bridge.posted.length
// Fail if no binary lane opened; optional chaining would otherwise look like a correctly dropped frame.
const emitBinary = bridge.client.streams[0]?.emitBinary
if (emitBinary === null || emitBinary === undefined) {
throw new Error('the subscribe opened no binary stream')
}
emitBinary(screencastFrame(image))
const json = bridge.posted.at(-1) ?? ''
const posts = bridge.posted.length - before
const event = posts === 0 ? null : bridge.last()
const b64 = event !== null && 'binary' in event ? event.binary.b64 : ''
return { bytes: utf8ByteLength(json), envelope: utf8ByteLength(json) - b64.length, posts }
}
// These synthetic bytes prove base64 arithmetic/drop rules, not JPEG bytes-per-pixel assumption.
describe('a frame at exactly the budgeted area', () => {
/** The image the budget says the mobile view's worst case produces, to the byte. */
const BUDGETED_IMAGE_BYTES = Math.floor(
mobileBrowserFrameAreaBudget() * WORST_CASE_JPEG_BYTES_PER_PIXEL
)
it('is a ceiling: an image past it is dropped by the shell, not sent over the cap', () => {
// Unexpected worst-case overflow must be dropped at shell boundary (C6 ruling 1).
const { posts } = postedFrame(noise(BUDGETED_IMAGE_BYTES + binaryEventEnvelopeBytes()))
expect(posts).toBe(0)
})
})
@@ -1,116 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { BRIDGE_MAX_MESSAGE_BYTES } from '../mobile-web-shell/bridge/bridge-caps'
import { buildMobileBrowserScreencastRequest } from './browser-screencast-request'
import {
base64Characters,
binaryEventEnvelopeBytes,
budgetedMobileViewDeviceScaleFactor,
buildMobileBrowserScreencastRequest as buildOnWeb,
WORST_CASE_JPEG_BYTES_PER_PIXEL
} from './browser-screencast-request.web'
/** A phone's measured browser area, in CSS pixels. */
const PHONE = { width: 390, height: 712 }
/** What the shell would have to post for a frame of this area at the worst case JPEG has. */
function frameMessageBytes(areaPixels: number): number {
const imageBytes = Math.ceil(areaPixels * WORST_CASE_JPEG_BYTES_PER_PIXEL)
return base64Characters(imageBytes) + binaryEventEnvelopeBytes()
}
function mobileFrameArea(
layout: { width: number; height: number },
request: { deviceScaleFactor?: number } | null
): number {
const scale = request?.deviceScaleFactor
if (scale === undefined) {
throw new Error('the request carried no device scale factor')
}
return Math.round(layout.width) * Math.round(layout.height) * scale * scale
}
describe('the mobile-view area budget', () => {
// Native density at same phone size exceeds bridge cap; without web budget shell drops frame.
it('is needed: the native request overflows the frame cap on a phone', () => {
const native = buildMobileBrowserScreencastRequest(PHONE, 2, 'mobile')
expect(native?.deviceScaleFactor).toBe(2)
expect(frameMessageBytes(mobileFrameArea(PHONE, native))).toBeGreaterThan(
BRIDGE_MAX_MESSAGE_BYTES
)
})
it('keeps the worst case frame inside one bridge message', () => {
const budgeted = buildOnWeb(PHONE, 2, 'mobile')
expect(frameMessageBytes(mobileFrameArea(PHONE, budgeted))).toBeLessThanOrEqual(
BRIDGE_MAX_MESSAGE_BYTES
)
})
it('uses the largest hundredth of density whose frame fits the cap', () => {
const scale = budgetedMobileViewDeviceScaleFactor(PHONE)
expect(
frameMessageBytes(mobileFrameArea(PHONE, { deviceScaleFactor: scale + 0.01 }))
).toBeGreaterThan(BRIDGE_MAX_MESSAGE_BYTES)
})
it('leaves web mode byte-identical to the native request', () => {
expect(buildOnWeb(PHONE, 2, 'web')).toEqual(
buildMobileBrowserScreencastRequest(PHONE, 2, 'web')
)
expect(buildOnWeb(PHONE, 2)).toEqual(buildMobileBrowserScreencastRequest(PHONE, 2))
})
it('never asks for more density than native, on a viewport the budget does not bind', () => {
expect(budgetedMobileViewDeviceScaleFactor({ width: 200, height: 200 })).toBe(2)
})
it('stops at one device pixel per CSS pixel on a viewport no scale would fit', () => {
// Never request fewer device pixels than CSS pixels; shell drops frames still too large at density 1.
expect(budgetedMobileViewDeviceScaleFactor({ width: 2000, height: 1400 })).toBe(1)
})
it('answers the native factor when there is no layout to budget against', () => {
expect(budgetedMobileViewDeviceScaleFactor(null)).toBe(2)
expect(buildOnWeb(null, 2, 'mobile')).toBeNull()
expect(buildOnWeb({ width: 0, height: 712 }, 2, 'mobile')).toBeNull()
})
})
it('counts base64 padding for an image that does not fill its last group', () => {
expect(base64Characters(3001)).toBe(4004)
})
describe('web-mode request work', () => {
for (const mode of [undefined, 'web'] as const) {
it(`skips discarded mobile density work in ${mode ?? 'default'} view`, () => {
const layouts = [
{ width: 360, height: 640 },
{ width: 390, height: 712 },
{ width: 402, height: 593 },
{ width: 319.49, height: 239.51 },
{ width: 1200, height: 1200 },
{ width: 2000, height: 1400 }
]
const expected = layouts.map((layout) => buildMobileBrowserScreencastRequest(layout, 2, mode))
const stringify = vi.spyOn(JSON, 'stringify')
const sqrt = vi.spyOn(Math, 'sqrt')
let actual: ReturnType<typeof buildOnWeb>[] = []
let envelopeCalls = 0
let sqrtCalls = 0
try {
actual = layouts.map((layout) => buildOnWeb(layout, 2, mode))
envelopeCalls = stringify.mock.calls.length
sqrtCalls = sqrt.mock.calls.length
} finally {
stringify.mockRestore()
sqrt.mockRestore()
}
expect(actual).toEqual(expected)
expect(envelopeCalls).toBe(0)
expect(sqrtCalls).toBe(0)
})
}
})
@@ -37,7 +37,7 @@ const WIDEST_JSON_DOUBLE_CHARS = 25
const NARROWEST_JSON_DOUBLE_CHARS = 1
// Derive envelope bound from real protocol shape: longest correlation id, MAX_SAFE_INTEGER counters and every metadata field widened to finite-double maximum.
// Budget cannot predict unknown loose metadata or letterboxed web frames; shell drops over-cap frames. browser-screencast-budget-at-the-shell.test.ts reconstructs bound from real encoded/serialized event.
// Budget cannot predict unknown loose metadata or letterboxed web frames; shell drops over-cap frames.
export function binaryEventEnvelopeBytes(): number {
const skeleton = JSON.stringify({
v: BRIDGE_PROTOCOL_VERSION,
-12
View File
@@ -1,12 +0,0 @@
import { describe, expect, it } from 'vitest'
import { normalizeBrowserUrl } from './browser-url'
describe('normalizeBrowserUrl', () => {
it('keeps localhost-style addresses as http URLs', () => {
expect(normalizeBrowserUrl('localhost:3000')).toBe('http://localhost:3000/')
expect(normalizeBrowserUrl('127.0.0.1:6769/web-index.html')).toBe(
'http://127.0.0.1:6769/web-index.html'
)
})
})

Some files were not shown because too many files have changed in this diff Show More