diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index d0b6347805d..0f4a7f0245b 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -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: diff --git a/.github/workflows/performance-contracts.yml b/.github/workflows/performance-contracts.yml index cd3ba1dfa3a..2af8bb94c6f 100644 --- a/.github/workflows/performance-contracts.yml +++ b/.github/workflows/performance-contracts.yml @@ -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' diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index edc22bc6505..578dcdd68d9 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -342,12 +342,6 @@ jobs: if [ "$PREFLIGHT_PHASE_SELECTED" != true ] || [ "$PREFLIGHT_PRIOR_SUCCESS" != true ]; then exit 0; fi node config/scripts/preflight/changed-checks/check-changed-code-quality.mjs "${{ github.event.pull_request.base.sha }}" - - name: Verify locked audit tools - if: needs.code_paths.outputs.static_analysis == 'true' - env: - ORCA_BACKGROUND_LAUNCH: '1' - run: node config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs - - name: Enforce React Doctor on changed lines if: needs.code_paths.outputs.static_analysis == 'true' run: node config/scripts/static-analysis/react-doctor/check-react-doctor-changed.mjs "${{ github.event.pull_request.base.sha }}" @@ -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 \ diff --git a/.github/workflows/zcode-credential-contract.yml b/.github/workflows/zcode-credential-contract.yml index d5374f037c6..83e1d99cca6 100644 --- a/.github/workflows/zcode-credential-contract.yml +++ b/.github/workflows/zcode-credential-contract.yml @@ -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 diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 985459aac85..acf380823b0 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -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", diff --git a/cloud/apps/push/src/durable-push-payload-parse-budget.test.ts b/cloud/apps/push/src/durable-push-payload-parse-budget.test.ts deleted file mode 100644 index 8e8b89443c2..00000000000 --- a/cloud/apps/push/src/durable-push-payload-parse-budget.test.ts +++ /dev/null @@ -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) -}) diff --git a/cloud/apps/push/src/durable-push-store.test.ts b/cloud/apps/push/src/durable-push-store.test.ts index b9331192e0c..d8387793d45 100644 --- a/cloud/apps/push/src/durable-push-store.test.ts +++ b/cloud/apps/push/src/durable-push-store.test.ts @@ -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) diff --git a/cloud/apps/push/src/durable-push-worker.test.ts b/cloud/apps/push/src/durable-push-worker.test.ts index c5a77e32c29..5eb84f35110 100644 --- a/cloud/apps/push/src/durable-push-worker.test.ts +++ b/cloud/apps/push/src/durable-push-worker.test.ts @@ -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)[] = [] @@ -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() - const release = Promise.withResolvers() - 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) -}) diff --git a/cloud/apps/push/src/host-challenge-store.test.ts b/cloud/apps/push/src/host-challenge-store.test.ts index 62dd815f52e..f73a4f53ea8 100644 --- a/cloud/apps/push/src/host-challenge-store.test.ts +++ b/cloud/apps/push/src/host-challenge-store.test.ts @@ -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() - }) - }) diff --git a/config/audit-tools/README.md b/config/audit-tools/README.md index 7ae8738106c..9c060fa55a2 100644 --- a/config/audit-tools/README.md +++ b/config/audit-tools/README.md @@ -13,4 +13,3 @@ To update a tool, change its exact version in this package's manifest, run `pnpm --dir config/audit-tools install --ignore-scripts`, and review both the manifest and generated lockfile. The workspace enforces a three-day release delay and disables install scripts. Keep its package-manager pin aligned with the root. -Run `node config/scripts/verify-locked-audit-tools.mjs` to exercise both tools. diff --git a/config/build-plugins/cli-main-entry-names.ts b/config/build-plugins/cli-main-entry-names.ts index 92a872d7a51..56905221b8e 100644 --- a/config/build-plugins/cli-main-entry-names.ts +++ b/config/build-plugins/cli-main-entry-names.ts @@ -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', diff --git a/config/build-plugins/main-build-entry-points.ts b/config/build-plugins/main-build-entry-points.ts index de85496fb88..1521adc3dc3 100644 --- a/config/build-plugins/main-build-entry-points.ts +++ b/config/build-plugins/main-build-entry-points.ts @@ -20,6 +20,7 @@ export const MAIN_BUILD_ENTRY_POINTS: Record = { ), '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' ), diff --git a/config/build-plugins/plain-node-entry-guard.ts b/config/build-plugins/plain-node-entry-guard.ts index 69f7c8114c1..1a031934482 100644 --- a/config/build-plugins/plain-node-entry-guard.ts +++ b/config/build-plugins/plain-node-entry-guard.ts @@ -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 diff --git a/config/build-plugins/react-compiler.ts b/config/build-plugins/react-compiler.ts new file mode 100644 index 00000000000..fcdb314daa8 --- /dev/null +++ b/config/build-plugins/react-compiler.ts @@ -0,0 +1,47 @@ +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import type { Options } from '@vitejs/plugin-react' + +// Hand-kept list plus every file still in a hazard ratchet; compiled, these would run differently. +const UNCOMPILED_FILE_LISTS = [ + 'config/react-compiler-uncompiled-files.txt', + 'config/render-path-translate-baseline.txt', + 'config/react-compiler-hazard-baseline.txt' +] + +function listedFiles(list: string): string[] { + return readFileSync(resolve(list), 'utf8') + .split('\n') + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith('#')) + .map((line) => line.replace(/^\d+\s+/, '').split('#')[0]) +} + +export function reactCompilerExcludedFiles(): string[] { + return [...new Set(UNCOMPILED_FILE_LISTS.flatMap(listedFiles))] +} + +export function isReactCompilerEnabled(): boolean { + return process.env.ORCA_REACT_COMPILER !== '0' +} + +export const REACT_COMPILER_OPTIONS = { target: '19' } as const + +function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +export function reactCompilerExcludePattern(): RegExp { + return new RegExp(`/(?:${reactCompilerExcludedFiles().map(escapeRegExp).join('|')})$`) +} + +// ORCA_REACT_COMPILER=0 builds without the compiler for bisecting. +export function reactPluginOptions(): Options { + if (!isReactCompilerEnabled()) { + return {} + } + return { + compiler: REACT_COMPILER_OPTIONS, + exclude: [/\/node_modules\//, reactCompilerExcludePattern()] + } +} diff --git a/config/build-plugins/vitest-compiler-runtime-fallback.ts b/config/build-plugins/vitest-compiler-runtime-fallback.ts new file mode 100644 index 00000000000..9c917969fb6 --- /dev/null +++ b/config/build-plugins/vitest-compiler-runtime-fallback.ts @@ -0,0 +1,25 @@ +import { createRequire } from 'node:module' + +// Why: hook-harness tests mock React or call hooks outside render; there, run uncached like uncompiled code. +const require = createRequire(import.meta.url) +const react: { + __CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE: { H: unknown } +} = require('react') +const internals = react.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE +const runtime: { c: (size: number) => unknown[] } = require('react/compiler-runtime') +const sentinel = Symbol.for('react.memo_cache_sentinel') +const uncached = (size: number): unknown[] => Array.from({ length: size }, () => sentinel) + +export function c(size: number): unknown[] { + if (!internals.H) { + return uncached(size) + } + try { + return runtime.c(size) + } catch (error) { + if (error instanceof Error && error.message.startsWith('Invalid hook call')) { + return uncached(size) + } + throw error + } +} diff --git a/config/build-plugins/vitest-react-compiler.ts b/config/build-plugins/vitest-react-compiler.ts new file mode 100644 index 00000000000..1b3a180f43a --- /dev/null +++ b/config/build-plugins/vitest-react-compiler.ts @@ -0,0 +1,66 @@ +import { resolve } from 'node:path' +import { normalizePath, type Plugin } from 'vite' +import { + REACT_COMPILER_OPTIONS, + isReactCompilerEnabled, + reactCompilerExcludePattern +} from './react-compiler' + +const rendererSource = /\/src\/renderer\/src\/.*\.tsx?$/ +// Only shipped code is compiled; tests, fixtures, mocks and harnesses run as written. +const testSupport = + /\/__(?:mocks|fixtures|tests)__\/|\.(?:test|spec|bench)\.tsx?$|[.-]test-|[.-]fixtures?\.tsx?$/ +const importsVitest = /\bfrom ['"]vitest['"]/ +const runtimeFallback = normalizePath( + resolve(import.meta.dirname, 'vitest-compiler-runtime-fallback.ts') +) + +// Why: @vitejs/plugin-react skips the compiler for vitest's server consumer, so call it directly. +export function vitestReactCompiler(): Plugin[] { + if (!isReactCompilerEnabled()) { + return [] + } + const excluded = reactCompilerExcludePattern() + return [ + { + name: 'vitest-react-compiler', + enforce: 'pre', + configureVitest({ defineCacheKeyGenerator }) { + // Ratchet baselines move files in and out of compilation without touching their source. + defineCacheKeyGenerator(({ id }) => + excluded.test(normalizePath(id.split('?')[0])) ? 'react-compiler:excluded' : '' + ) + }, + async transform(source, id) { + const filename = normalizePath(id.split('?')[0]) + if ( + !rendererSource.test(filename) || + testSupport.test(filename) || + excluded.test(filename) || + importsVitest.test(source) + ) { + return null + } + const { transform } = await import('oxc-transform-react') + const result = await transform(filename, source, { + jsx: { runtime: 'automatic', development: true }, + reactCompiler: REACT_COMPILER_OPTIONS, + sourcemap: true + }) + const diagnostics = result.errors.map( + (e) => `${e.message}${e.codeframe ? `\n${e.codeframe}` : ''}` + ) + if (result.fatal) { + this.error(diagnostics.join('\n\n') || `React Compiler transform failed: ${filename}`) + } + return { + code: result.code.replace( + /from ["']react\/compiler-runtime["']/, + `from ${JSON.stringify(runtimeFallback)}` + ), + map: result.map + } + } + } + ] +} diff --git a/config/build-plugins/worker-thread-entry-names.ts b/config/build-plugins/worker-thread-entry-names.ts new file mode 100644 index 00000000000..3f72cea6df2 --- /dev/null +++ b/config/build-plugins/worker-thread-entry-names.ts @@ -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 diff --git a/config/electron-builder.config.cjs b/config/electron-builder.config.cjs index 45e04fdcd0a..face51a2e73 100644 --- a/config/electron-builder.config.cjs +++ b/config/electron-builder.config.cjs @@ -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/**', diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index b0f4d7fe4d4..f6bcf6ca71e 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -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 diff --git a/config/focus-setting-read-baseline.txt b/config/focus-setting-read-baseline.txt index 1e553776daa..9e6d01f833d 100644 --- a/config/focus-setting-read-baseline.txt +++ b/config/focus-setting-read-baseline.txt @@ -225,7 +225,7 @@ 1 src/renderer/src/lib/default-creation-host.ts # the sanctioned reader of the default host 1 src/renderer/src/lib/launch-ai-vault-session.ts 1 src/renderer/src/lib/local-preflight-context.ts -2 src/renderer/src/lib/provider-runtime-context.ts +2 src/renderer/src/runtime/hosts/observations/provider-runtime-context.ts 2 src/renderer/src/lib/repo-runtime-owner.ts 1 src/renderer/src/lib/runtime-session-mirror-owners.ts 1 src/renderer/src/lib/runtime-session-mirror-targets.ts diff --git a/config/host-list-render-baseline.txt b/config/host-list-render-baseline.txt index b1a39632401..09d3a029300 100644 --- a/config/host-list-render-baseline.txt +++ b/config/host-list-render-baseline.txt @@ -7,7 +7,7 @@ 1 src/renderer/src/components/settings/browser/profiles/BrowserSessionCookiesSection.tsx 1 src/renderer/src/components/settings/browser/routing/BrowserSshWorkspaceRoutingSetting.tsx 1 src/renderer/src/components/settings/quick-commands/QuickCommandsToolbar.tsx -1 src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.tsx +1 src/renderer/src/components/settings/repository/hosts/RepositoryHostSetupsSection.tsx 1 src/renderer/src/components/sidebar/host-admission/ssh/AddRemoteHostSshConfigPicker.tsx 4 src/renderer/src/components/status-bar/SshStatusSegment.tsx 1 src/renderer/src/components/status-bar/resource-usage-popover-body.tsx diff --git a/config/localization-coverage-allowlist.json b/config/localization-coverage-allowlist.json index 18549199187..4222e7a5add 100644 --- a/config/localization-coverage-allowlist.json +++ b/config/localization-coverage-allowlist.json @@ -60,31 +60,45 @@ "kind": "object-property:keywords", "text": "ghostty", "dynamic": false, - "count": 2 + "count": 1 + }, + { + "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts", + "kind": "object-property:keywords", + "text": "ghostty", + "dynamic": false, + "count": 1 }, { "filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts", "kind": "object-property:keywords", "text": "Ghostty", "dynamic": false, - "count": 2 + "count": 1 }, { - "filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts", + "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts", + "kind": "object-property:keywords", + "text": "Ghostty", + "dynamic": false, + "count": 1 + }, + { + "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts", "kind": "object-property:keywords", "text": "Kitty", "dynamic": false, "count": 1 }, { - "filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts", + "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts", "kind": "object-property:keywords", "text": "kitty", "dynamic": false, "count": 1 }, { - "filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts", + "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts", "kind": "object-property:keywords", "text": "kitty.conf", "dynamic": false, diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 0eccabfb512..e106b4f0b3b 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -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 diff --git a/config/mobile-ci.vitest.config.mjs b/config/mobile-ci.vitest.config.mjs index 23b80145a37..61ddb17f32e 100644 --- a/config/mobile-ci.vitest.config.mjs +++ b/config/mobile-ci.vitest.config.mjs @@ -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', diff --git a/config/path-literal-baseline.txt b/config/path-literal-baseline.txt index a0a0ede85ea..3d31a05c9e5 100644 --- a/config/path-literal-baseline.txt +++ b/config/path-literal-baseline.txt @@ -6,7 +6,6 @@ config/scripts/performance/session-search/session-search-tool-heavy-corpus.ts src/main/ai-vault/session-transcript-reader.ts config/scripts/runtime-verification/desktop-transport/run-linux-lid-sleep-assertion-docker.mjs src/main/linux-lid-sleep-assertion.ts config/scripts/runtime-verification/desktop-transport/run-ssh-staged-upload-reliability.mjs src/main/ssh/ssh-relay-install-namespace.test.ts -config/scripts/session-search-file-id-e2e/run.ts src/main/ai-vault/session-scanner-service-entry.ts config/scripts/static-analysis/ratchets/renderer-state/check-layout-writer-ratchets.mjs src/renderer/src/runtime/remote-workspace-frozen/ config/scripts/workflow/source-routing/pr-code-change-scope.mjs src/main/runtime/runtime-worktree-agent- config/scripts/workflow/source-routing/pr-code-change-scope.mjs src/shared/agent-session-mutation-envelope diff --git a/config/process-host-direct-import-baseline.txt b/config/process-host-direct-import-baseline.txt index 04253a93e8e..85d6225d4a7 100644 --- a/config/process-host-direct-import-baseline.txt +++ b/config/process-host-direct-import-baseline.txt @@ -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 diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt index 933ce4f0a05..c4cd51da520 100644 --- a/config/react-compiler-bailout-baseline.txt +++ b/config/react-compiler-bailout-baseline.txt @@ -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 diff --git a/config/react-compiler-uncompiled-files.txt b/config/react-compiler-uncompiled-files.txt new file mode 100644 index 00000000000..7c7b729df86 --- /dev/null +++ b/config/react-compiler-uncompiled-files.txt @@ -0,0 +1,37 @@ +# Renderer files React Compiler skips; compiled, they would run differently. Hand-maintained. +# Files in config/render-path-translate-baseline.txt and config/react-compiler-hazard-baseline.txt +# are skipped too. Remove a line once its file is safe to compile. + +# Render-time reads of providerRuntimeSessionGeneration (lib/provider-runtime-context.ts; hazard live-read-in-memo-block). +src/renderer/src/components/feature-wall/FeatureWallSetupChecklist.tsx +src/renderer/src/components/feature-wall/use-integration-connection-status.ts +src/renderer/src/components/integrations/task-trackers/jira-integration-card.tsx +src/renderer/src/components/integrations/task-trackers/linear-integration-card.tsx +src/renderer/src/components/new-workspace/use-jira-source-connection.ts +src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts +src/renderer/src/components/settings/skills/linear/LinearAgentSkillPane.tsx +src/renderer/src/components/settings/tasks/use-task-source-provider-readiness.ts +src/renderer/src/components/sidebar/workspace-card/details/use-worktree-card-review-details.ts +src/renderer/src/components/task-page/jira/Content.tsx +src/renderer/src/components/task-page/jira/use-task-page-jira-list-projection.ts +src/renderer/src/components/task-page/jira/use-task-page-jira-list-state.ts +src/renderer/src/hooks/use-integration-provider-status-refresh.ts + +# structuredSessionSelectionAuthority/Controller read module state the selection lifetime replaces (live-read-in-memo-block). +src/renderer/src/components/native-chat/session/options/structured/use-structured-agent-session-option-state.ts + +# applyTerminalColdActivation mutates controller refs during render on the terminal hot path. +src/renderer/src/components/use-terminal-controller.ts + +# Caches keyed on a TanStack virtualizer, which mutates in place (hazard virtualizer-in-memo-block). +src/renderer/src/components/editor/combined-diff/scroll-viewport/combined-diff-section-list.tsx +src/renderer/src/components/editor/markdown-preview/search/use-markdown-preview-search-reveal.ts +src/renderer/src/components/editor/markdown-preview/viewport/use-markdown-preview-scroll-anchor.ts +src/renderer/src/components/github-item-dialog/inspect-pull-request/pr-files-combined-diff-body.tsx +src/renderer/src/components/right-sidebar/file-explorer/panel/FileExplorerVirtualRows.tsx +src/renderer/src/components/right-sidebar/file-explorer/tree/FileExplorerFilesTreePane.tsx +src/renderer/src/components/sidebar/worktree-list/viewport/VirtualizedWorktreeViewport.tsx + +# The workbench subtree relies on the shell re-rendering on every app render. +src/renderer/src/app-shell/AppWorkspaceShell.tsx +src/renderer/src/app-shell/use-app-chrome-layout.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 345522b5723..76de250ab2b 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -4456,7 +4456,6 @@ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx src/shared/document-preview/doc-preview-scheme.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/main/ipc/browser/browser.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/link-actions/LinkActionPopover.test.tsx src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-editor-diff-tabs.test.ts", @@ -4884,6 +4883,7 @@ "Collect 100 consecutive focused CI passes or 14 days without an unexplained flake." ], "knownGaps": [ + "Audit2643 deletes the seven fake-manager browser IPC cases: renderer-owned registration repair, untrusted download cancellation refusal, exact certificate approval, cancelled pending grab enablement, in-flight grab serialization, stale guest registration waits, and annotation ownership refusal. These alarms are intentionally lost without replacement; dated evidence retains its original scope and no fresh gate execution is claimed.", "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts. Unresolved local/computed edges remain explicit debt.", "Audit2095 current-parent preparation2126 (approved2092/2093 removals; source refresh2109/independent2112): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts: rejects exact terminal stop for multiple expected PTYs before stopping anything; omits stale renderer leaves when fresh PTY liveness is required; omits unbound renderer placeholders when fresh PTY liveness is required; captures the event method before the nested sleep receipt changes it; returns the close receipt without requiring a PTY stop; uses the same stop result as an empty explicit stop. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts: builds a compact worktree summary from persisted and live runtime state; reads the linked-PR state from the renderer repoId-keyed GitHub cache; carries persisted worktree host ownership in mobile summaries; emits only instance- and boundary-validated lineage parents in mobile summaries; resolves WSL platforms only for repos represented in mobile summaries; omits worktrees hidden by the host visibility policy from mobile summaries; applies linked-checkout source visibility to mobile summaries. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts: routes runtime GitHub PR details and actions through the selected WSL project runtime; passes SSH connection context through hosted review creation flows; routes local WSL project hosted review flows through runtime git options; treats SSH worktree drift as unknown without local git probes. src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts: emits one mobile session terminal tab per live PTY even if two tabs resolve to it; resolves projected split authority from the parent layout PTY binding; keeps explicit-id terminal lists from resolving all worktrees; keeps explicit-id cold-cache terminal lists from classifying unrelated same-repo worktrees; keeps unknown bare terminal-list ids on the no-scan exact-id path; matches explicit-id cwd PTYs for folder workspace instance IDs; routes PTY output through the PTY leaf index in large terminal graphs. src/main/runtime/orca-runtime-tests/window-authority.spec.ts: claims the first window as authoritative and ignores later windows; transfers authority from the headless sentinel to the first real window; relays terminal browser launches only while headless owns the graph; marks live headless PTYs for renderer reattach before desktop promotion; reports the activation gate state while no desktop window is available; bumps the epoch and enters reloading when the authoritative window reloads; can mark the graph ready for the authoritative window; drops back to unavailable and clears authority when the window disappears; hands the graph back to headless when a promoted serve window closes (#27292); keeps a crashed promoted serve renderer on its own window while the window is open; stays unavailable during initial loads before a graph is published. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts, src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts, src/main/runtime/orca-runtime-tests/window-authority.spec.ts. Unresolved local/computed edges remain explicit debt.", @@ -7676,7 +7676,7 @@ "oracle": "Audit2371 reduces all-host-folder-workspace-catalogs.test.ts by removing the repeated offline compatibility-probe budget and its incidental local-fallback/restored-owner samples, and catalog-settlement-notifications.test.ts by removing the four-route ten-equal-refresh notification/reference matrix. Those probe, quietness, identity and fallback alarms are intentionally lost. Remaining stale-response and revision-fencing examples do not supply equivalent replacement coverage. No fresh execution or red/green evidence validates the reduced sources; the four unrelated physical selected-runtime E2E receipts retain their original commands and scope. Historical prior account (preserved verbatim): Audit2360 removes src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts and its exclusive fake-effect harness. Lose local default-runtime persistence across navigation; focused/background terminal request/create/reveal and no-focus recovery; startup cwd/config/agent/view-mode forwarding; explicit runtime-session routing; remote/ambiguous/missing owner refusal; history focus; existing PTY reuse/title preservation; pending tab PTY/layout/identity adoption; split tree, focus, identity and telemetry samples. No equivalent replacement claimed. Changed selectors have no fresh execution or red/green credit. Unrelated retained receipt objects keep their original narrow scope. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/store/project-groups/nested-repository-operations.test.ts: routes local nested scan progress by scanId and unsubscribes after completion. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Start with Active Server=Local desktop, connect and navigate Windows 2, then reveal a local terminal and assert it succeeds while the persisted preference remains local before and after restart. Repeat transient routing and selected-runtime Add Project operations with exact-ID host decoys and completion reordering. Separately pair the real web client to an isolated headed host, then make its sole still-listed runtime compatibility-blocked and unavailable. Require a null authoritative selection, a disabled host option, and disabled Browse, Clone, and Create actions with no local fallback. Repeat against headless serve. Run the byte-identical selector/action contract on latest main, candidate, and candidate with the eligibility seam disabled.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts src/renderer/src/store/slices/settings/settings.test.ts src/renderer/src/store/slices/browser/hosts/browser-session-host-selection.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts --maxWorkers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/all-host-folder-workspace-catalogs.test.ts src/renderer/src/store/host-catalog/catalog-settlement-notifications.test.ts src/renderer/src/store/repos/repos-stale-fetch.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-routing.test.ts src/renderer/src/store/repos/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/worktrees/session/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-owner-routing.test.ts --maxWorkers=1", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/all-host-folder-workspace-catalogs.test.ts src/renderer/src/store/host-catalog/catalog-settlement-notifications.test.ts src/renderer/src/store/repos/repos-stale-fetch.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-routing.test.ts src/renderer/src/store/repos/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/worktrees/session/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-owner-routing.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/project-admission/dialog/AddRepoStartSteps.test.tsx --maxWorkers=1", "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" @@ -7689,7 +7689,6 @@ "src/renderer/src/web/web-preload-api-runtime-environment.test.ts", "src/renderer/src/components/sidebar/project-admission/dialog/AddRepoStartSteps.test.tsx", "src/renderer/src/lib/resolved-worktree-execution-host.test.ts", - "src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts", "src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts", "src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts", "src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts", @@ -7809,6 +7808,8 @@ "Run the paired Add Project journey on Linux and native Windows, plus live SSH and WSL hosts." ], "knownGaps": [ + "Audit2680: Delete the whole supplied-state worktree-runtime-owner suite. Lose immutable collection-reference invalidation and per-worktree override/folder inheritance lookup alarms without replacement. Remove its prospective selector and file membership; unchanged independent Electron evidenceRuns remain historical and do not validate the reduced selector. No fresh execution or equivalent replacement is claimed.", + "Audit2680 historical original selector metadata, preserved verbatim; not current evidence: {\"command\":\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/all-host-folder-workspace-catalogs.test.ts src/renderer/src/store/host-catalog/catalog-settlement-notifications.test.ts src/renderer/src/store/repos/repos-stale-fetch.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-routing.test.ts src/renderer/src/store/repos/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/worktrees/session/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-owner-routing.test.ts --maxWorkers=1\",\"testFiles\":\"src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts\"}", "Audit2360 removes src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts and its exclusive fake-effect harness. Lose local default-runtime persistence across navigation; focused/background terminal request/create/reveal and no-focus recovery; startup cwd/config/agent/view-mode forwarding; explicit runtime-session routing; remote/ambiguous/missing owner refusal; history focus; existing PTY reuse/title preservation; pending tab PTY/layout/identity adoption; split tree, focus, identity and telemetry samples. No equivalent replacement claimed. Changed selectors have no fresh execution or red/green credit. Unrelated retained receipt objects keep their original narrow scope. Retired assertion reference verbatim: {\n \"file\": \"src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts\",\n \"assertions\": [\n \"Local desktop remains the durable default after transient Windows 2 navigation and a focused local terminal reveal succeeds\",\n \"local and remote terminal create route by target workspace ownership instead of the durable preference\"\n ]\n }", "Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "The exact journey is deterministic contract coverage, not a packaged Windows UI automation run.", @@ -11424,7 +11425,7 @@ "id": "terminal-render.foreground-repair-span", "title": "A forced foreground repaint covers every row the write changed", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-rendering", "layer": "renderer-unit", "surfaces": [ @@ -11437,39 +11438,20 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "remote-runtime"], - "coveredPlatforms": ["macos"], + "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Audit2236: retire the21-profile real-parser row-change corpus and bottom-row narrowing bound. Retain one controlled hardcoded dirty-span case proving pre/post cursor inclusion. No retained case proves real-parser changed-row convergence, viewport-scroll/alternate-screen full-grid fallback, work bounds or pixel behavior. Historical dated parser/CDP/red-green/performance evidence remains verbatim history and does not validate reduced source bytes; no equivalent replacement or fresh evidence is claimed. Historical prior account (preserved verbatim): Renderer-unit convergence corpus over a real xterm parser, plus manual CDP pixel evidence on the macOS WebGL renderer. The repaint span is provider-independent because it is computed from xterm's parse, not from the transport; SSH/WSL/remote were not exercised live. The audit removes isolated unobservable-span fallback and follow-up full-grid repaint examples. The retained real-parser corpus checks observed row changes and cursor spans; it does not establish those removed fallback alarms.", + "coverageNotes": "Audit2615: all retained source alarms retired. No retained source coverage or current source oracle remains for this gate. Prior notes and dated evidence are historical only; no equivalent replacement or fresh evidence is claimed. Audit2236: retire the21-profile real-parser row-change corpus and bottom-row narrowing bound. Retain one controlled hardcoded dirty-span case proving pre/post cursor inclusion. No retained case proves real-parser changed-row convergence, viewport-scroll/alternate-screen full-grid fallback, work bounds or pixel behavior. Historical dated parser/CDP/red-green/performance evidence remains verbatim history and does not validate reduced source bytes; no equivalent replacement or fresh evidence is claimed. Historical prior account (preserved verbatim): Renderer-unit convergence corpus over a real xterm parser, plus manual CDP pixel evidence on the macOS WebGL renderer. The repaint span is provider-independent because it is computed from xterm's parse, not from the transport; SSH/WSL/remote were not exercised live. The audit removes isolated unobservable-span fallback and follow-up full-grid repaint examples. The retained real-parser corpus checks observed row changes and cursor spans; it does not establish those removed fallback alarms.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/2669", "https://github.com/stablyai/orca/pull/4669", "https://github.com/stablyai/orca/pull/8178" ], "invariant": "The row span Orca asks xterm to repaint after a forced foreground refresh must cover every viewport row whose rendered content changed during that write, plus the cursor row before and after it; when the span cannot be established — unobservable parse, viewport scroll, or a normal/alternate buffer flip — the whole viewport must be repainted.", - "oracle": "Audit2236: retire the21-profile real-parser row-change corpus and bottom-row narrowing bound. Retain one controlled hardcoded dirty-span case proving pre/post cursor inclusion. No retained case proves real-parser changed-row convergence, viewport-scroll/alternate-screen full-grid fallback, work bounds or pixel behavior. Historical dated parser/CDP/red-green/performance evidence remains verbatim history and does not validate reduced source bytes; no equivalent replacement or fresh evidence is claimed. Historical prior account (preserved verbatim): A real @xterm/headless parser replays an adversarial corpus (in-place bottom-row redraws, standalone CR overwrite, backspace, erase-in-line, erase-in-display above and below the cursor, full clear, wide CJK, emoji, combining marks, ZWJ sequences, scroll-region insert/delete, reverse index, DEC 2026 frames, alternate-screen enter and exit, viewport scroll, narrow panes). Each viewport row is serialized cell-by-cell with its attributes before and after the write, and every row that differs must fall inside the span the settle path requested. A vacuity guard asserts each case actually moves the screen.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/pane-manager/terminal-foreground-repair-convergence.test.ts" - ], - "testFiles": [ - "src/renderer/src/lib/pane-manager/terminal-foreground-repair-convergence.test.ts" - ], - "assertionRefs": [ - { - "file": "src/renderer/src/lib/pane-manager/terminal-foreground-repair-convergence.test.ts", - "assertions": ["widens the repair to the cursor rows on both sides of the write"] - } - ], - "evidenceRuns": [ - { - "date": "2026-09-02", - "runner": "local", - "platform": "macos", - "result": "passed", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/pane-manager/terminal-foreground-repair-convergence.test.ts", - "durationSeconds": 1, - "summary": "25 cases passed against a real xterm parser; paired CDP run on a 4-pane macOS WebGL dev build produced screenshots byte-identical to a forced full model rebuild." - } - ], + "oracle": "Audit2615: all retained source alarms retired. No retained source coverage or current source oracle remains for this gate. Prior notes and dated evidence are historical only; no equivalent replacement or fresh evidence is claimed. Audit2236: retire the21-profile real-parser row-change corpus and bottom-row narrowing bound. Retain one controlled hardcoded dirty-span case proving pre/post cursor inclusion. No retained case proves real-parser changed-row convergence, viewport-scroll/alternate-screen full-grid fallback, work bounds or pixel behavior. Historical dated parser/CDP/red-green/performance evidence remains verbatim history and does not validate reduced source bytes; no equivalent replacement or fresh evidence is claimed. Historical prior account (preserved verbatim): A real @xterm/headless parser replays an adversarial corpus (in-place bottom-row redraws, standalone CR overwrite, backspace, erase-in-line, erase-in-display above and below the cursor, full clear, wide CJK, emoji, combining marks, ZWJ sequences, scroll-region insert/delete, reverse index, DEC 2026 frames, alternate-screen enter and exit, viewport scroll, narrow panes). Each viewport row is serialized cell-by-cell with its attributes before and after the write, and every row that differs must fall inside the span the settle path requested. A vacuity guard asserts each case actually moves the screen.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 15, "scope": "Renderer-unit convergence corpus" @@ -11492,11 +11474,13 @@ "Keep a full-grid fallback assertion for every new span-narrowing condition." ], "knownGaps": [ + "Audit2615: all retained source alarms retired. No retained source coverage or current source oracle remains for this gate. Prior notes and dated evidence are historical only; no equivalent replacement or fresh evidence is claimed.", "Audit2236: retire the21-profile real-parser row-change corpus and bottom-row narrowing bound. Retain one controlled hardcoded dirty-span case proving pre/post cursor inclusion. No retained case proves real-parser changed-row convergence, viewport-scroll/alternate-screen full-grid fallback, work bounds or pixel behavior. Historical dated parser/CDP/red-green/performance evidence remains verbatim history and does not validate reduced source bytes; no equivalent replacement or fresh evidence is claimed.", "No CI-wired pixel oracle; WebGL convergence evidence was collected manually over CDP.", "Windows ConPTY synchronous repair has no retained parser-corpus or Windows-runner coverage after the corpus retirement.", "SSH/WSL/remote providers were not exercised live; the span is transport-independent by construction.", - "The audit removes isolated unobservable-span fallback and follow-up full-grid repaint examples, and retires the real-parser corpus. The surviving controlled cursor-span case does not establish those fallback alarms or real-parser convergence." + "The audit removes isolated unobservable-span fallback and follow-up full-grid repaint examples, and retires the real-parser corpus. The surviving controlled cursor-span case does not establish those fallback alarms or real-parser convergence.", + "Audit2615 historical evidenceRuns only; no current protection. Original JSON verbatim:\n[\n {\n \"date\": \"2026-09-02\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"result\": \"passed\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/pane-manager/terminal-foreground-repair-convergence.test.ts\",\n \"durationSeconds\": 1,\n \"summary\": \"25 cases passed against a real xterm parser; paired CDP run on a 4-pane macOS WebGL dev build produced screenshots byte-identical to a forced full model rebuild.\"\n }\n ]" ], "demotionRule": "Demote or block if a narrowing condition is added without a matching convergence case, if the corpus stops asserting that each case changes at least one row, or if a repaint regression is reported for in-place agent redraws." }, diff --git a/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs b/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs index 7d97c713144..a1d27b2dbec 100644 --- a/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs +++ b/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs @@ -5,11 +5,7 @@ import { withScratch, copyWrittenBundle } from '../../mobile-web-app/mobile-web-app-bundle-test-fixture.mjs' -import { - bundleMobileWebApp, - renameOutputsByContent, - routeChunkNames -} from './build-mobile-web-app-bundle.mjs' +import { bundleMobileWebApp } from './build-mobile-web-app-bundle.mjs' import { MOBILE_WEB_APP_ROUTE_ROOT } from '../../mobile-web-app/mobile-web-app-route-manifest.mjs' import { verifyMobileWebAppBundle } from './verify-mobile-web-app-bundle.mjs' import { @@ -141,33 +137,3 @@ describe('the verifier', () => { 240_000 ) }) - -describe('naming an output by its bytes', () => { - it('refuses two outputs that name each other', () => { - const emitted = (text) => new TextEncoder().encode(text) - const metafile = { - outputs: { - 'dist/a.js': { imports: [{ path: 'dist/b.js', kind: 'import-statement' }] }, - 'dist/b.js': { imports: [{ path: 'dist/a.js', kind: 'import-statement' }] } - } - } - // Cycles have no final dependency names/content hash; fail if esbuild ever stops emitting a DAG. - expect(() => - renameOutputsByContent(metafile, [ - { path: 'dist/a.js', contents: emitted('import "/assets/b.js"') }, - { path: 'dist/b.js', contents: emitted('import "/assets/a.js"') } - ]) - ).toThrow(/output cycle/) - }) - - it('refuses a route it cannot find an output for', async () => { - await withScratch(async (scratch) => { - const module = join(scratch, 'index.tsx') - await writeFile(module, 'export default function Route() { return null }\n') - // Only metafile maps routes to chunks; missing output must fail before phones request undefined/404. - expect(() => - routeChunkNames({ outputs: {} }, [{ key: './index.tsx', module }], new Map()) - ).toThrow(/\.\/index\.tsx reached no output/) - }) - }) -}) diff --git a/config/scripts/build/mobile-web-app/mobile-web-bundle-manifest.test.mjs b/config/scripts/build/mobile-web-app/mobile-web-bundle-manifest.test.mjs deleted file mode 100644 index e00c3366b52..00000000000 --- a/config/scripts/build/mobile-web-app/mobile-web-bundle-manifest.test.mjs +++ /dev/null @@ -1,50 +0,0 @@ -import { existsSync } from 'node:fs' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { - contentTypeForExtension, - hashedAsset, - sha256Hex, - writeMobileWebBundleTree -} from './mobile-web-bundle-manifest.mjs' - -describe('hashedAsset', () => { - it('refuses an extension with no registered content type', () => { - // Unknown content type must fail rather than leave phone guessing how to serve addressed bytes. - expect(() => hashedAsset(Buffer.from('body'), 'wasm')).toThrow(/no content type registered/) - }) -}) - -describe('writeMobileWebBundleTree', () => { - it('marks a dark build outside the manifest, so its buildId is the same tree’s', async () => { - const outDir = await mkdtemp(join(tmpdir(), 'mobile-web-bundle-manifest-')) - try { - const bytes = Buffer.from('\n', 'utf8') - const tree = (env) => - writeMobileWebBundleTree({ - outDir, - written: [ - { - path: 'index.html', - bytes, - sha256: sha256Hex(bytes), - byteLength: bytes.byteLength, - contentType: contentTypeForExtension('html') - } - ], - desktopVersion: '1.0.0', - protocolWindow: { runtimeProtocolVersion: 3, minCompatibleRuntimeProtocolVersion: 3 }, - env - }) - const dark = await tree({ ORCA_SIDEBAR_INPUTS: 'main' }) - expect(existsSync(join(outDir, 'ORCA_SIDEBAR_INPUTS_MAIN'))).toBe(true) - const off = await tree({}) - expect(existsSync(join(outDir, 'ORCA_SIDEBAR_INPUTS_MAIN'))).toBe(false) - expect(dark.manifest.buildId).toBe(off.manifest.buildId) - } finally { - await rm(outDir, { recursive: true, force: true }) - } - }) -}) diff --git a/config/scripts/build/mobile-web-app/mobile-web-page-routes.test.mjs b/config/scripts/build/mobile-web-app/mobile-web-page-routes.test.mjs deleted file mode 100644 index eb7522f2543..00000000000 --- a/config/scripts/build/mobile-web-app/mobile-web-page-routes.test.mjs +++ /dev/null @@ -1,99 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - MOBILE_WEB_BUNDLE_MAX_ROUTE_GRANTS, - MobileWebBundleRouteSchema -} from '../../../../src/shared/mobile-web-bundle/manifest-contract.ts' -import { resolveMobileWebPageRoutes } from './build-mobile-web-app-bundle.mjs' -import { MOBILE_WEB_PAGE_ROUTES } from './mobile-web-page-routes.mjs' -import { routePathnameFromKey } from '../../mobile-web-app/mobile-web-app-route-manifest.mjs' - -// Test declared screens separately from bundle mechanics so route inventory can grow without coupling builder test size. - -describe('the page routes the manifest declares', () => { - it('turns a route key into the URL pattern expo-router gives it', () => { - expect(routePathnameFromKey('./h/[hostId]/index.tsx')).toBe('/h/[hostId]') - expect(routePathnameFromKey('./h/[hostId]/tasks.tsx')).toBe('/h/[hostId]/tasks') - expect(routePathnameFromKey('./h/[hostId]/session/[worktreeId].tsx')).toBe( - '/h/[hostId]/session/[worktreeId]' - ) - }) - - it('answers null for a layout, which is not a screen anyone navigates to', () => { - expect(routePathnameFromKey('./h/_layout.tsx')).toBeNull() - expect(routePathnameFromKey('./h/[hostId]/_layout.tsx')).toBeNull() - }) - - // Synthetic optional-grant input checks member-by-member mapping; newly declared field must survive builder map before reaching phone. - it('carries an optional grant list through, and writes no key for a route without one', () => { - expect( - resolveMobileWebPageRoutes( - ['./h/[hostId]/index.tsx', './h/[hostId]/tasks.tsx'], - [ - { - pathname: '/h/[hostId]', - grants: ['navigate'], - optionalGrants: ['externalNavigation'] - }, - { pathname: '/h/[hostId]/tasks', grants: ['navigate'], optionalGrants: [] } - ] - ) - ).toEqual([ - { pathname: '/h/[hostId]', grants: ['navigate'], optionalGrants: ['externalNavigation'] }, - { pathname: '/h/[hostId]/tasks', grants: ['navigate'] } - ]) - }) - - it('carries the host-area declaration through, and writes no key where there is none', () => { - expect( - resolveMobileWebPageRoutes( - ['./h/[hostId]/index.tsx', './h/[hostId]/tasks.tsx'], - [ - { pathname: '/h/[hostId]', grants: ['navigate'], canOwnHostArea: true }, - { pathname: '/h/[hostId]/tasks', grants: ['navigate'] } - ] - ) - ).toEqual([ - { pathname: '/h/[hostId]', grants: ['navigate'], canOwnHostArea: true }, - { pathname: '/h/[hostId]/tasks', grants: ['navigate'] } - ]) - }) - - /** - * The wide iPad's host-area session is granted every served route's list, so its in-page hops - * stay in the page. Bounded by what one route can be granted, so that grant never outgrows one route's. - */ - - // The phone refuses the whole manifest over one bad route, which takes every page down. - it('declares only routes the manifest schema accepts', () => { - for (const route of MOBILE_WEB_PAGE_ROUTES) { - expect( - MobileWebBundleRouteSchema.safeParse(route).error?.issues ?? [], - route.pathname - ).toEqual([]) - } - }) - - it('holds the optional lane to the manifest grammar and its own ceiling', () => { - // Released shells read each list against the ceiling on its own, so the writer bounds each the same way. - const withOptional = (optionalGrants, grants = []) => - MobileWebBundleRouteSchema.safeParse({ pathname: '/h/[hostId]', grants, optionalGrants }) - .success - expect(withOptional(['externalNavigation'])).toBe(true) - expect(withOptional(['native.externalNavigation'])).toBe(false) - const names = (count, prefix) => - Array.from({ length: count }, (_value, index) => `${prefix}${String(index)}`) - const cap = MOBILE_WEB_BUNDLE_MAX_ROUTE_GRANTS - expect(withOptional(names(cap, 'opt'), names(cap, 'req'))).toBe(true) - expect(withOptional(names(cap + 1, 'opt'))).toBe(false) - }) - - it('fails the build on a declaration the bundle cannot render', () => { - // Declared-but-unbundled route opens page then paints Unmatched; catch mismatch at declaration. - expect(() => - resolveMobileWebPageRoutes( - ['./h/[hostId]/index.tsx'], - [{ pathname: '/h/[hostId]/gone', grants: [] }] - ) - ).toThrow('has no module in the bundle') - }) -}) diff --git a/config/scripts/build/mobile-web-app/mobile-web-source-line-endings.test.mjs b/config/scripts/build/mobile-web-app/mobile-web-source-line-endings.test.mjs deleted file mode 100644 index e5df4594bb8..00000000000 --- a/config/scripts/build/mobile-web-app/mobile-web-source-line-endings.test.mjs +++ /dev/null @@ -1,19 +0,0 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { assertNoCarriageReturnsInSource } from './mobile-web-source-line-endings.mjs' - -describe('assertNoCarriageReturnsInSource', () => { - it('rejects a CRLF source file, because CRLF changes every asset hash and the buildId', async () => { - const scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-eol-')) - try { - await writeFile(join(scratch, 'route.tsx'), 'const a = 1\r\nconst b = 2\r\n', 'utf8') - await expect(assertNoCarriageReturnsInSource(scratch)).rejects.toThrow( - /CRLF in mobile web source/ - ) - } finally { - await rm(scratch, { recursive: true, force: true }) - } - }) -}) diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 2a25d38facd..da79a66c8cf 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -5190,8 +5190,8 @@ "src/renderer/src/components/github/github-work-item-mutation-target.test.ts": 348, "src/renderer/src/components/github/use-image-input.test.ts": 2619, "src/renderer/src/components/gitlab-item-dialog/use-gitlab-primary-actions.test.ts": 2141, - "src/renderer/src/components/host-picker/bounded-host-list.test.tsx": 667, - "src/renderer/src/components/host-picker/host-list-surfaces.large-config.test.tsx": 2963, + "src/renderer/src/components/host-picker/HostListSearchField.test.tsx": 667, + "src/renderer/src/components/sidebar/project-admission/host-selection/AddRepoHostSelector.large-config.test.tsx": 2963, "src/renderer/src/components/jira-attachment-image.test.tsx": 2117, "src/renderer/src/components/jira-connect-scoped-token.test.tsx": 1047, "src/renderer/src/components/jira-issue-assignee-control.test.tsx": 2875, @@ -5606,7 +5606,7 @@ "src/renderer/src/components/settings/form-controls/SettingsFormControls.segmented-control.test.tsx": 730, "src/renderer/src/components/settings/shortcuts/ShortcutFilterRail.test.ts": 273, "src/renderer/src/components/settings/shortcuts/ShortcutsPane.provenance.test.tsx": 2302, - "src/renderer/src/components/settings/repository/execution/SparsePresetSettingsSection.test.tsx": 744, + "src/renderer/src/components/settings/repository/worktrees/SparsePresetSettingsSection.test.tsx": 744, "src/renderer/src/components/settings/ssh/server-actions/SshHostDeltaMoveDialog.test.tsx": 438, "src/renderer/src/components/settings/ssh/server-actions/SshHostRecoverServerAction.test.tsx": 669, "src/renderer/src/components/settings/ssh/SshPane.test.tsx": 1699, @@ -5636,23 +5636,23 @@ "src/renderer/src/components/settings/notifications/notification-host-pending-save.test.tsx": 2029, "src/renderer/src/components/settings/repository/RepositoryJiraProjectSection.test.tsx": 463, "src/renderer/src/components/settings/repository/RepositoryPaneDraftInput.test.tsx": 314, - "src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.settings-entry.test.tsx": 2007, - "src/renderer/src/components/settings/repository/execution/RepositoryWorktreeDefaultsSection.test.tsx": 495, + "src/renderer/src/components/settings/repository/hosts/RepositoryHostSetupsSection.settings-entry.test.tsx": 2007, + "src/renderer/src/components/settings/repository/worktrees/RepositoryWorktreeDefaultsSection.test.tsx": 495, "src/renderer/src/components/settings/repository/identity/RepositoryIconPicker.github-avatar-refresh.test.tsx": 615, "src/renderer/src/components/settings/runtime-environments/pairing/runtime-share-computer-button.test.tsx": 2092, "src/renderer/src/components/settings/navigation/settings-project-list.test.ts": 99, "src/renderer/src/components/settings/source-control/source-control-action-card-layout.test.tsx": 4551, "src/renderer/src/components/settings/source-control/source-control-action-permission-draft.test.tsx": 6938, - "src/renderer/src/components/settings/ssh/targets/ssh-target-draft.test.ts": 72, + "src/renderer/src/components/ssh-host-form/ssh-target-draft.test.ts": 72, "src/renderer/src/components/settings/ssh/targets/ssh-target-list-model.test.ts": 56, "src/renderer/src/components/integrations/task-trackers/linear-integration-card.test.tsx": 1414, "src/renderer/src/components/settings/appearance/themes/use-catalog-app-themes.test.ts": 2159, "src/renderer/src/components/settings/form-controls/use-debounced-settings-text-draft.test.ts": 308, - "src/renderer/src/components/settings/repository/execution/use-repository-hook-settings-draft.test.tsx": 586, + "src/renderer/src/components/settings/repository/hooks/use-repository-hook-settings-draft.test.tsx": 586, "src/renderer/src/components/settings/repository/hooks/use-repository-issue-command-wsl-stopped.test.ts": 523, "src/renderer/src/components/settings/runtime-environments/catalog/use-runtime-environment-catalog.test.tsx": 2252, "src/renderer/src/components/settings/runtime-environments/catalog/use-runtime-environment-mutation-actions.test.tsx": 2069, - "src/renderer/src/components/settings/session-history/use-session-search-status.test.tsx": 477, + "src/renderer/src/components/session-search/use-session-search-status.test.tsx": 477, "src/renderer/src/components/settings/accounts/usage/use-zcode-plan-credentials.test.tsx": 880, "src/renderer/src/lib/directory-path-suggestion-filter.scan-budget.test.ts": 68, "src/renderer/src/lib/directory-path-suggestion-filter.test.ts": 51, diff --git a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs index 5519e995ad8..567d2c83bf9 100644 --- a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs +++ b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs @@ -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', diff --git a/config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs b/config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs deleted file mode 100644 index 400546950fb..00000000000 --- a/config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs +++ /dev/null @@ -1,118 +0,0 @@ -import assert from 'node:assert/strict' -import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { join, resolve } from 'node:path' -import { parse } from 'yaml' -import { runProcessSync } from '@orca/process-host' -import { auditToolEntry, installAuditTools } from './run-audit-tool.mjs' - -const root = resolve(import.meta.dirname, '../../../..') -const installed = installAuditTools(root) -assert.equal(installed.code, 0, 'Frozen, script-free audit tool install failed') - -const scratch = join(root, 'tmp') -mkdirSync(scratch, { recursive: true }) -const fixture = mkdtempSync(join(scratch, 'locked audit tools ')) -const toolManifest = JSON.parse(readFileSync(join(root, 'config/audit-tools/package.json'), 'utf8')) - -function command(program, args, expectedCode = 0) { - const result = runProcessSync({ program, args, cwd: fixture, timeoutMs: 60_000 }) - assert.equal(result.timedOut, false, `${program} timed out`) - assert.equal(result.signal, null, `${program} received ${result.signal}`) - assert.equal(result.code, expectedCode, `${result.stdout}\n${result.stderr}`) - return result.stdout -} - -function tool(name, args, expectedCode = 0) { - return command(process.execPath, [auditToolEntry(name, root), ...args], expectedCode) -} - -function write(file, value) { - writeFileSync(join(fixture, file), value) -} - -const cleanComponent = 'export default function App() { return }\n' -const indexKeyComponent = - 'export default function App() { return
{["one"].map((text, index) => {text})}
}\n' -const doctorArgs = [ - '.', - '--yes', - '--no-dead-code', - '--no-supply-chain', - '--no-telemetry', - '--no-cache', - '--json', - '--blocking', - 'warning' -] - -try { - command('git', ['init', '--quiet']) - command('git', ['config', 'core.hooksPath', join(fixture, '.git', 'disabled-hooks')]) - command('git', ['config', 'commit.gpgSign', 'false']) - write( - 'package.json', - JSON.stringify({ name: 'locked-audit-smoke', private: true, dependencies: { react: '19.2.8' } }) - ) - write('App.tsx', cleanComponent) - write('knip.json', JSON.stringify({ entry: ['App.tsx'], project: ['*.tsx'] })) - - for (const name of ['react-doctor', 'knip']) { - assert.equal(tool(name, ['--version']).trim(), toolManifest.dependencies[name]) - } - - const clean = JSON.parse(tool('react-doctor', doctorArgs)) - assert.equal(clean.ok, true) - assert.ok(clean.projects.some((project) => project.analyzedFiles.includes('App.tsx'))) - tool('knip', ['--config', 'knip.json', '--files']) - - write('App.tsx', indexKeyComponent) - command('git', ['add', '.']) - command('git', [ - '-c', - 'user.name=Audit tool smoke', - '-c', - 'user.email=audit-smoke@example.invalid', - 'commit', - '--quiet', - '-m', - 'Baseline' - ]) - write('Changed.tsx', indexKeyComponent.replace('function App', 'function Changed')) - command('git', ['add', 'Changed.tsx']) - const changed = JSON.parse( - tool('react-doctor', [...doctorArgs, '--scope', 'lines', '--base', 'HEAD'], 1) - ) - assert.ok(changed.diagnostics.some((item) => item.filePath.endsWith('Changed.tsx'))) - assert.ok(changed.diagnostics.every((item) => !item.filePath.endsWith('App.tsx'))) - - write('Orphan.tsx', 'export const orphan = true\n') - assert.match(tool('knip', ['--config', 'knip.json', '--files'], 1), /Orphan\.tsx/) - - const stale = join(fixture, 'config', 'audit-tools') - mkdirSync(stale, { recursive: true }) - mkdirSync(join(fixture, 'config', 'patches'), { recursive: true }) - const toolPolicy = parse( - readFileSync(join(root, 'config/audit-tools/pnpm-workspace.yaml'), 'utf8') - ) - for (const patch of Object.values(toolPolicy.patchedDependencies ?? {})) { - copyFileSync(join(root, 'config/audit-tools', patch), join(stale, patch)) - } - for (const file of ['pnpm-lock.yaml', 'pnpm-workspace.yaml']) { - copyFileSync(join(root, 'config', 'audit-tools', file), join(stale, file)) - } - writeFileSync( - join(stale, 'package.json'), - JSON.stringify({ - ...toolManifest, - dependencies: { ...toolManifest.dependencies, knip: '0.0.0' } - }) - ) - const rejected = installAuditTools(fixture, (spec) => runProcessSync({ ...spec, stdio: 'pipe' })) - assert.notEqual(rejected.code, 0, 'A stale tool lockfile was accepted') - assert.match(`${rejected.stdout}\n${rejected.stderr}`, /OUTDATED_LOCKFILE/) - console.log( - 'Locked audit tools: real analysis, changed-line filtering, findings and stale-lock rejection passed' - ) -} finally { - rmSync(fixture, { recursive: true, force: true }) -} diff --git a/config/scripts/desktop-distribution/runtime-verification/electron-builder-runtime-resources.test.mjs b/config/scripts/desktop-distribution/runtime-verification/electron-builder-runtime-resources.test.mjs index f693ed3997d..29915eb54ff 100644 --- a/config/scripts/desktop-distribution/runtime-verification/electron-builder-runtime-resources.test.mjs +++ b/config/scripts/desktop-distribution/runtime-verification/electron-builder-runtime-resources.test.mjs @@ -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'), '') - 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') - } -} diff --git a/config/scripts/desktop-distribution/runtime-verification/verify-packaged-daemon-entry.test.mjs b/config/scripts/desktop-distribution/runtime-verification/verify-packaged-daemon-entry.test.mjs index 72dd2f078fb..1266c14b392 100644 --- a/config/scripts/desktop-distribution/runtime-verification/verify-packaged-daemon-entry.test.mjs +++ b/config/scripts/desktop-distribution/runtime-verification/verify-packaged-daemon-entry.test.mjs @@ -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([]) - }) }) diff --git a/config/scripts/mobile-web-app/shell/mobile-web-app-held-press-render.test.mjs b/config/scripts/mobile-web-app/shell/mobile-web-app-held-press-render.test.mjs deleted file mode 100644 index 3148e1797f6..00000000000 --- a/config/scripts/mobile-web-app/shell/mobile-web-app-held-press-render.test.mjs +++ /dev/null @@ -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 -) diff --git a/config/scripts/orcad-distribution/server-bundle/orcad-child-artifacts.test.mjs b/config/scripts/orcad-distribution/server-bundle/orcad-child-artifacts.test.mjs new file mode 100644 index 00000000000..0ab57b04a53 --- /dev/null +++ b/config/scripts/orcad-distribution/server-bundle/orcad-child-artifacts.test.mjs @@ -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)) + } +) diff --git a/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs b/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs index ad7a1da8c5a..cc412c5eb09 100644 --- a/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs +++ b/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs @@ -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', diff --git a/config/scripts/performance/terminal-stream/terminal-output-frame-chunk-benchmark.mjs b/config/scripts/performance/terminal-stream/terminal-output-frame-chunk-benchmark.mjs index 6d54a4accc6..3869c703a5f 100644 --- a/config/scripts/performance/terminal-stream/terminal-output-frame-chunk-benchmark.mjs +++ b/config/scripts/performance/terminal-stream/terminal-output-frame-chunk-benchmark.mjs @@ -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) { diff --git a/config/scripts/performance/terminal-stream/terminal-stream-byte-length-benchmark.mjs b/config/scripts/performance/terminal-stream/terminal-stream-byte-length-benchmark.mjs index 6a60e9ac7ed..85d0ce1da1d 100644 --- a/config/scripts/performance/terminal-stream/terminal-stream-byte-length-benchmark.mjs +++ b/config/scripts/performance/terminal-stream/terminal-stream-byte-length-benchmark.mjs @@ -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 diff --git a/config/scripts/performance/transport/cli-runtime-client-deferral-equivalence.mjs b/config/scripts/performance/transport/cli-runtime-client-deferral-equivalence.mjs index 9121a8bf520..a3d06d5f9d6 100644 --- a/config/scripts/performance/transport/cli-runtime-client-deferral-equivalence.mjs +++ b/config/scripts/performance/transport/cli-runtime-client-deferral-equivalence.mjs @@ -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 ] 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' }], diff --git a/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs b/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs index 047a8d72c74..f9ddb0587af 100644 --- a/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs +++ b/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs @@ -1,4 +1,4 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import path from 'node:path' import process from 'node:process' @@ -36,29 +36,4 @@ describe('validate-plugin-files', () => { expect(result.code).toBe(1) expect(result.stderr).toContain('panel/index.html') }, 60_000) - - it('passes a scaffolded plugin, explaining why there is no release entry outside Git', async () => { - const dir = path.join(await tempRoot(), 'dusk') - await createPluginFromTemplate({ dir, template: 'theme', publisher: 'acme' }) - const result = await validate(dir) - expect(result.code, result.stderr).toBe(0) - expect(result.stdout).toContain('not in a Git repository') - }, 60_000) - - it('passes a language pack that translates protected copy, warning that Orca ignores it', async () => { - const dir = path.join(await tempRoot(), 'portuguese') - await createPluginFromTemplate({ dir, template: 'language-pack', publisher: 'acme' }) - await writeFile( - path.join(dir, 'locales', 'pt-BR.json'), - JSON.stringify({ - common: { cancel: 'Cancelar' }, - components: { 'native-chat': { approval: { allow: 'Permitir', deny: 'Negar' } } } - }) - ) - const result = await validate(dir) - expect(result.code, result.stderr).toBe(0) - expect(result.stderr).toContain( - 'warning: contributes.languagePacks "pt-BR" (locales/pt-BR.json): 2 protected strings are ignored' - ) - }, 60_000) }) diff --git a/config/scripts/preflight/changed-checks/check-changed-code-quality.test.mjs b/config/scripts/preflight/changed-checks/check-changed-code-quality.test.mjs index 203524cd23e..f6b7806fd7f 100644 --- a/config/scripts/preflight/changed-checks/check-changed-code-quality.test.mjs +++ b/config/scripts/preflight/changed-checks/check-changed-code-quality.test.mjs @@ -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 { diff --git a/config/scripts/preflight/changed-checks/check-changed-selection.mjs b/config/scripts/preflight/changed-checks/check-changed-selection.mjs index 3bf510cc912..99d3c46bff0 100644 --- a/config/scripts/preflight/changed-checks/check-changed-selection.mjs +++ b/config/scripts/preflight/changed-checks/check-changed-selection.mjs @@ -272,6 +272,7 @@ const RATCHET_SHARED_MODULES = { 'config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs': [ 'check-react-compiler-compat-ratchet.mjs' ], + 'config/react-compiler-uncompiled-files.txt': ['check-react-compiler-compat-ratchet.mjs'], 'config/scripts/localization/reactive-translate/render-path-translate.mjs': [ 'check-render-path-translate-ratchet.mjs' ] diff --git a/config/scripts/session-search-file-id-e2e/README.md b/config/scripts/session-search-file-id-e2e/README.md deleted file mode 100644 index ae1de7fd994..00000000000 --- a/config/scripts/session-search-file-id-e2e/README.md +++ /dev/null @@ -1,80 +0,0 @@ -# Windows session-search file-ID integration reproduction - -Opt-in Windows/NTFS harness for #20551. Run from the fix workspace root with -dependencies, the Electron binary, and Git object `9845bef63a6` available. -Everything generated stays under ignored `notes/search-ipc/`; each run gets fresh -roots and a profile. No real transcripts, WSL discovery, desktop windows, or user -profile are used. The synthetic file is recreated until NTFS assigns a real inode -above `Number.MAX_SAFE_INTEGER`; failure to obtain one fails the test. - -```powershell -$env:ORCA_BACKGROUND_LAUNCH='1' -pnpm exec esbuild config/scripts/session-search-file-id-e2e/run.ts --bundle --platform=node --format=esm --packages=external --outfile=notes/search-ipc/run.mjs -node notes/search-ipc/run.mjs red -# Expected exit 1: initial indexing/query succeeds, subsequent reconciliation fails. -node notes/search-ipc/run.mjs green -# Expected exit 0 for both the lifecycle and fresh-host restart phases. -node config/scripts/session-search-file-id-e2e/verify.cjs -``` - -Run red and green sequentially: their build step reuses the exported source tree. -The verifier checks the expected red failure, green reports, identical oracle -expressions after formatting normalization, and that exactly the two file-ID -SELECT source files differ. It does not turn an arbitrary red failure into success. - -## Exact topology - -The runner exports **LOCAL integration overlay** #20516 head -`9845bef63a6d0b80ec37af82b5b275287b8e17df` with `git archive`, then bundles the real -scanner entry and parent modules with esbuild. It does not check out, stage, or -push overlay sources. Green changes only the two SELECT projections to the CAST -expressions in #20551; red retains the original projections. CLI #20514 is unused. - -An isolated, windowless Electron host installs the production child search -enablement using fixture settings. The production shared scanner client invokes -`spawnAiVaultServiceProcess`, which forks Electron with `ELECTRON_RUN_AS_NODE=1` -and the real `session-scanner-service-entry`. That child owns the production -instance, indexer, SQLite search engine, and IPC request handling. - -Marker queries come from **separate Node client processes over a real Windows -named pipe**, through production `UnixSocketTransport`, production `RpcDispatcher` -and `AI_VAULT_METHODS`, then the search registry/service and scanner IPC. Status -polls and default-off/disabled responses also exercise registered handlers directly. -An independent read-only SQLite connection verifies active FTS rows and committed -file metadata against filesystem size/mtime. The transcript-consumer observation -logs actual replace/append modes without supplying messages or search results. - -Labelled fixture seams, identical in both variants: - -- Parent root resolution returns the existing `isolatedScanRoots` fixture. -- `getSettings` supplies the isolated JSON policy; real enablement/settings-change functions apply it. -- The child's allowlisted environment includes `ORCA_BACKGROUND_LAUNCH=1`. -- Passive child PID, IPC, stderr, and transcript-read observations are added. -- The unused default RPC method catalog is excluded; the dispatcher receives the production `AI_VAULT_METHODS` explicitly. Its runtime context supplies only a fixture runtime ID. - -## Oracle and evidence - -Default-off creates no DB and returns disabled. Enablement indexes the marker; -two **real default 20-second recent timer cycles** and two explicit full passes -preserve it. An append becomes searchable; a rename replacement with equal byte -length and exactly restored mtime removes the old marker and adds the new one. -The scanner restarts, then a second Electron host opens the same profile/DB and -queries again. Disablement followed by an append, explicit reconcile, and 21-second -wait leaves the DB unchanged and the new marker absent. - -`red-latest.json` / `green-latest.json` locate each run. Reports contain parent and -scanner PIDs, executable/Node/Electron versions, IPC events, raw unsafe inode, -queries, DB metadata, read modes, and scanner exit codes. `*-stages.jsonl` gives -live progress; `process-*.log` preserves complete output. `comparison.json` records -the two-source-only comparison. The production scanner shutdown protocol closes -only recorded children; the runner waits for its own Electron hosts and external -clients. Profiles/DBs remain as evidence, not running services. - -## Boundaries not exercised - -This is not a packaged/full Orca desktop launch. The host and scanner are bundled -from production sources by this harness, not electron-vite's complete app build. -The actual runtime authentication/metadata server, CLI routing, remote SSH/relay -transport, and UI are not exercised. Named-pipe framing and dispatcher are real, -but the harness connects them directly with a fixture token; it makes no claim -about production authentication. No session-search UI exists in this topology. diff --git a/config/scripts/session-search-file-id-e2e/client.cjs b/config/scripts/session-search-file-id-e2e/client.cjs deleted file mode 100644 index 1922547f6ac..00000000000 --- a/config/scripts/session-search-file-id-e2e/client.cjs +++ /dev/null @@ -1,30 +0,0 @@ -const { connect } = require('node:net') -const assert = require('node:assert/strict') -assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1') -const socket = connect(process.argv[2]) -let buffer = '' -socket.setEncoding('utf8') -socket.setTimeout(10_000, () => socket.destroy(new Error('RPC client timeout'))) -socket.on('connect', () => - socket.write( - `${JSON.stringify({ - id: 'file-id-query', - authToken: 'isolated-fixture', - method: 'aiVault.searchSessions', - params: JSON.parse(process.argv[3]) - })}\n` - ) -) -socket.on('data', (chunk) => { - buffer += String(chunk) - const newline = buffer.indexOf('\n') - if (newline === -1) { - return - } - console.log(JSON.stringify({ pid: process.pid, response: JSON.parse(buffer.slice(0, newline)) })) - socket.end() -}) -socket.on('error', (error) => { - console.error(error) - process.exitCode = 1 -}) diff --git a/config/scripts/session-search-file-id-e2e/host.cjs b/config/scripts/session-search-file-id-e2e/host.cjs deleted file mode 100644 index 17ddbb21ff8..00000000000 --- a/config/scripts/session-search-file-id-e2e/host.cjs +++ /dev/null @@ -1,325 +0,0 @@ -const { app } = require('electron') -const assert = require('node:assert/strict') -const fs = require('node:fs/promises') -const { existsSync, appendFileSync } = require('node:fs') -const { join } = require('node:path') -const { DatabaseSync } = require('node:sqlite') -const output = process.argv[2] -const phase = process.argv[3] -const profile = join(output, 'profile') -app.setPath('userData', profile) -app.setPath('sessionData', join(profile, 'chromium')) -app.disableHardwareAcceleration() -globalThis.__fileIdChildren = [] -const report = { - phase, - pid: process.pid, - execPath: process.execPath, - versions: process.versions, - stages: [], - children: [], - stderr: [], - ipc: [] -} -globalThis.__fileIdObserveChild = (child) => { - globalThis.__fileIdChildren.push(child) - child.stderr.on('data', (chunk) => report.stderr.push(String(chunk))) - child.on('message', (message) => - report.ipc.push({ pid: child.pid, type: message.type, operation: message.operation }) - ) -} -const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) -const sessionId = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' -const markers = { - initial: 'quartzinitialmarker', - append: 'cobaltappendedmarker', - replacement: 'velvetreplacedmarker', - disabled: 'tungstendisabledmarker' -} -let api -let registration -let transport -const endpoint = `\\\\.\\pipe\\orca-file-id-${process.pid}` -let settings = {} -let transcript -const database = join(profile, 'ai-vault', 'session-search.sqlite') -function record(stage, data = {}) { - const entry = { stage, at: Date.now(), ...data } - report.stages.push(entry) - appendFileSync(join(output, `${phase}-stages.jsonl`), `${JSON.stringify(entry)}\n`) - console.log(stage, JSON.stringify(data)) -} -function inspect(marker) { - const db = new DatabaseSync(database, { readOnly: true }) - try { - const query = db.prepare( - 'SELECT CAST(ino AS TEXT) AS ino, byte_offset, size_bytes, mtime_ms FROM files WHERE path = ?' - ) - const rows = db - .prepare(`SELECT s.session_id FROM messages_fts f JOIN messages m ON m.id=f.rowid - JOIN sessions s ON s.id=m.session_row_id WHERE messages_fts MATCH ?`) - .all(marker) - return { file: query.get(transcript), sessions: rows.map((row) => row.session_id) } - } finally { - db.close() - } -} -async function query(marker, present) { - const result = await api.runProcess({ - program: process.env.ORCA_FILE_ID_NODE, - args: [ - join(output, 'client.cjs'), - endpoint, - JSON.stringify({ query: `"${marker}"`, scope: 'conversation', freshness: 'indexed' }) - ], - env: process.env, - timeoutMs: 15_000 - }) - assert.equal(result.code, 0, result.stderr) - const external = JSON.parse(result.stdout) - assert.equal(external.response.ok, true, JSON.stringify(external)) - const response = external.response.result - assert.equal(response.kind, 'results', JSON.stringify(response)) - assert.equal( - response.hits.some((hit) => hit.sessionId === sessionId), - present, - `RPC ${marker}` - ) - const disk = inspect(marker) - assert.equal(disk.sessions.includes(sessionId), present, `DB ${marker}`) - const actual = await fs.stat(transcript) - assert.equal( - disk.file.byte_offset, - actual.size, - 'Committed cursor covers actual transcript bytes' - ) - assert.equal(disk.file.size_bytes, actual.size) - assert.equal(disk.file.mtime_ms, actual.mtimeMs) - record('query', { marker, present, clientPid: external.pid, endpoint, response, disk }) -} -async function status() { - return api.rpc('aiVault.searchStatus', {}) -} -async function waitFor(predicate, label, timeout = 30_000) { - const until = Date.now() + timeout - while (Date.now() < until) { - const current = await status() - if (predicate(current)) { - return current - } - await sleep(200) - } - throw new Error(`Timed out: ${label}`) -} -async function policy(next) { - const before = settings - settings = next - await fs.writeFile(join(profile, 'fixture-settings.json'), JSON.stringify(settings)) - api.applySessionSearchSettingsChange(before, settings) -} -async function stopChild() { - const children = [...globalThis.__fileIdChildren] - api.resetAiVaultScannerServiceForTests() - for (const child of children) { - const until = Date.now() + 5000 - while (child.exitCode === null && child.signalCode === null && Date.now() < until) { - await sleep(50) - } - assert.ok( - child.exitCode !== null || child.signalCode !== null, - `Child ${child.pid} did not exit` - ) - if (!report.children.some((row) => row.pid === child.pid)) { - report.children.push({ - pid: child.pid, - spawnfile: child.spawnfile, - spawnargs: child.spawnargs, - exitCode: child.exitCode, - signalCode: child.signalCode - }) - } - } -} -async function run() { - assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1') - await fs.mkdir(profile, { recursive: true }) - api = require('./production.js') - api.setAppEnvironment({ - getPath: (name) => (name === 'userData' ? profile : app.getPath(name)), - getAppPath: () => output, - getVersion: () => app.getVersion(), - isPackaged: () => false, - onWillQuit: (handler) => app.on('will-quit', handler), - exit: (code) => app.exit(code), - getAppMetrics: () => app.getAppMetrics() - }) - const dispatcher = new api.RpcDispatcher({ - methods: api.AI_VAULT_METHODS, - runtime: { getRuntimeId: () => `file-id-${process.pid}` } - }) - transport = new api.UnixSocketTransport({ endpoint, kind: 'named-pipe' }) - transport.onMessage((message, reply) => { - void dispatcher - .dispatch(JSON.parse(message)) - .then((response) => reply(JSON.stringify(response))) - }) - await transport.start() - record('rpc-transport', { - endpoint, - auth: 'fixture; production auth/metadata server not booted', - methods: 'production AI_VAULT_METHODS', - dispatcher: 'production RpcDispatcher' - }) - const roots = { - ...api.isolatedScanRoots(join(output, 'roots')), - wslHomeDirs: [], - additionalCodexSessionsDirs: [], - executionHostId: 'local' - } - process.env.ORCA_FILE_ID_ROOTS = JSON.stringify(roots) - await fs.mkdir(roots.claudeProjectsDir, { recursive: true }) - transcript = join(roots.claudeProjectsDir, `${sessionId}.jsonl`) - if (phase === 'restart') { - settings = JSON.parse(await fs.readFile(join(profile, 'fixture-settings.json'), 'utf8')) - assert.equal(settings.aiVaultSearch.enabled, true) - const beforeRestart = inspect(markers.replacement) - registration = api.installChildSessionSearchService({ - dataRoot: profile, - getSettings: () => settings - }) - await waitFor((s) => s.filesIndexed === 1 && s.phase === 'current', 'Electron host restart') - await query(markers.append, false) - await query(markers.replacement, true) - assert.deepEqual(inspect(markers.replacement), beforeRestart) - record('app-host-restart-same-db') - await disableAndCheck() - return - } - const body = `${api.claudeLines([markers.initial], sessionId, 0).join('\n')}\n` - await fs.writeFile(transcript, body) - let raw = await fs.stat(transcript, { bigint: true }) - for (let n = 0; raw.ino <= BigInt(Number.MAX_SAFE_INTEGER) && n < 512; n++) { - await fs.unlink(transcript) - await fs.writeFile(transcript, body) - raw = await fs.stat(transcript, { bigint: true }) - } - assert.ok(raw.ino > BigInt(Number.MAX_SAFE_INTEGER), 'NTFS must supply an actual unsafe inode') - record('fixture', { - transcript, - rawIno: raw.ino.toString(), - numericIno: BigInt(Number(raw.ino)).toString() - }) - registration = api.installChildSessionSearchService({ - dataRoot: profile, - getSettings: () => settings - }) - assert.ok(registration) - assert.equal((await status()).enabled, false) - assert.deepEqual(await api.rpc('aiVault.searchSessions', { query: markers.initial }), { - kind: 'unavailable', - reason: 'disabled' - }) - assert.equal(existsSync(database), false) - record('default-off') - await policy({ aiVaultSearch: { enabled: true, historyDays: null } }) - const initial = await waitFor( - (s) => s.filesIndexed === 1 && s.phase === 'current', - 'initial indexing' - ) - assert.equal(inspect(markers.initial).file.ino, BigInt(Number(raw.ino)).toString()) - await query(markers.initial, true) - record('initial-indexing', { status: initial }) - let recent = initial - for (let n = 0; n < 2; n++) { - const previous = recent - recent = await waitFor( - (s) => s.lastReconcileAt > previous.lastReconcileAt, - 'recent timer reconciliation' - ) - assert.equal( - recent.lastSweepCompletedAt, - initial.lastSweepCompletedAt, - 'Expected a recent pass' - ) - await query(markers.initial, true) - record('recent-pass', { status: recent }) - } - for (let n = 0; n < 2; n++) { - await api.reconcileSessionSearchInService() - await query(markers.initial, true) - record('full-pass', { status: await status() }) - } - await fs.appendFile( - transcript, - `${api.claudeLines([markers.append], sessionId, 10).join('\n')}\n` - ) - const frozen = new Date(Math.floor((await fs.stat(transcript)).mtimeMs)) - await fs.utimes(transcript, frozen, frozen) - await api.reconcileSessionSearchInService() - await query(markers.append, true) - const before = await fs.stat(transcript) - const replacement = `${transcript}.replacement` - const replacementBody = (await fs.readFile(transcript, 'utf8')).replaceAll( - markers.append, - markers.replacement - ) - assert.equal(Buffer.byteLength(replacementBody), before.size) - await fs.writeFile(replacement, replacementBody) - await fs.rename(replacement, transcript) - await fs.utimes(transcript, before.atime, before.mtime) - const after = await fs.stat(transcript) - assert.equal(after.size, before.size) - assert.equal(after.mtimeMs, before.mtimeMs) - assert.notEqual(after.ino, before.ino) - await api.reconcileSessionSearchInService() - await query(markers.append, false) - await query(markers.replacement, true) - record('replacement', { beforeIno: before.ino, afterIno: after.ino }) - await stopChild() - await waitFor((s) => s.filesIndexed === 1 && s.phase === 'current', 'scanner restart') - await query(markers.append, false) - await query(markers.replacement, true) - record('service-restart') -} -async function disableAndCheck() { - await policy({ aiVaultSearch: { enabled: false, historyDays: null } }) - await waitFor((s) => !s.enabled, 'disable') - const snapshot = inspect(markers.replacement) - await fs.appendFile( - transcript, - `${api.claudeLines([markers.disabled], sessionId, 20).join('\n')}\n` - ) - await api.reconcileSessionSearchInService() - await sleep(21_000) - assert.deepEqual(await api.rpc('aiVault.searchSessions', { query: markers.disabled }), { - kind: 'unavailable', - reason: 'disabled' - }) - assert.deepEqual(inspect(markers.replacement), snapshot) - assert.deepEqual(inspect(markers.disabled).sessions, []) - record('disabled-no-indexing') -} -app.whenReady().then(async () => { - try { - await run() - report.ok = true - } catch (error) { - report.ok = false - report.error = error.stack - console.error(error) - } finally { - registration?.dispose() - await transport?.stop() - if (api) { - await stopChild().catch((error) => { - report.cleanupError = String(error) - report.ok = false - }) - } - if (report.stderr.some((text) => text.includes('[ai-vault-search]'))) { - report.ok = false - } - await fs.writeFile(join(output, `report-${phase}.json`), JSON.stringify(report, null, 2)) - app.exit(report.ok ? 0 : 1) - } -}) diff --git a/config/scripts/session-search-file-id-e2e/run.ts b/config/scripts/session-search-file-id-e2e/run.ts deleted file mode 100644 index 3ab6b5ae15d..00000000000 --- a/config/scripts/session-search-file-id-e2e/run.ts +++ /dev/null @@ -1,194 +0,0 @@ -import assert from 'node:assert/strict' -import { mkdir, readFile, writeFile, copyFile } from 'node:fs/promises' -import { resolve, join, relative } from 'node:path' -import { createHash } from 'node:crypto' -import { build } from 'esbuild' -import { runProcess } from '@orca/process-host' - -const root = process.cwd() -const evidence = resolve('notes/search-ipc') -const overlay = join(evidence, 'overlay') -const wiring = '9845bef63a6' -const mode = process.argv[2] -assert.equal(process.platform, 'win32', 'This harness requires native Windows and NTFS') -assert.ok(mode === 'red' || mode === 'green', 'Pass red or green') -assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1') -const output = join(evidence, mode, String(Date.now())) -await mkdir(output, { recursive: true }) - -async function command(program: string, args: string[]) { - const result = await runProcess({ program, args, cwd: root, timeoutMs: 120_000 }) - assert.equal(result.code, 0, result.stderr) - return result.stdout.trim() -} - -// The overlay is exported, never checked out or staged on the fix branch. -await mkdir(overlay, { recursive: true }) -await command('git', [ - 'archive', - '--format=tar', - `--output=${join(evidence, 'overlay.tar')}`, - wiring, - 'src' -]) -await command('tar', [ - '-xf', - relative(root, join(evidence, 'overlay.tar')), - '-C', - relative(root, overlay) -]) -const edits: { path: string; sha256: string }[] = [] -function replaceOnce(source: string, before: string, after: string) { - assert.equal(source.split(before).length, 2, `Expected exactly one injection: ${before}`) - return source.replace(before, after) -} - -const adapter = join(output, 'adapter.mjs') -const source = (path: string) => JSON.stringify(join(overlay, 'src', path)) -await writeFile( - adapter, - ` -export { installChildSessionSearchService, applySessionSearchSettingsChange } from ${source('main/ai-vault-search/session-search-enablement.ts')}; -export { resetAiVaultScannerServiceForTests, reconcileSessionSearchInService } from ${source('main/ai-vault/session-scanner-service-spawn.ts')}; -export { setAppEnvironment } from ${source('shared/app-environment.ts')}; -export { isolatedScanRoots } from ${source('main/ai-vault/session-scanner-test-fixtures.ts')}; -export { claudeLines } from ${source('main/ai-vault-search/session-search-indexer-test-fixture.ts')}; -export { runProcess } from '@orca/process-host'; -export { UnixSocketTransport } from ${source('main/runtime/rpc/unix-socket-transport.ts')}; -export { RpcDispatcher } from ${source('main/runtime/rpc/dispatcher.ts')}; -export { AI_VAULT_METHODS } from ${source('main/runtime/rpc/methods/ai-vault.ts')}; -import { buildRegistry } from ${source('main/runtime/rpc/core.ts')}; -import { AI_VAULT_METHODS } from ${source('main/runtime/rpc/methods/ai-vault.ts')}; -const registry = buildRegistry(AI_VAULT_METHODS); -export async function rpc(name, params) { - const method = registry.get(name); - if (!method || !name.startsWith('aiVault.search')) throw new Error('Unexpected method'); - return method.handler(method.params.parse(params), {}); -} -` -) - -await build({ - entryPoints: { - production: adapter, - 'session-scanner-service-entry': join( - overlay, - 'src/main/ai-vault/session-scanner-service-entry.ts' - ) - }, - outdir: output, - platform: 'node', - format: 'cjs', - bundle: true, - packages: 'external', - define: { ORCA_FEATURE_WALL_ENABLED: 'true' }, - plugins: [ - { - name: 'labelled-local-fixtures', - setup(api) { - api.onLoad({ filter: /\.ts$/ }, async (args) => { - let contents = await readFile(args.path, 'utf8') - const path = args.path.replaceAll('\\', '/') - if (path.endsWith('/runtime/rpc/methods/rpc-method-registry.ts')) { - // DispatcherOptions explicitly supplies AI_VAULT_METHODS; don't load unrelated default methods. - contents = 'export const ALL_RPC_METHODS = []' - } - if (path.endsWith('/cached-session-list.ts')) { - contents = replaceOnce( - contents, - ' const [additionalCodexHomes, wslHomeDirs] = await Promise.all([', - ' return JSON.parse(process.env.ORCA_FILE_ID_ROOTS!);\n const [additionalCodexHomes, wslHomeDirs] = await Promise.all([' - ) - } - if (path.endsWith('/session-scanner-service-env.ts')) { - contents = replaceOnce( - contents, - " env.ELECTRON_RUN_AS_NODE = '1'", - " env.ORCA_BACKGROUND_LAUNCH = '1'\n env.ELECTRON_RUN_AS_NODE = '1'" - ) - } - if (path.endsWith('/session-scanner-service-spawn.ts')) { - contents = replaceOnce( - contents, - ' lowerAiVaultServicePriority(child.pid)', - ' globalThis.__fileIdObserveChild?.(child)\n lowerAiVaultServicePriority(child.pid)' - ) - } - if (path.endsWith('/session-scanner-service-entry.ts')) { - contents = `import { registerTranscriptConsumer } from './session-transcript-consumers'; -registerTranscriptConsumer({beginRead: start => { console.error('[file-id-read]', JSON.stringify({mode:start.mode,path:start.candidate.file.path})); return null }}); -console.error('[file-id-child]', JSON.stringify({pid:process.pid,execPath:process.execPath,versions:process.versions,background:process.env.ORCA_BACKGROUND_LAUNCH}));\n${contents}` - } - if (mode === 'green' && path.endsWith('/session-search-store.ts')) { - contents = replaceOnce( - contents, - 'SELECT path, dev, ino, mtime_ms', - 'SELECT path, CAST(dev AS REAL) AS dev, CAST(ino AS REAL) AS ino, mtime_ms' - ) - } - if (mode === 'green' && path.endsWith('/session-search-index-writer.ts')) { - contents = replaceOnce( - contents, - 'SELECT dev, ino, byte_offset', - 'SELECT CAST(dev AS REAL) AS dev, CAST(ino AS REAL) AS ino, byte_offset' - ) - } - edits.push({ - path: path.replace(overlay.replaceAll('\\', '/'), ''), - sha256: createHash('sha256').update(contents).digest('hex') - }) - return { contents, loader: 'ts' } - }) - } - } - ] -}) -await copyFile( - join(root, 'config/scripts/session-search-file-id-e2e/host.cjs'), - join(output, 'host.cjs') -) -await copyFile( - join(root, 'config/scripts/session-search-file-id-e2e/client.cjs'), - join(output, 'client.cjs') -) -await writeFile( - join(output, 'topology.json'), - JSON.stringify( - { - wiring: await command('git', ['rev-parse', wiring]), - fix: await command('git', ['rev-parse', 'HEAD']), - mode, - injections: [ - 'isolated root resolver', - 'background child env', - 'child PID/error/read observation', - 'unused default RPC catalog excluded; explicit production AI_VAULT_METHODS' - ], - files: edits.sort((a, b) => a.path.localeCompare(b.path)) - }, - null, - 2 - ) -) -await writeFile(join(evidence, `${mode}-latest.json`), JSON.stringify({ output })) -for (const phase of ['lifecycle', 'restart']) { - console.log(JSON.stringify({ mode, phase, output })) - const result = await runProcess({ - program: join(root, 'node_modules/electron/dist/electron.exe'), - args: [join(output, 'host.cjs'), output, phase], - cwd: output, - env: { - ...process.env, - ORCA_BACKGROUND_LAUNCH: '1', - ELECTRON_RUN_AS_NODE: undefined, - ORCA_FILE_ID_NODE: process.execPath - }, - timeoutMs: 180_000 - }) - await writeFile(join(output, `process-${phase}.log`), result.stdout + result.stderr) - console.log(JSON.stringify({ mode, phase, code: result.code, timedOut: result.timedOut, output })) - process.exitCode = result.code ?? 1 - if (process.exitCode !== 0) { - break - } -} diff --git a/config/scripts/session-search-file-id-e2e/verify.cjs b/config/scripts/session-search-file-id-e2e/verify.cjs deleted file mode 100644 index 180bf4cf154..00000000000 --- a/config/scripts/session-search-file-id-e2e/verify.cjs +++ /dev/null @@ -1,62 +0,0 @@ -const assert = require('node:assert/strict') -const { readFileSync, writeFileSync } = require('node:fs') -const { join, resolve } = require('node:path') -const { createHash } = require('node:crypto') -const { transformSync } = require('esbuild') -const evidence = resolve('notes/search-ipc') -const json = (path) => JSON.parse(readFileSync(path, 'utf8')) -const red = json(join(evidence, 'red-latest.json')).output -const green = json(join(evidence, 'green-latest.json')).output -const before = json(join(red, 'topology.json')) -const after = json(join(green, 'topology.json')) -assert.equal(before.wiring, after.wiring) -assert.deepEqual(before.injections, after.injections) -const oldFiles = new Map(before.files.map((row) => [row.path, row.sha256])) -assert.equal(oldFiles.size, after.files.length) -const changed = after.files - .filter((row) => oldFiles.get(row.path) !== row.sha256) - .map((row) => row.path) - .sort() -assert.deepEqual(changed, [ - '/src/main/ai-vault-search/session-search-index-writer.ts', - '/src/main/ai-vault-search/session-search-store.ts' -]) -for (const name of ['host.cjs', 'client.cjs']) { - // Ignore formatter-only differences; preserve every expression and assertion. - const hash = (root) => - createHash('sha256') - .update( - transformSync(readFileSync(join(root, name), 'utf8'), { - loader: 'js', - minifyWhitespace: true - }).code - ) - .digest('hex') - assert.equal(hash(red), hash(green), `Identical oracle: ${name}`) -} -const failed = json(join(red, 'report-lifecycle.json')) -assert.equal(failed.ok, false) -assert.match(failed.stderr.join(''), /RangeError: Value is too large/) -assert.ok(failed.stages.some((row) => row.stage === 'initial-indexing')) -const reports = [ - json(join(green, 'report-lifecycle.json')), - json(join(green, 'report-restart.json')) -] -for (const report of reports) { - assert.equal(report.ok, true) - assert.ok(report.ipc.some((row) => row.operation === 'searchSessions')) - assert.ok(report.stages.some((row) => row.stage === 'query' && row.clientPid !== report.pid)) - assert.ok(report.children.every((child) => child.exitCode === 0)) -} -assert.notEqual(reports[0].pid, reports[1].pid) -const result = { - ok: true, - wiring: before.wiring, - changed, - red, - green, - parentPids: [failed.pid, ...reports.map((row) => row.pid)], - childPids: [failed, ...reports].flatMap((report) => report.children.map((child) => child.pid)) -} -writeFileSync(join(evidence, 'comparison.json'), JSON.stringify(result, null, 2)) -console.log(JSON.stringify(result)) diff --git a/config/scripts/static-analysis/process-boundaries/check-runtime-electron-ratchet.test.mjs b/config/scripts/static-analysis/process-boundaries/check-runtime-electron-ratchet.test.mjs deleted file mode 100644 index 20d9dc63f14..00000000000 --- a/config/scripts/static-analysis/process-boundaries/check-runtime-electron-ratchet.test.mjs +++ /dev/null @@ -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) -}) diff --git a/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs b/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs index 69c920f9add..714acf736a6 100644 --- a/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs +++ b/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs @@ -16,9 +16,15 @@ import { } from '../../ratchet-baseline/ratchet-baseline.mjs' import { HAZARD_FIXES, + LIVE_MODULE_READERS, + VIRTUALIZER_HOOKS, + findLiveReadWrappers, findMemoizedCalls, findSourceHazards, + findVirtualizerMemoFlows, + findVirtualizerWrappers, hookCallLines, + renderLiveReadLines, renderStoreReadLines } from './react-compiler-hazards.mjs' @@ -28,6 +34,8 @@ import { const SCAN_ROOT = 'src/renderer/src' const BAILOUT_BASELINE = 'config/react-compiler-bailout-baseline.txt' const HAZARD_BASELINE = 'config/react-compiler-hazard-baseline.txt' +// The build leaves these files uncompiled, so their hazards cannot run. +const UNCOMPILED_LIST = 'config/react-compiler-uncompiled-files.txt' const COMMAND = 'pnpm check:react-compiler-compat-ratchet' const NOT_SHIPPED = /(?:^|\/)__(?:mocks|fixtures|tests)__\/|\.(?:test|spec|bench)\.[cm]?tsx?$|[.-]test-|[.-]fixtures?\.tsx?$/ @@ -93,6 +101,59 @@ function addTo(map, key, value) { map.set(key, [...(map.get(key) ?? []), value]) } +function readUncompiledFiles(root) { + const file = path.join(root, UNCOMPILED_LIST) + if (!fs.existsSync(file)) { + return new Set() + } + return new Set( + fs + .readFileSync(file, 'utf8') + .split('\n') + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith('#')) + ) +} + +/** Virtualizer hooks plus every hook that returns one, followed through wrappers of wrappers. */ +function collectVirtualizerHooks(sources) { + const hooks = new Map(VIRTUALIZER_HOOKS) + for (let grew = true; grew;) { + grew = false + for (const [rel, text] of sources) { + for (const { name, shape } of findVirtualizerWrappers(rel, text, hooks)) { + if (!hooks.has(name)) { + hooks.set(name, shape) + grew = true + } + } + } + } + return hooks +} + +/** Live module-state readers plus every plain function that calls one, followed through wrappers. */ +function collectLiveReaders(sources) { + const readers = new Set(LIVE_MODULE_READERS) + for (let grew = true; grew;) { + grew = false + for (const [rel, text] of sources) { + for (const name of findLiveReadWrappers(rel, text, readers)) { + if (!readers.has(name)) { + readers.add(name) + grew = true + } + } + } + } + return readers +} + +function sourceLineOf(text, snippet) { + const index = text.split('\n').findIndex((line) => line.includes(snippet.split('(')[0])) + return index === -1 ? '?' : index + 1 +} + async function scanFile(rel, text, result) { const output = await transform(rel, text, COMPILER_OPTIONS) if (output.fatal) { @@ -105,15 +166,37 @@ async function scanFile(rel, text, result) { const message = error.message.split('\n')[0] addTo(result.diagnostics, rel, { line: lineAt(bytes, error.labels[0]?.start ?? 0), message }) } + if (result.uncompiled.has(rel)) { + return + } + for (const { fn, text: snippet } of findVirtualizerMemoFlows( + rel, + text, + output.code, + result.virtualizerHooks + )) { + addTo( + result.hazards, + `${rel}#${fn}:virtualizer-in-memo-block`, + `${sourceLineOf(text, snippet)}: ${snippet}` + ) + } for (const hazard of findSourceHazards(rel, text)) { addTo(result.hazards, `${rel}#${hazard.fn}:${hazard.kind}`, `${hazard.line}: ${hazard.text}`) } const storeReadFns = new Set() - for (const { fn, kind, name } of findMemoizedCalls(rel, output.code)) { + for (const { fn, kind, name } of findMemoizedCalls(rel, output.code, result.liveReaders)) { if (kind === 'store-read') { storeReadFns.add(fn) continue } + if (kind === 'live-read') { + // A call inside the source's own useMemo or a closure keeps its written behavior. + for (const line of renderLiveReadLines(rel, text, fn, name)) { + addTo(result.hazards, `${rel}#${fn}:live-read-in-memo-block`, `${line}: ${name}()`) + } + continue + } const lines = hookCallLines(rel, text, fn, name) addTo(result.hazards, `${rel}#${fn}:hook-in-memo-block`, `${lines.join(', ')}: ${name}()`) } @@ -126,8 +209,17 @@ async function scanFile(rel, text, result) { } export async function scanRenderer(root = process.cwd()) { - const result = { files: 0, compiled: 0, diagnostics: new Map(), hazards: new Map() } - const pending = [...readTrackedSources(root, [SCAN_ROOT], isScannedPath)] + const sources = [...readTrackedSources(root, [SCAN_ROOT], isScannedPath)] + const result = { + files: 0, + compiled: 0, + diagnostics: new Map(), + hazards: new Map(), + uncompiled: readUncompiledFiles(root), + virtualizerHooks: collectVirtualizerHooks(sources), + liveReaders: collectLiveReaders(sources) + } + const pending = [...sources] result.files = pending.length await Promise.all( Array.from({ length: IN_FLIGHT }, async () => { diff --git a/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs b/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs index 0dee8c26189..fbe7590cf13 100644 --- a/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs +++ b/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs @@ -31,6 +31,16 @@ export const HAZARD_FIXES = { 'React Compiler caches this render-time `store.getState()` snapshot on unrelated inputs, so it', 'goes stale. Read it in the event handler or effect that uses it, or select it with a hook.' ], + 'virtualizer-in-memo-block': [ + 'A TanStack virtualizer is one object mutated in place, so React Compiler serves rows, sizes or', + 'child elements cached on it after every scroll. Add the file to', + 'config/react-compiler-uncompiled-files.txt, owners that pass the virtualizer down included.' + ], + 'live-read-in-memo-block': [ + 'React Compiler caches this render-time read of module state (a provider runtime context key or a', + 'structured selection) on its arguments, so it misses the module-level change. Add the file to', + 'config/react-compiler-uncompiled-files.txt, or subscribe to the state so a change re-renders.' + ], 'hook-in-memo-block': [ 'React Compiler memoizes this hook call inside a cached block, so it runs only when the block', 'recomputes (a conditional hook). Call the hook in its own top-level `const` and use the variable.' @@ -247,16 +257,19 @@ function isStoreRead(node) { ) } -function memoizedCallKind(node) { +function memoizedCallKind(node, liveReaders) { if (isStoreRead(node)) { return { kind: 'store-read', name: 'getState' } } - const hook = calleeName(node.expression) - return hook && HOOK_NAME.test(hook) ? { kind: 'hook', name: hook } : null + const callee = calleeName(node.expression) + if (callee && liveReaders.has(callee)) { + return { kind: 'live-read', name: callee } + } + return callee && HOOK_NAME.test(callee) ? { kind: 'hook', name: callee } : null } -/** Hook calls and `getState()` reads the compiler placed inside a memo-cache guarded block. */ -export function findMemoizedCalls(fileName, compiledCode) { +/** Hook calls, `getState()` reads and live module-state reads the compiler placed inside a memo-cache guarded block. */ +export function findMemoizedCalls(fileName, compiledCode, liveReaders = new Set()) { if (!compiledCode.includes('compiler-runtime')) { return [] } @@ -271,7 +284,7 @@ export function findMemoizedCalls(fileName, compiledCode) { if (isFunctionNode(node)) { return } - const call = ts.isCallExpression(node) ? memoizedCallKind(node) : null + const call = ts.isCallExpression(node) ? memoizedCallKind(node, liveReaders) : null // Nested guarded blocks are walked once per enclosing block; keying by node dedupes them. if (call) { found.set(node, { fn, ...call }) @@ -315,6 +328,20 @@ export function findMemoizedStoreReads(fileName, compiledCode) { /** Source lines of render-time `getState()` calls in `fnName`; a useMemo/callback read is excluded. */ export function renderStoreReadLines(fileName, text, fnName) { + return renderCallLines(fileName, text, fnName, isStoreRead) +} + +/** Source lines of render-time calls to `callee` in `fnName`; a useMemo/callback call is excluded. */ +export function renderLiveReadLines(fileName, text, fnName, callee) { + return renderCallLines( + fileName, + text, + fnName, + (node) => ts.isCallExpression(node) && calleeName(node.expression) === callee + ) +} + +function renderCallLines(fileName, text, fnName, matches) { const sourceFile = parseModule(fileName, text) const lines = new Set() for (const { name, node: root } of listReactFunctions(sourceFile)) { @@ -325,7 +352,7 @@ export function renderStoreReadLines(fileName, text, fnName) { if (node !== root && isFunctionNode(node)) { return } - if (isStoreRead(node)) { + if (matches(node)) { lines.add(lineOf(sourceFile, node)) } ts.forEachChild(node, visit) @@ -335,6 +362,69 @@ export function renderStoreReadLines(fileName, text, fnName) { return [...lines].sort((a, b) => a - b) } +// Reads of module-level state that changes without a React update; a cache keyed on props keeps the old value. +export const LIVE_MODULE_READERS = [ + // Both fold in providerRuntimeSessionGeneration (lib/provider-runtime-context.ts). + 'getProviderRuntimeContextKey', + 'getEnvironmentRuntimeContextKey', + // Both read the selection lifetime registry in structured-agent-session-selection-controller.ts. + 'structuredSessionSelectionAuthority', + 'structuredSessionSelectionController' +] + +function moduleFunctionName(node) { + if (ts.isFunctionDeclaration(node) && node.name) { + return node.name.text + } + const parent = node.parent + return (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) && + ts.isVariableDeclaration(parent) && + ts.isIdentifier(parent.name) && + ts.isVariableStatement(parent.parent?.parent) + ? parent.name.text + : null +} + +/** Module-scope plain functions whose own body calls a live reader, so their result is live too. */ +export function findLiveReadWrappers(fileName, text, readers) { + if (![...readers].some((reader) => text.includes(reader))) { + return [] + } + const sourceFile = parseModule(fileName, text) + const wrappers = [] + for (const statement of sourceFile.statements) { + const candidates = ts.isFunctionDeclaration(statement) + ? [statement] + : ts.isVariableStatement(statement) + ? statement.declarationList.declarations + .map((declaration) => declaration.initializer && unwrap(declaration.initializer)) + .filter((init) => init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) + : [] + for (const fn of candidates) { + const name = moduleFunctionName(fn) + if (!name || isReactName(name) || readers.has(name)) { + continue + } + let calls = false + const visit = (node) => { + if (calls || (node !== fn && isFunctionNode(node))) { + return + } + if (ts.isCallExpression(node) && readers.has(calleeName(node.expression) ?? '')) { + calls = true + return + } + ts.forEachChild(node, visit) + } + visit(fn) + if (calls) { + wrappers.push(name) + } + } + } + return wrappers +} + /** Source lines of `hook` calls in `fnName` that sit inside a larger expression. */ export function hookCallLines(fileName, text, fnName, hook) { const sourceFile = parseModule(fileName, text) @@ -358,3 +448,204 @@ export function hookCallLines(fileName, text, fnName, hook) { } return lines.size > 0 ? [...lines].sort((a, b) => a - b) : ['?'] } + +// A TanStack virtualizer is one object mutated in place, so a cache keyed on it never refreshes. +export const VIRTUALIZER_HOOKS = new Map([ + ['useVirtualizer', 'direct'], + ['useWindowVirtualizer', 'direct'] +]) +const VIRTUALIZER_NAME = /^\w*[vV]irtualizer$/ +const VIRTUALIZER_TYPE = /\bVirtualizer\s* text.includes(hook))) { + return [] + } + const sourceFile = parseModule(fileName, text) + const wrappers = [] + for (const { name, node } of listReactFunctions(sourceFile)) { + if (!HOOK_NAME.test(name) || hooks.has(name)) { + continue + } + const bound = new Set() + let shape = null + const visit = (child) => { + if (child !== node && isFunctionNode(child)) { + return + } + if ( + ts.isVariableDeclaration(child) && + ts.isIdentifier(child.name) && + virtualizerHookShape(child.initializer, hooks) === 'direct' + ) { + bound.add(child.name.text) + } + if (ts.isReturnStatement(child) && child.expression) { + const value = unwrap(child.expression) + if ( + (ts.isIdentifier(value) && bound.has(value.text)) || + virtualizerHookShape(value, hooks) === 'direct' + ) { + shape = 'direct' + } else if ( + ts.isObjectLiteralExpression(value) && + value.properties.some( + (p) => p.name && ts.isIdentifier(p.name) && p.name.text === 'virtualizer' + ) + ) { + shape ??= 'property' + } + } + ts.forEachChild(child, visit) + } + visit(node) + if (shape) { + wrappers.push({ name, shape }) + } + } + return wrappers +} + +/** Prop and parameter names this module types as a Virtualizer. */ +function virtualizerTypedNames(fileName, text) { + const names = new Set() + if (!VIRTUALIZER_TYPE.test(text)) { + return names + } + const sourceFile = parseModule(fileName, text) + const visit = (node) => { + if ( + (ts.isPropertySignature(node) || ts.isParameter(node)) && + node.type && + ts.isIdentifier(node.name) && + VIRTUALIZER_TYPE.test(node.type.getText(sourceFile)) + ) { + names.add(node.name.text) + } + ts.forEachChild(node, visit) + } + visit(sourceFile) + return names +} + +/** Cache blocks keyed on a virtualizer that read it or pass it as a JSX prop: `{ fn, text }`. */ +export function findVirtualizerMemoFlows( + fileName, + sourceText, + compiledCode, + hooks = VIRTUALIZER_HOOKS +) { + if ( + !compiledCode.includes('compiler-runtime') || + !( + /[vV]irtualizer/.test(compiledCode) || + [...hooks.keys()].some((hook) => compiledCode.includes(hook)) + ) + ) { + return [] + } + const typed = virtualizerTypedNames(fileName, sourceText) + const sourceFile = parseModule(fileName, compiledCode) + const runtime = compilerCacheNames(sourceFile) + if (runtime.size === 0) { + return [] + } + const caches = new Set() + const bound = new Set() + const isVirtualizer = (expression) => { + const node = unwrap(expression) + if (ts.isIdentifier(node)) { + const name = node.text.replace(/_\d+$/, '') + return bound.has(node.text) || VIRTUALIZER_NAME.test(name) || typed.has(name) + } + if (ts.isPropertyAccessExpression(node)) { + const name = node.name.text + return VIRTUALIZER_NAME.test(name) || typed.has(name) + } + return false + } + const keyedOnVirtualizer = (condition) => { + let keyed = false + const visit = (node) => { + if ( + ts.isBinaryExpression(node) && + node.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsEqualsToken && + (isVirtualizer(node.left) || isVirtualizer(node.right)) + ) { + keyed = true + } + if (!keyed) { + ts.forEachChild(node, visit) + } + } + visit(condition) + return keyed + } + const found = new Map() + // Closures call the live virtualizer when they run; only render-time reads and props go stale. + const collect = (fn, node) => { + if (isFunctionNode(node)) { + return + } + const passed = + ts.isJsxAttribute(node) && + node.initializer && + ts.isJsxExpression(node.initializer) && + node.initializer.expression && + isVirtualizer(node.initializer.expression) + const read = + ts.isPropertyAccessExpression(node) && + isVirtualizer(node.expression) && + !(STABLE_VIRTUALIZER_METHODS.has(node.name.text) && !ts.isCallExpression(node.parent)) + if (passed || read) { + found.set(node, { fn, text: node.getText(sourceFile).split('\n')[0].slice(0, 100) }) + return + } + ts.forEachChild(node, (child) => collect(fn, child)) + } + const visit = (fn, node) => { + if (ts.isVariableDeclaration(node) && node.initializer) { + const init = unwrap(node.initializer) + const shape = virtualizerHookShape(init, hooks) + if (ts.isIdentifier(node.name)) { + if ( + ts.isCallExpression(init) && + ts.isIdentifier(init.expression) && + runtime.has(init.expression.text) + ) { + caches.add(node.name.text) + } else if (shape === 'direct' || isVirtualizer(init)) { + bound.add(node.name.text) + } + } else if (ts.isObjectBindingPattern(node.name)) { + for (const element of node.name.elements) { + const key = (element.propertyName ?? element.name).getText(sourceFile) + if (ts.isIdentifier(element.name) && (key === 'virtualizer' || typed.has(key))) { + bound.add(element.name.text) + } + } + } + } + if ( + ts.isIfStatement(node) && + readsCache(node.expression, caches) && + keyedOnVirtualizer(node.expression) + ) { + collect(fn, node.thenStatement) + } + const next = isFunctionNode(node) ? (reactFunctionName(node) ?? fn) : fn + ts.forEachChild(node, (child) => visit(next, child)) + } + visit('(module)', sourceFile) + return [...found.values()] +} diff --git a/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.test.mjs b/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.test.mjs index e7ec711261d..5a249927121 100644 --- a/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.test.mjs +++ b/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.test.mjs @@ -1,9 +1,14 @@ import { describe, expect, it } from 'vitest' import { + findLiveReadWrappers, + findMemoizedCalls, findMemoizedHookCalls, findMemoizedStoreReads, findSourceHazards, + findVirtualizerMemoFlows, + findVirtualizerWrappers, + renderLiveReadLines, renderStoreReadLines } from './react-compiler-hazards.mjs' @@ -101,3 +106,90 @@ describe('store reads in memo blocks', () => { expect(renderStoreReadLines('a.ts', src, 'useRoute')).toEqual([3]) }) }) + +describe('virtualizer flows into memo blocks', () => { + it('follows wrapper hooks and flags cached reads and props, not closures or bound methods', () => { + const wrapper = [ + 'export function useRows(n) {', + ' const virtualizer = useVirtualizer({ count: n })', + ' return { virtualizer, n }', + '}' + ].join('\n') + expect(findVirtualizerWrappers('w.ts', wrapper)).toEqual([ + { name: 'useRows', shape: 'property' } + ]) + const hooks = new Map([ + ['useVirtualizer', 'direct'], + ['useList', 'direct'] + ]) + const compiled = [ + 'import { c as _c } from "react/compiler-runtime";', + 'export function Pane() {', + ' const $ = _c(4);', + ' const list = useList();', + ' let t0;', + ' if ($[0] !== list) {', + ' t0 = list.scrollToIndex(0)} rowRef={list.measureElement} />;', + ' $[0] = list;', + ' $[1] = t0;', + ' } else {', + ' t0 = $[1];', + ' }', + ' let t1;', + ' if ($[2] !== list) {', + ' t1 = () => list.getVirtualItems();', + ' $[2] = list;', + ' $[3] = t1;', + ' } else {', + ' t1 = $[3];', + ' }', + ' return t0;', + '}' + ].join('\n') + expect( + findVirtualizerMemoFlows('a.jsx', '', compiled, hooks).map(({ fn, text }) => `${fn}:${text}`) + ).toEqual(['Pane:list={list}', 'Pane:list.getTotalSize']) + }) +}) + +describe('live module-state reads in memo blocks', () => { + it('follows plain wrappers and flags a render read the compiler caches, not a useMemo one', () => { + const lib = [ + 'export function scopeKey(s) {', + ' return s ? runtimeKey(s.env) : null', + '}', + 'export const later = (s) => () => runtimeKey(s)', + 'export function useScope(s) {', + ' return runtimeKey(s)', + '}' + ].join('\n') + expect(findLiveReadWrappers('lib.ts', lib, new Set(['runtimeKey']))).toEqual(['scopeKey']) + const compiled = [ + 'import { c as _c } from "react/compiler-runtime";', + 'export function Card(t0) {', + ' const $ = _c(2);', + ' const { settings } = t0;', + ' let t1;', + ' if ($[0] !== settings) {', + ' t1 = scopeKey(settings);', + ' $[0] = settings;', + ' $[1] = t1;', + ' } else {', + ' t1 = $[1];', + ' }', + ' return t1;', + '}' + ].join('\n') + const readers = new Set(['runtimeKey', 'scopeKey']) + expect(findMemoizedCalls('a.js', compiled, readers)).toEqual([ + { fn: 'Card', kind: 'live-read', name: 'scopeKey' } + ]) + const src = [ + 'export function Card({ settings }) {', + ' const kept = useMemo(() => scopeKey(settings), [settings])', + ' return [kept, scopeKey(settings)]', + '}' + ].join('\n') + expect(renderLiveReadLines('a.tsx', src, 'Card', 'scopeKey')).toEqual([3]) + }) +}) diff --git a/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs b/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs deleted file mode 100644 index 7e0a827a2ff..00000000000 --- a/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs +++ /dev/null @@ -1,66 +0,0 @@ -import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterAll, describe, expect, it } from 'vitest' -import { copyScriptWithLocalModules } from './script-module-dependencies.mjs' - -const fixtureDir = mkdtempSync(join(tmpdir(), 'script-module-dependencies-')) - -afterAll(() => { - rmSync(fixtureDir, { recursive: true, force: true }) -}) - -function sourceTree(files) { - const sourceDir = mkdtempSync(join(fixtureDir, 'source-')) - for (const [name, contents] of Object.entries(files)) { - writeFileSync(join(sourceDir, name), contents) - } - return sourceDir -} - -function copiedNames(files, entryName) { - const sourceDir = sourceTree(files) - const destinationDir = join(mkdtempSync(join(fixtureDir, 'dest-')), 'scripts') - copyScriptWithLocalModules(join(sourceDir, entryName), destinationDir) - const names = readdirSync(destinationDir).sort() - for (const name of names) { - expect(readFileSync(join(destinationDir, name), 'utf8'), name).toBe(files[name]) - } - return names -} - -describe('copyScriptWithLocalModules', () => { - it('preserves parent paths for modules shared with the runtime', () => { - const sourceDir = sourceTree({ 'runtime.ts': 'export const value = 42\n' }) - mkdirSync(join(sourceDir, 'scripts')) - writeFileSync(join(sourceDir, 'scripts', 'entry.mjs'), "export { value } from '../runtime'\n") - const destinationRoot = mkdtempSync(join(fixtureDir, 'dest-')) - copyScriptWithLocalModules( - join(sourceDir, 'scripts', 'entry.mjs'), - join(destinationRoot, 'scripts') - ) - expect(readFileSync(join(destinationRoot, 'runtime.ts'), 'utf8')).toBe( - 'export const value = 42\n' - ) - }) - - // Cover require-only CJS gate dependencies so copied fixture fails for target defect, not missing module. - - it('follows a require reached only through an imported module', () => { - const names = copiedNames( - { - 'entry.mjs': "import './middle.cjs'\n", - 'middle.cjs': "require('./leaf.cjs')\n", - 'leaf.cjs': 'module.exports = {}\n' - }, - 'entry.mjs' - ) - expect(names).toContain('leaf.cjs') - }) - - it('terminates on a cycle rather than recursing forever', () => { - expect( - copiedNames({ 'a.mjs': "import './b.mjs'\n", 'b.mjs': "import './a.mjs'\n" }, 'a.mjs') - ).toEqual(['a.mjs', 'b.mjs']) - }) -}) diff --git a/config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs b/config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs new file mode 100644 index 00000000000..df83d7ca439 --- /dev/null +++ b/config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.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) + } + } + } +}) diff --git a/config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.test.mjs b/config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.test.mjs new file mode 100644 index 00000000000..4d10389b5b8 --- /dev/null +++ b/config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.test.mjs @@ -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 }) + } +}) diff --git a/config/scripts/test-runtime/execution-policy/vitest-shared-worker-files.mjs b/config/scripts/test-runtime/execution-policy/vitest-shared-worker-files.mjs new file mode 100644 index 00000000000..e436fafecca --- /dev/null +++ b/config/scripts/test-runtime/execution-policy/vitest-shared-worker-files.mjs @@ -0,0 +1,94 @@ +import { readFileSync, statSync } from 'node:fs' +import { dirname, join, relative, resolve } from 'node:path' + +// vitest-shared-worker-file-reset.mjs undoes mocks, timers, stubs, env and cwd after each file. +// These can't be undone between files, so a file that uses them keeps its own worker. +const ISOLATION_REQUIRING_API = new RegExp( + [ + // Opt-out for a file whose state leaks in ways the reset cannot see. + String.raw`@orca-isolated-worker\b`, + String.raw`\bvi\.(?:doMock|unmock|doUnmock|resetModules)\(`, + String.raw`@vitest-environment\s+(?!node\b)`, + String.raw`\bglobalThis(?:\.\w+|\[[^\]]+\])\s*=[^=]`, + String.raw`\bObject\.defineProperty\(\s*(?:globalThis|process|navigator|window|document)\b` + ].join('|') +) +const IMPORT_SPECIFIER = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)['"]([^'"]+)['"]/g +const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.mts', '.mjs', '.js'] + +function isFile(path) { + try { + return statSync(path).isFile() + } catch { + return false + } +} + +function resolveLocal(fromFile, specifier, aliases) { + let base = null + if (specifier.startsWith('./') || specifier.startsWith('../')) { + base = resolve(dirname(fromFile), specifier) + } else { + const alias = aliases.find(({ find }) => specifier === find || specifier.startsWith(`${find}/`)) + if (!alias) { + return null + } + base = join(alias.replacement, specifier.slice(alias.find.length)) + } + const stem = base.replace(/\.[cm]?jsx?$/, '') + const candidates = [ + base, + ...SOURCE_EXTENSIONS.map((extension) => stem + extension), + ...SOURCE_EXTENSIONS.map((extension) => join(base, `index${extension}`)) + ] + return ( + candidates.find( + (candidate) => !/[\\/]node_modules[\\/]/.test(candidate) && isFile(candidate) + ) ?? null + ) +} + +/** + * Returns the test files (root-relative, forward slashes) that can share a worker's module cache. + * Only the test file and the test-support files it imports are scanned, not production modules. + */ +export function filesSafeToShareWorker(root, files, aliases = []) { + const sources = new Map() + const read = (file) => { + let source = sources.get(file) + if (source === undefined) { + source = readFileSync(file, 'utf8') + sources.set(file, source) + } + return source + } + const isTestSupport = (file) => /\bfrom\s+['"]vitest['"]/.test(read(file)) + const memo = new Map() + const visiting = new Set() + const requiresIsolation = (file) => { + const known = memo.get(file) + if (known !== undefined) { + return known + } + if (visiting.has(file)) { + return false + } + visiting.add(file) + const source = read(file) + let result = ISOLATION_REQUIRING_API.test(source) + for (const match of result ? [] : source.matchAll(IMPORT_SPECIFIER)) { + const target = resolveLocal(file, match[1], aliases) + if (target && isTestSupport(target) && requiresIsolation(target)) { + result = true + break + } + } + visiting.delete(file) + memo.set(file, result) + return result + } + return files + .map((file) => resolve(root, file)) + .filter((file) => isFile(file) && !requiresIsolation(file)) + .map((file) => relative(root, file).replaceAll('\\', '/')) +} diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs index 3fc7dd70837..d8942881e55 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs @@ -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', diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs index a79aea4f639..2259db54cb3 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs @@ -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', diff --git a/config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs b/config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs index ce11311f482..0b31fb8b6f5 100644 --- a/config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs +++ b/config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs @@ -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', diff --git a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs index 3166e02549d..627cfe9031b 100644 --- a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs +++ b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs @@ -157,7 +157,6 @@ export const WINDOWS_BOUNDARY_TESTS = [ 'config/scripts/native-build/windows/windows-pe-machine.test.mjs', 'config/scripts/native-build/windows/build-windows-cli-launcher.test.mjs', 'config/scripts/desktop-distribution/runtime-verification/verify-packaged-windows-agent-hook.test.mjs', - 'config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs', 'src/main/windows/windows-registry-addon.test.ts', 'src/main/daemon/executable-host/windows/testing/daemon-host-process-package.test.ts', 'src/shared/windows-security-addon.win32.test.ts', @@ -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', diff --git a/config/scripts/workflow/source-routing/pr-unit-support-routing.test.mjs b/config/scripts/workflow/source-routing/pr-unit-support-routing.test.mjs deleted file mode 100644 index 7e3a023c4f4..00000000000 --- a/config/scripts/workflow/source-routing/pr-unit-support-routing.test.mjs +++ /dev/null @@ -1,98 +0,0 @@ -import { beforeAll, describe, expect, it } from 'vitest' -import { - buildUnitDependencyGraph, - collectUnitDependencyGraph, - unitConsumers -} from '../../ci/unit-selection/dependency-graph/ci-unit-dependency-graph.mjs' -import { - CROSS_VERSION_WIRE_DIR, - discoverUnitFiles -} from '../../ci/unit-selection/dependency-graph/ci-unit-files.mjs' - -const harness = - 'src/renderer/src/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture.ts' -const structuredSessionHarness = - 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx' - -const unitHarnesses = [ - harness, - structuredSessionHarness, - 'src/renderer/src/store/slices/editor/editor-slice-test-harness.ts', - 'src/renderer/src/store/slices/browser/browser-slice-test-harness.ts', - 'src/renderer/src/runtime/hosted-terminals/creation/testing/web-runtime-terminal-create.test-fixture.ts', - 'src/renderer/src/runtime/sync-runtime-graph/testing/sync-runtime-graph-test-harness.ts' -] -const supportBridges = new Set([ - // Launch request suites' store rig; it takes the terminal harness's workspace layout. - 'src/renderer/src/runtime/hosted-terminals/creation/agent-launch/web-runtime-agent-launch-options.test-fixture.ts', - 'src/renderer/src/runtime/browser/creation/testing/web-runtime-browser-creation-placement-test-rig.ts', - 'src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts', - // Autosave suites' store rig; it takes the editor harness's tab-layout maps. - 'src/renderer/src/components/editor/autosave/editor-autosave-controller-test-fixture.ts', - // Closed-saving-view save suites' rig; it builds on the autosave rig above. - 'src/renderer/src/components/editor/save/queue/editor-save-closed-view.test-fixture.ts', - // Browser suites' store with main drawing their tabs; it takes the browser harness's store. - 'src/renderer/src/store/slices/browser/browser-slice-drawn-from-main.test-fixture.ts' -]) - -function productConsumers(file, graph, unitFiles) { - return [...unitConsumers([file], graph.reverse)].filter( - (consumer) => - consumer !== file && - !unitFiles.has(consumer) && - !(consumer.startsWith(CROSS_VERSION_WIRE_DIR) && consumer.endsWith('.unit.test.ts')) && - !supportBridges.has(consumer) - ) -} - -describe('unit support import ownership', () => { - let graph - let unitFiles - beforeAll(() => { - graph = collectUnitDependencyGraph() - unitFiles = new Set(discoverUnitFiles()) - }, 60_000) - - it.each(unitHarnesses)('rejects any product consumer of %s', (unitHarness) => { - expect(graph.files.has(unitHarness)).toBe(true) - expect( - [...unitConsumers([unitHarness], graph.reverse)].some((file) => unitFiles.has(file)) - ).toBe(true) - expect(productConsumers(unitHarness, graph, unitFiles)).toEqual([]) - }) - - it.each([ - "import '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'", - "export * from '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'", - "import('@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture')", - "import type { Fixture } from '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'" - ])('detects a product importer using %s', (source) => { - const importer = 'src/renderer/src/runtime/product.ts' - const test = 'src/renderer/src/runtime/ownership.test.ts' - const synthetic = buildUnitDependencyGraph( - new Map([ - [harness, 'export const value = 1'], - [importer, source], - [test, "import './web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'"] - ]) - ) - expect(productConsumers(harness, synthetic, new Set([test]))).toEqual([importer]) - }) - - it('rejects product consumers reached through an audited support bridge', () => { - const bridge = - 'src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts' - const importer = 'src/renderer/src/components/editor/product.ts' - const synthetic = buildUnitDependencyGraph( - new Map([ - [harness, 'export const value = 1'], - [ - bridge, - "import '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'" - ], - [importer, "import './model-lifetime/retention/editor-model-lifetime-fixture'"] - ]) - ) - expect(productConsumers(harness, synthetic, new Set())).toEqual([importer]) - }) -}) diff --git a/config/vitest.config.ts b/config/vitest.config.ts index 6202566aa32..7dc0f04c525 100644 --- a/config/vitest.config.ts +++ b/config/vitest.config.ts @@ -1,4 +1,4 @@ -import { readFileSync } from 'node:fs' +import { globSync, readFileSync } from 'node:fs' import { createRequire } from 'node:module' import { resolve } from 'node:path' import { normalizePath, transformWithOxc, type Plugin } from 'vite' @@ -9,12 +9,14 @@ import { UNIT_SETUP_FILES } from './scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs' import TimingSequencer from './scripts/ci/sharding/ci-unit-sequencer.mjs' +import { filesSafeToShareWorker } from './scripts/test-runtime/execution-policy/vitest-shared-worker-files.mjs' import RuntimeSequencer from './scripts/test-runtime/execution-policy/vitest-runtime-sequencer.mjs' import { getNodeRuntimeInclude } from './scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs' import { nodeRuntimePool } from './scripts/test-runtime/node-worker/vitest-node-runtime-pool' import { readRunFilters } from './scripts/test-runtime/execution-policy/vitest-run-filters.mjs' import { createWorkspaceSourceResolver } from './scripts/workspace/source-exports/workspace-source-exports.mjs' import { moduleCacheResolutionKey } from './scripts/test-runtime/module-cache/vitest-module-cache-resolution-key' +import { vitestReactCompiler } from './build-plugins/vitest-react-compiler' const nodeRuntimeInclude = process.versions.bun ? getNodeRuntimeInclude({ filters: readRunFilters() }) @@ -44,6 +46,7 @@ const transforms = { } } satisfies Plugin, ...(moduleCachePath ? [moduleCacheResolutionKey()] : []), + ...vitestReactCompiler(), { // Unit tests have no asset server; retain real catalog parsing through fetch(data:). name: 'locale-catalog-test-assets', @@ -121,7 +124,46 @@ const bunProject = { sequence: { groupOrder: 1 } } } -const projects = [...(process.versions.bun ? [bunProject] : []), nodeProject] +// Files whose state the per-file reset can undo share one worker's module cache instead of +// re-importing thousands of modules each. ORCA_VITEST_ISOLATE_EVERY_FILE=1 turns it off. +const runtimeProject = process.versions.bun ? bunProject : nodeProject +const nodeRuntimeFiles = new Set(nodeRuntimeInclude.map((file) => file.replaceAll('\\', '/'))) +const sharedWorkerFiles = + process.env.ORCA_VITEST_ISOLATE_EVERY_FILE === '1' + ? [] + : filesSafeToShareWorker( + process.cwd(), + globSync(UNIT_INCLUDE) + .map((file) => file.replaceAll('\\', '/')) + .filter((file) => !nodeRuntimeFiles.has(file)), + [ + { find: '@renderer', replacement: resolve('src/renderer/src') }, + { find: '@', replacement: resolve('src/renderer/src') } + ] + ) +const sharedProjects = + sharedWorkerFiles.length > 0 + ? [ + { + ...runtimeProject, + test: { + ...runtimeProject.test, + name: `${runtimeProject.test.name}-shared`, + include: sharedWorkerFiles, + isolate: false, + setupFiles: [ + ...runtimeProject.test.setupFiles, + resolve('config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs') + ] + } + } + ] + : [] +runtimeProject.test.exclude = [ + ...(runtimeProject.test.exclude ?? testOptions.exclude), + ...sharedWorkerFiles +] +const projects = [...(process.versions.bun ? [bunProject] : []), nodeProject, ...sharedProjects] export default defineConfig({ ...transforms, diff --git a/config/vitest.performance.config.ts b/config/vitest.performance.config.ts index 00967828447..a29424675e5 100644 --- a/config/vitest.performance.config.ts +++ b/config/vitest.performance.config.ts @@ -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', diff --git a/docs/agents-md-refs/protected-telemetry-milestones/remote-accepted-prompts.md b/docs/agents-md-refs/protected-telemetry-milestones/remote-accepted-prompts.md new file mode 100644 index 00000000000..d894ae0f1a5 --- /dev/null +++ b/docs/agents-md-refs/protected-telemetry-milestones/remote-accepted-prompts.md @@ -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. diff --git a/docs/assets/readme-downloads.svg b/docs/assets/readme-downloads.svg index 7cb6662503d..844b8971f54 100644 --- a/docs/assets/readme-downloads.svg +++ b/docs/assets/readme-downloads.svg @@ -1,5 +1,5 @@ - - downloads: 159m + + downloads: 160m @@ -15,7 +15,7 @@ downloads downloads - 159m - 159m + 160m + 160m diff --git a/docs/site/content/docs/agents/codex-hot-swap.mdx b/docs/site/content/docs/agents/codex-hot-swap.mdx index f80db35dd4a..bc66a569409 100644 --- a/docs/site/content/docs/agents/codex-hot-swap.mdx +++ b/docs/site/content/docs/agents/codex-hot-swap.mdx @@ -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. diff --git a/docs/site/content/docs/agents/codex.mdx b/docs/site/content/docs/agents/codex.mdx index 0cad8eef860..91175ac7d7b 100644 --- a/docs/site/content/docs/agents/codex.mdx +++ b/docs/site/content/docs/agents/codex.mdx @@ -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` diff --git a/docs/site/content/docs/remote-servers.mdx b/docs/site/content/docs/remote-servers.mdx index f402cc99f1d..866722a7fc5 100644 --- a/docs/site/content/docs/remote-servers.mdx +++ b/docs/site/content/docs/remote-servers.mdx @@ -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: diff --git a/docs/site/content/docs/settings.mdx b/docs/site/content/docs/settings.mdx index 1aecfa62b28..7d71631f1c5 100644 --- a/docs/site/content/docs/settings.mdx +++ b/docs/site/content/docs/settings.mdx @@ -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 diff --git a/docs/site/content/docs/telemetry.mdx b/docs/site/content/docs/telemetry.mdx index 21d1d016ff9..c7c503c9901 100644 --- a/docs/site/content/docs/telemetry.mdx +++ b/docs/site/content/docs/telemetry.mdx @@ -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. diff --git a/docs/styleguide/components.md b/docs/styleguide/components.md index 24e304a519b..46dbd89f118 100644 --- a/docs/styleguide/components.md +++ b/docs/styleguide/components.md @@ -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 `` 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 `` 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 `` 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 `` rather than baking the keys into the label string. The chips render correctly per platform; baked-in strings drift. diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 673eb8847e7..0a2e110aca1 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -15,6 +15,7 @@ import { createViteCacheRetentionPlugin } from './config/build-plugins/vite-cach import { MAIN_BUILD_ENTRY_POINTS } from './config/build-plugins/main-build-entry-points' import { createPlainNodeEntryGuardPlugin } from './config/build-plugins/plain-node-entry-guard' import { createDevServeConfig } from './config/build-plugins/dev-serve-config' +import { reactPluginOptions } from './config/build-plugins/react-compiler' import { resolveBuildSourceCommit } from './config/scripts/build-identity/build-source-commit.mjs' const BUNDLED_MAIN_DEPENDENCIES = new Set([ @@ -284,7 +285,7 @@ export const electronViteConfig: UserConfig = { } }, plugins: [ - react(), + react(reactPluginOptions()), tailwindcss(), createPdfjsViewerAssetsPlugin(), createViteCacheRetentionPlugin() diff --git a/mobile/app/h/[hostId]/source-control/[worktreeId].web.tsx b/mobile/app/h/[hostId]/source-control/[worktreeId].web.tsx index cef6989884d..18c7ccc3813 100644 --- a/mobile/app/h/[hostId]/source-control/[worktreeId].web.tsx +++ b/mobile/app/h/[hostId]/source-control/[worktreeId].web.tsx @@ -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 ( - ) + fun documentBridgeMessage(json: String) + fun documentExternalNavigation(url: String) +} + +/** One WebView and every fence on it, apart from React. The view hosts it and lays it out. */ +@SuppressLint("SetJavaScriptEnabled") +internal class MobileWebShellDocument(private val context: Context) { + var sink: MobileWebShellDocumentSink? = null + private var bridgeInstalled = false + private val bridgeGate = MobileWebShellBridgeGate() + // The page sends ready before native replies; volatile proxy state crosses interceptor/UI threads. + @Volatile private var replyProxy: JavaScriptReplyProxy? = null + private var applied: MobileWebShellAppliedProps? = null + private val loadState = MobileWebShellLoadStateMachine() + // Failure state crosses main-thread callbacks and Chromium’s background interceptor. + @Volatile private var documentFailed = false + @Volatile private var served: MobileWebShellServed? = null + private var blocker: ScriptHandler? = null + // Read by the interceptor thread when it reports a failed main-frame load. + @Volatile var webView: WebView? = createWebView() + private set + + /** Still showable: not torn down, and no terminal load failure or renderer loss. */ + val isUsable: Boolean get() = webView != null && !loadState.isTerminal + + /** Apply unordered props together; identical triples do not retry. Recovery requires a remount. */ + fun apply(generationDirectory: String, sessionId: String, bridgeEnabled: Boolean) { + val next = MobileWebShellAppliedProps(generationDirectory, sessionId, bridgeEnabled) + if (applied?.matches(next) == true) return + applied = next + documentFailed = false + loadState.reset() + val view = webView + if (view == null) { + // A dead renderer requires a remount; changed props must still report failure. + emit(loadState.rendererStillGone()) + return + } + view.stopLoading() + emit(loadState.started()) + + val origin = mobileWebShellOrigin(sessionId) + val host = mobileWebShellOriginHost(sessionId) + if (origin == null || host == null) { + // The private origin is the isolation primitive; a malformed session id leaves us without one. + failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE) + return + } + val loaded = MobileWebShellGeneration.load(generationDirectory) + if (loaded == null) { + failPropUpdate(MobileWebShellFailureReason.GENERATION_UNREADABLE) + return + } + blocker?.remove() + blocker = installMobileWebShellNetworkApiBlocker(view, origin) + if (blocker == null) { + failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE) + return + } + if (!applyBridgeListener(view, origin, bridgeEnabled)) { + failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE) + return + } + served = MobileWebShellServed(loaded, host) + view.visibility = View.VISIBLE + view.loadUrl("$origin/") + } + + /** Retire the old visible generation even when the replacement fails. */ + private fun failPropUpdate(reason: MobileWebShellFailureReason) { + // Remove the old listener: stopLoading leaves its same-origin document alive and able to rearm replies. + removeBridgeListener() + served = null + webView?.visibility = View.INVISIBLE + emit(loadState.failed(reason)) + } + + /** addWebMessageListener injects before scripts and enforces origins; false means unsupported provider. */ + private fun applyBridgeListener(view: WebView, origin: String, bridgeEnabled: Boolean): Boolean { + removeBridgeListener() + val outcome = mobileWebShellBridgeInstall( + bridgeEnabled, + WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER) + ) + if (outcome != MobileWebShellBridgeInstall.INSTALL) { + return outcome == MobileWebShellBridgeInstall.SKIP + } + return runCatching { + WebViewCompat.addWebMessageListener( + view, + MOBILE_WEB_SHELL_BRIDGE_OBJECT, + setOf(origin), + bridgeListener + ) + bridgeInstalled = true + }.isSuccess + } + + /** The one way the bridge goes away, so no disable path can leave a listener behind. */ + private fun removeBridgeListener() { + val view = webView + if (bridgeInstalled && view != null) { + WebViewCompat.removeWebMessageListener(view, MOBILE_WEB_SHELL_BRIDGE_OBJECT) + } + bridgeInstalled = false + replyProxy = null + } + + /** Chromium calls this on the UI thread, which is also the only thread that may reply. */ + private val bridgeListener = WebViewCompat.WebMessageListener { + _, message, _, isMainFrame, proxy -> + val isStringMessage = message.type == WebMessageCompat.TYPE_STRING + val json = if (isStringMessage) message.data else null + if ( + acceptsMobileWebShellBridgeFrame( + isMainFrame, + isStringMessage, + loadState.hasCommittedDocument + ) && json != null && + bridgeGate.accepts(json.toByteArray(Charsets.UTF_8).size) + ) { + replyProxy = proxy + sink?.documentBridgeMessage(json) + } + } + + /** Throw so a host chunking bug rejects rather than leaving its request unsettled. */ + fun postBridgeMessage(json: String) { + val proxy = replyProxy ?: throw MobileWebShellBridgeUnavailableException() + val byteCount = json.toByteArray(Charsets.UTF_8).size + if (!acceptsMobileWebShellBridgeByteCount(byteCount)) { + throw MobileWebShellBridgeMessageTooLargeException(byteCount) + } + proxy.postMessage(json) + } + + /** A frame from the shell itself, to the frame that spoke. */ + fun postHostFrame(json: String) { + replyProxy?.postMessage(json) + } + + /** The view's attach and detach: off-window, the page reads hidden, as a buried WKWebView does on iOS. */ + fun resume() { + webView?.onResume() + } + + fun pause() { + webView?.onPause() + } + + /** The view is done with it, or onRenderProcessGone. */ + fun destroyWebView() { + val view = webView ?: return + removeBridgeListener() + loadState.documentEnded() + webView = null + blocker?.remove() + blocker = null + served = null + documentFailed = false + view.stopLoading() + (view.parent as? ViewGroup)?.removeView(view) + view.destroy() + } + + // Keep explicit settings for the Chromium 83 floor, even where newer WebViews ignore deprecated options. + // B4 requires device proofs: no network, persistent state, file/content access, cleartext or navigation escape. + @Suppress("DEPRECATION") + private fun createWebView(): WebView { + val view = MobileWebShellSelectionView(context) + view.setBackgroundColor(Color.TRANSPARENT) + view.settings.apply { + javaScriptEnabled = true + domStorageEnabled = false + databaseEnabled = false + allowFileAccess = false + allowFileAccessFromFileURLs = false + allowUniversalAccessFromFileURLs = false + allowContentAccess = false + javaScriptCanOpenWindowsAutomatically = false + setSupportMultipleWindows(false) + mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW + cacheMode = WebSettings.LOAD_NO_CACHE + blockNetworkLoads = true + mediaPlaybackRequiresUserGesture = true + setGeolocationEnabled(false) + } + // clearCache(true) is process-global, including terminals; use per-view LOAD_NO_CACHE and no-store. + view.webViewClient = ShellWebViewClient() + view.webChromeClient = object : WebChromeClient() { + override fun onCreateWindow( + view: WebView?, + isDialog: Boolean, + isUserGesture: Boolean, + resultMsg: Message? + ): Boolean = false + } + view.setDownloadListener { _, _, _, _, _ -> } + // Replace WebView inset handling on P–R/S+; forward zeroed insets for S+ parity. + ViewCompat.setOnApplyWindowInsetsListener(view) { target, insets -> + ViewCompat.onApplyWindowInsets(target, insetsForShellPage(insets)) + } + return view + } + + private fun emit(emission: MobileWebShellLoadEmission?) { + if (emission != null) sink?.documentLoadState(emission.toPayload()) + } + + /** Post hiding past Chromium’s error-document commit; interception may also run off the main thread. */ + private fun reportDocumentFailure() { + replyProxy = null + // Drop replies synchronously before Chromium’s error document commits and the posted hide runs. + loadState.documentEnded() + // Set before posting: intervening onPageFinished must not restore ready or expose the error page. + documentFailed = true + val epoch = loadState.epoch + // The WebView's queue, like the view it sits in: a detached document reports once it attaches. + webView?.post { + if (!documentFailed) return@post + val emission = loadState.failedDuring( + epoch, + MobileWebShellFailureReason.DOCUMENT_LOAD_FAILED + ) ?: return@post + webView?.visibility = View.INVISIBLE + emit(emission) + } + } + + private fun isDocumentUrl(url: Uri): Boolean { + val host = served?.originHost ?: return false + return resolveMobileWebShellRequestPath(requestParts(url), host) == "/" + } + + private fun requestParts( + url: Uri, + method: String = "GET", + hasRangeHeader: Boolean = false + ): MobileWebShellRequestParts = MobileWebShellRequestParts( + method = method, + hasRangeHeader = hasRangeHeader, + scheme = url.scheme, + host = url.host, + port = url.port, + userInfo = url.userInfo, + query = url.query, + fragment = url.fragment, + encodedPath = url.encodedPath, + urlLength = url.toString().length + ) + + private fun serveRequest(request: WebResourceRequest): WebResourceResponse? { + val current = served ?: return null + val parts = requestParts( + request.url, + method = request.method, + hasRangeHeader = request.requestHeaders.keys.any { it.equals("Range", ignoreCase = true) } + ) + val path = resolveMobileWebShellRequestPath(parts, current.originHost) ?: return null + val asset = current.generation.entries[path] ?: return null + val bytes = runCatching { asset.file.readBytes() }.getOrNull() ?: return null + val headers = mobileWebShellResponseHeaders(path, bytes.size) + val (mimeType, charset) = splitMobileWebShellContentType(asset.contentType) + return WebResourceResponse(mimeType, charset, 200, "OK", headers, ByteArrayInputStream(bytes)) + } + + private fun refusedResponse(): WebResourceResponse = WebResourceResponse( + MOBILE_WEB_SHELL_REFUSAL_MIME_TYPE, + MOBILE_WEB_SHELL_REFUSAL_CHARSET, + MOBILE_WEB_SHELL_REFUSAL_STATUS, + MOBILE_WEB_SHELL_REFUSAL_REASON, + MOBILE_WEB_SHELL_REFUSAL_HEADERS, + ByteArrayInputStream(mobileWebShellRefusalBody()) + ) + + private inner class ShellWebViewClient : WebViewClient() { + /** Never null, so no request can fall through to the network. */ + override fun shouldInterceptRequest( + view: WebView, + request: WebResourceRequest + ): WebResourceResponse { + val response = serveRequest(request) + if (response != null) return response + if (request.isForMainFrame) reportDocumentFailure() + return refusedResponse() + } + + override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { + // hasGesture gates only opener offers: human requests may omit it and subframes can target top without it. + val verdict = mobileWebShellNavigationVerdict( + url = request.url?.toString(), + isForMainFrame = request.isForMainFrame, + // Not reported here, unlike WKNavigationAction.sourceFrame on iOS. + isFromSubframe = false, + isDocumentUrl = !mobileWebShellDropsNavigation( + requestParts(request.url), + served?.originHost, + request.isForMainFrame + ), + // loadUrl bypasses this callback by WebViewClient contract; no callback action is our own load. + isShellLoad = false, + hasGesture = request.hasGesture(), + isDownload = false + ) + if (verdict is MobileWebShellNavigationVerdict.CancelAndOffer) { + sink?.documentExternalNavigation(verdict.url) + } + return verdict !is MobileWebShellNavigationVerdict.Allow + } + + override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) { + // Discard the replaced document’s reply proxy; the next page must send ready. + replyProxy = null + loadState.documentEnded() + if (documentFailed || !isDocumentUrl(Uri.parse(url))) return + // Arm at commit before page script runs. + loadState.committed() + emit(loadState.started()) + } + + // history.replaceState changes the document path before finish; commit state identifies the load. + override fun onPageFinished(view: WebView, url: String) { + if (documentFailed || !loadState.hasCommittedDocument) return + view.visibility = View.VISIBLE + // Remove history so the page cannot return to a replaced document. + view.clearHistory() + emit(loadState.finished()) + } + + override fun onReceivedError( + view: WebView, + request: WebResourceRequest, + error: WebResourceError + ) { + if (request.isForMainFrame) reportDocumentFailure() + } + + override fun onReceivedHttpError( + view: WebView, + request: WebResourceRequest, + errorResponse: WebResourceResponse + ) { + if (request.isForMainFrame) reportDocumentFailure() + } + + /** Return true to avoid killing the app; destroy the dead WebView and leave retry policy to the caller. */ + override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean { + // Android ends every WebView's renderer together; off-screen or low-memory losses are the OS's doing, not the page's. + val host = view.parent as? View ?: view + val background = !host.isShown || host.windowVisibility != View.VISIBLE + destroyWebView() + emit(loadState.rendererGone(background, detail.didCrash())) + return true + } + } +} + +internal class MobileWebShellBridgeUnavailableException : + CodedException("The mobile web shell bridge is not installed on this view") + +internal class MobileWebShellBridgeMessageTooLargeException(byteCount: Int) : CodedException( + "A bridge message of $byteCount bytes exceeds the " + + "$MOBILE_WEB_SHELL_BRIDGE_MAX_MESSAGE_BYTES byte cap" +) + +/** The shell already pads bars/keyboard; zero (never consume) insets to prevent WebView M144+ bar and M139+ IME double-padding. */ +private fun insetsForShellPage(insets: WindowInsetsCompat): WindowInsetsCompat = + WindowInsetsCompat.Builder(insets) + .setInsets(SHELL_OWNED_INSET_TYPES, Insets.NONE) + .build() + +private val SHELL_OWNED_INSET_TYPES = + WindowInsetsCompat.Type.systemBars() or + WindowInsetsCompat.Type.displayCutout() or + WindowInsetsCompat.Type.ime() diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt index 493e50b9b5b..93737f6dd66 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt @@ -26,6 +26,7 @@ internal data class MobileWebShellLoadEmission( /** Failure is terminal and duplicate reports are dropped: late error-document/rule-list callbacks must never restore ready. Cross-thread readers require volatile state. */ internal class MobileWebShellLoadStateMachine { private var terminal = false + val isTerminal: Boolean get() = terminal private var last: MobileWebShellLoadEmission? = null private var rendererLoss: Pair? = null diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellSparePool.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellSparePool.kt new file mode 100644 index 00000000000..791dbba21cf --- /dev/null +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellSparePool.kt @@ -0,0 +1,169 @@ +package expo.modules.orcamobilewebshell + +import android.app.Activity +import android.app.ActivityManager +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import java.util.Collections +import java.util.WeakHashMap + +/** More than 3 GiB can only come from a phone with 4 GB or more; those report about 3.5 to 3.9 GiB. */ +private const val MINIMUM_TOTAL_MEMORY_BYTES = 3L shl 30 + +/** A claim is adopted on the claiming screen's first commit; this only bounds a screen that never mounts. */ +private const val CLAIM_EXPIRY_MS = 10_000L + +/** Holds a parked WebView under the app's content: invisible, untouchable and out of accessibility. */ +private class MobileWebShellParking(context: Context) : FrameLayout(context) { + init { + alpha = 0f + isFocusable = false + descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS + importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS + } + + override fun dispatchTouchEvent(event: MotionEvent): Boolean = false +} + +/** + * A booted document waiting for a screen. It keeps what the page reported, and the page's ready, for + * the view that adopts it: a parked page stops asking for init, so its ready is answered from here. + */ +internal class MobileWebShellSpare( + activity: Activity, + val directory: String, + val sessionId: String +) : MobileWebShellDocumentSink { + val document = MobileWebShellDocument(activity) + val parking: ViewGroup = MobileWebShellParking(activity) + private val loadStates = mutableListOf>() + private var ready: String? = null + + init { + document.sink = this + } + + override fun documentLoadState(payload: Map) { + 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 = + 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 diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellView.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellView.kt index 32f824dff4c..506c6e03202 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellView.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellView.kt @@ -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>() private val onBridgeMessage by EventDispatcher>() private val onExternalNavigation by EventDispatcher>() @@ -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) = 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() diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt index c3d036b0416..81e5a16133a 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt @@ -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() diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellBridge.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellBridge.swift index 6a8fb35df39..f3d6ebb5cb4 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellBridge.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellBridge.swift @@ -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 diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellDocument.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellDocument.swift new file mode 100644 index 00000000000..ae372997bf4 --- /dev/null +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellDocument.swift @@ -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 = [] + + 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, + @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, + @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() + 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 + } +} diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellLoadState.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellLoadState.swift index 5fb8544ef73..b3e1fef7005 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellLoadState.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellLoadState.swift @@ -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. diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellSparePool.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellSparePool.swift new file mode 100644 index 00000000000..92e9ff89ffc --- /dev/null +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellSparePool.swift @@ -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.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) + } +} diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift index d341acab6bc..91aa028d7fa 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift @@ -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 = [] - - 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, - @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, - @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() - 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]) } } diff --git a/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift b/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift index 0f3bcaa5ca7..ed5e81770d1 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift @@ -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. diff --git a/mobile/modules/orca-mobile-web-shell/src/spare-document.ts b/mobile/modules/orca-mobile-web-shell/src/spare-document.ts new file mode 100644 index 00000000000..ca9ba5c1f85 --- /dev/null +++ b/mobile/modules/orca-mobile-web-shell/src/spare-document.ts @@ -0,0 +1,27 @@ +import { requireOptionalNativeModule } from 'expo-modules-core' + +type SpareDocumentModule = { + prepareSpareDocument?: (directory: string, sessionId: string) => Promise + claimSpareDocument?: (directory: string) => Promise + discardSpareDocument?: () => Promise +} + +// A binary built before the spare existed has the module without these functions. +const spareModule = (): SpareDocumentModule | null => + requireOptionalNativeModule('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 { + 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 { + return (await spareModule()?.claimSpareDocument?.(directory)) ?? null +} + +export async function discardSpareDocument(): Promise { + await spareModule()?.discardSpareDocument?.() +} diff --git a/mobile/rpc-foundation/goldens/settings-repo-metadata-refuse-after-data.json b/mobile/rpc-foundation/goldens/settings-repo-metadata-refuse-after-data.json index 3b737599abd..1ccd86c7a3e 100644 --- a/mobile/rpc-foundation/goldens/settings-repo-metadata-refuse-after-data.json +++ b/mobile/rpc-foundation/goldens/settings-repo-metadata-refuse-after-data.json @@ -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" ] } } diff --git a/mobile/scripts/check-tests-typecheck-ratchet.mjs b/mobile/scripts/check-tests-typecheck-ratchet.mjs index 8066911e602..b4545dc56ef 100644 --- a/mobile/scripts/check-tests-typecheck-ratchet.mjs +++ b/mobile/scripts/check-tests-typecheck-ratchet.mjs @@ -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('\\', '/') diff --git a/mobile/scripts/check-tests-typecheck-ratchet.test.ts b/mobile/scripts/check-tests-typecheck-ratchet.test.ts index e0d100035c6..cb326066f34 100644 --- a/mobile/scripts/check-tests-typecheck-ratchet.test.ts +++ b/mobile/scripts/check-tests-typecheck-ratchet.test.ts @@ -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( diff --git a/mobile/src/accounts/mobile-accounts-screen-reset-credit.test.ts b/mobile/src/accounts/mobile-accounts-screen-reset-credit.test.ts deleted file mode 100644 index 409b2896269..00000000000 --- a/mobile/src/accounts/mobile-accounts-screen-reset-credit.test.ts +++ /dev/null @@ -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 { - 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()) - }) -}) diff --git a/mobile/src/agent-history/agent-history-scope-paths.test.ts b/mobile/src/agent-history/agent-history-scope-paths.test.ts deleted file mode 100644 index 018129e9013..00000000000 --- a/mobile/src/agent-history/agent-history-scope-paths.test.ts +++ /dev/null @@ -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() - }) -}) diff --git a/mobile/src/app-update/app-update-checker.test.ts b/mobile/src/app-update/app-update-checker.test.ts index 1652654f393..6cfa6ab6e16 100644 --- a/mobile/src/app-update/app-update-checker.test.ts +++ b/mobile/src/app-update/app-update-checker.test.ts @@ -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((resolve) => { diff --git a/mobile/src/browser/browser-screencast-budget-at-the-shell.test.ts b/mobile/src/browser/browser-screencast-budget-at-the-shell.test.ts deleted file mode 100644 index dfceecbc797..00000000000 --- a/mobile/src/browser/browser-screencast-budget-at-the-shell.test.ts +++ /dev/null @@ -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) - }) -}) diff --git a/mobile/src/browser/browser-screencast-request.web.test.ts b/mobile/src/browser/browser-screencast-request.web.test.ts deleted file mode 100644 index cbf56338cea..00000000000 --- a/mobile/src/browser/browser-screencast-request.web.test.ts +++ /dev/null @@ -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[] = [] - 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) - }) - } -}) diff --git a/mobile/src/browser/browser-screencast-request.web.ts b/mobile/src/browser/browser-screencast-request.web.ts index 30dfe33a956..dacb72fb90e 100644 --- a/mobile/src/browser/browser-screencast-request.web.ts +++ b/mobile/src/browser/browser-screencast-request.web.ts @@ -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, diff --git a/mobile/src/browser/browser-url.test.ts b/mobile/src/browser/browser-url.test.ts deleted file mode 100644 index a0d2a7f11f4..00000000000 --- a/mobile/src/browser/browser-url.test.ts +++ /dev/null @@ -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' - ) - }) -}) diff --git a/mobile/src/browser/mobile-browser-view-mode-state.test.ts b/mobile/src/browser/mobile-browser-view-mode-state.test.ts deleted file mode 100644 index 495955a3cc2..00000000000 --- a/mobile/src/browser/mobile-browser-view-mode-state.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import { - clearMobileBrowserViewModeState, - getInitialMobileBrowserViewMode, - saveMobileBrowserViewMode -} from './mobile-browser-view-mode-state' - -describe('mobile browser view mode state', () => { - beforeEach(() => { - clearMobileBrowserViewModeState() - }) - - it('defaults each browser page to web view', () => { - expect(getInitialMobileBrowserViewMode('worktree-1', 'page-1')).toBe('web') - expect(getInitialMobileBrowserViewMode('worktree-1', null)).toBe('web') - }) - - it('defaults local HTML reports to mobile view', () => { - expect( - getInitialMobileBrowserViewMode( - 'folder:workspace-1', - 'page-1', - 'file:///Users/me/report%20one.HTML?generated=1' - ) - ).toBe('mobile') - expect( - getInitialMobileBrowserViewMode('worktree-1', 'page-2', 'file:///C:/Users/me/report.htm') - ).toBe('mobile') - }) - - it('keeps remote HTML URLs and non-HTML files in web view', () => { - expect( - getInitialMobileBrowserViewMode('worktree-1', 'page-1', 'https://example.com/report.html') - ).toBe('web') - expect(getInitialMobileBrowserViewMode('worktree-1', 'page-2', 'file:///repo/notes.txt')).toBe( - 'web' - ) - }) - - it('restores the last mode for the same browser page after remount', () => { - saveMobileBrowserViewMode('worktree-1', 'page-1', 'mobile') - - expect(getInitialMobileBrowserViewMode('worktree-1', 'page-1')).toBe('mobile') - expect(getInitialMobileBrowserViewMode('worktree-1', 'page-2')).toBe('web') - expect(getInitialMobileBrowserViewMode('worktree-2', 'page-1')).toBe('web') - }) - - it('preserves an explicit web choice for a local HTML report', () => { - saveMobileBrowserViewMode('worktree-1', 'page-1', 'web') - - expect( - getInitialMobileBrowserViewMode('worktree-1', 'page-1', 'file:///repo/report.html') - ).toBe('web') - }) -}) diff --git a/mobile/src/components/DragReorderList.test.tsx b/mobile/src/components/DragReorderList.test.tsx index bd3cb5aeb07..defe697b10a 100644 --- a/mobile/src/components/DragReorderList.test.tsx +++ b/mobile/src/components/DragReorderList.test.tsx @@ -25,17 +25,6 @@ describe('drag completion and cancellation', () => { await act(async () => fixture.root.unmount()) }) - it('commits the moved order once on a successful drop', async () => { - const fixture = await mounted() - await act(async () => { - fixture.gesture.start!({ absoluteY: 100, translationY: 0 }, true) - fixture.gesture.update!({ absoluteY: 180, translationY: 80 }, true) - fixture.gesture.finalize!({ absoluteY: 180, translationY: 80 }, true) - }) - expect(fixture.onReorder.mock.calls).toEqual([[['b', 'a']]]) - await act(async () => fixture.root.unmount()) - }) - it('does not write after a failed activation or an unchanged drop', async () => { const fixture = await mounted() await act(async () => { @@ -286,56 +275,3 @@ it('keeps measured rows still on hold, restores cancellation, and drops by moved expect(move).toHaveBeenCalledExactlyOnceWith({ movedId: 'a', afterId: 'c' }) await act(async () => root!.unmount()) }) - -it.each([100, 1000])( - 'bounds accessibility work for %i rows while excluded slots stay fixed', - async (count) => { - const ids = Array.from({ length: count }, (_, at) => - at === 1 ? 'fixed' : at === 2 ? 'busy' : `row-${at}` - ) - let keyReads = 0 - let membership = 0 - const onMove = vi.fn() - const onReorder = vi.fn() - function Harness({ items = ids }: { items?: string[] }) { - return createElement(DragReorderList, { - items, - itemKey: (id) => { - keyReads++ - return id - }, - canMove: (id) => { - membership++ - return id !== 'fixed' && id !== 'busy' - }, - rowHeight: 56, - renderRow: (id, handle) => createElement('Text', null, id, handle), - onMove, - onReorder, - scrollRef: useAnimatedRef(), - scrollOffsetY: useSharedValue(0), - scrollContentHeight: useSharedValue(count * 56) - }) - } - let root: ReturnType - await act(async () => { - root = create(createElement(Harness)) - }) - const first = root!.root.findAll( - (node) => node.type === Animated.View && node.props.onAccessibilityAction - )[0]! - const accessibilityAction = first.props.onAccessibilityAction - keyReads = membership = 0 - await act(async () => accessibilityAction({ nativeEvent: { actionName: 'moveUp' } })) - expect(onMove).not.toHaveBeenCalled() - await act(async () => accessibilityAction({ nativeEvent: { actionName: 'moveDown' } })) - expect(keyReads).toBeLessThanOrEqual(3 * count) - expect(membership).toBeLessThanOrEqual(3 * count) - expect(onReorder.mock.calls[0]![0].slice(0, 4)).toEqual(['row-3', 'fixed', 'busy', 'row-0']) - expect(onMove).toHaveBeenCalledExactlyOnceWith({ movedId: 'row-0', beforeId: 'row-4' }) - await act(async () => root!.update(createElement(Harness, { items: ids.slice(1) }))) - await act(async () => accessibilityAction({ nativeEvent: { actionName: 'moveDown' } })) - expect(onMove).toHaveBeenCalledOnce() - await act(async () => root!.unmount()) - } -) diff --git a/mobile/src/components/HostRouteNoticeBanner.test.tsx b/mobile/src/components/HostRouteNoticeBanner.test.tsx deleted file mode 100644 index 7726ba372a9..00000000000 --- a/mobile/src/components/HostRouteNoticeBanner.test.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { createElement, type ReactNode } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' - -vi.mock('react-native', async () => { - const React = await import('react') - return { - Pressable: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('Pressable', props, children), - Text: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('Text', props, children), - View: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('View', props, children), - StyleSheet: { create: (styles: unknown) => styles } - } -}) -vi.mock('lucide-react-native', () => ({ X: 'X' })) - -import { HostRouteNoticeBanner } from './HostRouteNoticeBanner' - -// Announce inserted banner because list reader may be below it; failure interrupts, bounced-route context stays polite so urgency retains meaning. -describe('the host route notice banner announces itself', () => { - let renderer: ReactTestRenderer | null = null - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - }) - - function banner(tone?: 'notice' | 'failure') { - act(() => { - renderer = create( - createElement(HostRouteNoticeBanner, { - message: 'Nothing happened', - tone, - onDismiss: () => {} - }) - ) - }) - if (renderer === null) { - throw new Error('the banner did not render') - } - // Match host name to avoid ElementType cast for arbitrary RN strings; first match is banner root carrying tested props. - return renderer.root.findAll((node) => String(node.type) === 'View')[0] - } - - it('interrupts for a failure, which is an action that did not happen', () => { - const root = banner('failure') - expect(root.props.accessibilityRole).toBe('alert') - expect(root.props.accessibilityLiveRegion).toBe('assertive') - }) - - it('waits its turn for a notice, which is context rather than a refusal', () => { - const root = banner('notice') - expect(root.props.accessibilityLiveRegion).toBe('polite') - // No alert role: nothing here failed, and an alert is what the tone above is for. - expect(root.props.accessibilityRole).toBeUndefined() - }) - - it('treats the default tone as the notice one, which is what the route caller passes', () => { - const root = banner(undefined) - expect(root.props.accessibilityLiveRegion).toBe('polite') - expect(root.props.accessibilityRole).toBeUndefined() - }) -}) diff --git a/mobile/src/components/MobileMarkdown.rendering.test.tsx b/mobile/src/components/MobileMarkdown.rendering.test.tsx deleted file mode 100644 index b01e4830d69..00000000000 --- a/mobile/src/components/MobileMarkdown.rendering.test.tsx +++ /dev/null @@ -1,115 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { MobileMarkdown } from './MobileMarkdown' -import { MarkdownLinkHandlerContext } from './markdown-link-handler' - -const openURL = vi.fn((_url: string) => Promise.resolve()) - -vi.mock('react-native', () => ({ - Linking: { openURL: (url: string) => openURL(url) }, - Platform: { OS: 'ios' }, - Pressable: 'Pressable', - ScrollView: 'ScrollView', - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, - Text: 'Text', - View: 'View' -})) -vi.mock('./pr-sidebar/MermaidDiagram', () => ({ MermaidDiagram: 'MermaidDiagram' })) -vi.mock('./MobileSourceCopyButton', () => ({ MobileSourceCopyButton: 'MobileSourceCopyButton' })) - -let renderer: ReactTestRenderer | null = null - -afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - openURL.mockClear() -}) - -function render(content: string, growing = false): ReactTestRenderer { - act(() => { - renderer = create(createElement(MobileMarkdown, { content, growing })) - }) - return renderer! -} - -function flatten(node: ReactTestInstance | string): string { - return typeof node === 'string' ? node : node.children.map(flatten).join('') -} - -const isText = (node: ReactTestInstance): boolean => String(node.type) === 'Text' - -/** Every Text not inside another Text, in reading order: what the reader sees, block by block. */ -function texts(tree: ReactTestRenderer): string[] { - return tree.root - .findAll((node) => isText(node) && !(node.parent && hasTextAncestor(node.parent))) - .map(flatten) -} - -function hasTextAncestor(node: ReactTestInstance): boolean { - return isText(node) || (node.parent !== null && hasTextAncestor(node.parent)) -} - -function press(tree: ReactTestRenderer, label: string): void { - const target = tree.root.find( - (node) => isText(node) && typeof node.props.onPress === 'function' && flatten(node) === label - ) - act(() => target.props.onPress()) -} - -describe('MobileMarkdown rendering', () => { - it('C21: closes open markup while a reply grows, and never links a half-written address', () => { - expect(texts(render('2 * 3 is six.\n\nRead **src/main/ses', true))).toEqual([ - '2 * 3 is six.', - 'Read src/main/ses' - ]) - const tree = render('See [config loader](https://exa', true) - expect(texts(tree)).toEqual(['See config loader']) - expect(tree.root.findAll((node) => typeof node.props.onPress === 'function')).toEqual([]) - }) - - it('hands a web link to the screen that offers choices; mail and file links still open directly', () => { - const onOpenLink = vi.fn() - const onOpenFile = vi.fn() - act(() => { - renderer = create( - createElement( - MarkdownLinkHandlerContext.Provider, - { value: onOpenLink }, - createElement(MobileMarkdown, { - content: '[docs](https://x.com/a), [mail](mailto:a@x.com) and [file](src/a.ts)', - onOpenFile - }) - ) - ) - }) - press(renderer!, 'docs') - press(renderer!, 'mail') - press(renderer!, 'file') - - expect(onOpenLink).toHaveBeenCalledTimes(1) - expect(onOpenLink).toHaveBeenCalledWith('https://x.com/a') - expect(openURL).toHaveBeenCalledTimes(1) - expect(openURL).toHaveBeenCalledWith('mailto:a@x.com') - expect(onOpenFile).toHaveBeenCalledWith('src/a.ts') - }) -}) - -it('draws every image in a paragraph and keeps the text around them, leaving declined images as links', () => { - const renderImage = vi.fn((href: string, alt: string) => - href.startsWith('/') ? createElement('View', { testID: `image:${href}`, alt }) : null - ) - act(() => { - renderer = create( - createElement(MobileMarkdown, { - content: - 'Before and after: \n![one](/tmp/a.png)\n![two](/tmp/b.png)\n![three](rel.png) done', - renderImage - }) - ) - }) - const images = renderer!.root.findAll((node) => String(node.props.testID).startsWith('image:')) - expect(images.map((node) => node.props.testID)).toEqual(['image:/tmp/a.png', 'image:/tmp/b.png']) - expect(texts(renderer!)).toEqual(['Before and after:', 'three done']) -}) diff --git a/mobile/src/components/MobileMarkdown.test.ts b/mobile/src/components/MobileMarkdown.test.ts index 455c05f153d..1eade1f67f5 100644 --- a/mobile/src/components/MobileMarkdown.test.ts +++ b/mobile/src/components/MobileMarkdown.test.ts @@ -1,22 +1,6 @@ import { describe, expect, it } from 'vitest' -import { isMobileMermaidLanguage } from './mobile-mermaid-language' import { normalizeMobileMarkdownPreviewHtml } from './mobile-markdown-preview-html' -describe('isMobileMermaidLanguage', () => { - it('matches mermaid case-insensitively after trim', () => { - expect(isMobileMermaidLanguage('mermaid')).toBe(true) - expect(isMobileMermaidLanguage('Mermaid')).toBe(true) - expect(isMobileMermaidLanguage(' MERMAID ')).toBe(true) - }) - - it('rejects non-mermaid languages and missing language', () => { - expect(isMobileMermaidLanguage(undefined)).toBe(false) - expect(isMobileMermaidLanguage('')).toBe(false) - expect(isMobileMermaidLanguage('ts')).toBe(false) - expect(isMobileMermaidLanguage('mermaidx')).toBe(false) - }) -}) - describe('normalizeMobileMarkdownPreviewHtml', () => { it('normalizes common README HTML into readable Markdown preview text', () => { const normalized = normalizeMobileMarkdownPreviewHtml(` diff --git a/mobile/src/components/MobileRepoIcon.test.tsx b/mobile/src/components/MobileRepoIcon.test.tsx deleted file mode 100644 index 09355287677..00000000000 --- a/mobile/src/components/MobileRepoIcon.test.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { Folder } from 'lucide-react-native' -import { createElement } from 'react' -import { Image } from 'react-native' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { MobileRepoIcon } from './MobileRepoIcon' - -vi.mock('react-native', () => ({ - Image: 'Image', - StyleSheet: { create: (styles: T) => styles }, - Text: 'Text', - View: 'View' -})) -// Each icon renders as an element named after it. -vi.mock( - 'lucide-react-native', - () => new Proxy({}, { has: () => true, get: (_, name) => String(name) }) -) -vi.mock('../theme/use-mobile-color-scheme', () => ({ useMobileColorScheme: () => 'dark' })) - -let renderer: ReactTestRenderer | null = null -afterEach(() => { - act(() => renderer?.unmount()) - renderer = null -}) - -function imageIcon(src: string) { - return createElement(MobileRepoIcon, { repoIcon: { type: 'image', src, label: 'owner/repo' } }) -} - -describe('MobileRepoIcon', () => { - it('shows the folder after an image fails, and tries a changed image again', () => { - act(() => { - renderer = create(imageIcon('https://github.com/owner.png?size=64')) - }) - act(() => renderer!.root.findByType(Image).props.onError()) - expect(renderer!.root.findAllByType(Image)).toHaveLength(0) - expect(renderer!.root.findAllByType(Folder)).toHaveLength(1) - - act(() => renderer!.update(imageIcon('data:image/png;base64,AAAA'))) - expect(renderer!.root.findByType(Image).props.source).toEqual({ - uri: 'data:image/png;base64,AAAA' - }) - }) -}) diff --git a/mobile/src/components/MobileRichMarkdownToolbar.test.tsx b/mobile/src/components/MobileRichMarkdownToolbar.test.tsx deleted file mode 100644 index 6cdbcbd498a..00000000000 --- a/mobile/src/components/MobileRichMarkdownToolbar.test.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' - -vi.mock('react-native', () => ({ - Pressable: 'Pressable', - ScrollView: 'ScrollView', - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, - View: 'View' -})) - -vi.mock('lucide-react-native', () => ({ - Bold: 'Bold', - Code2: 'Code2', - FileCode2: 'FileCode2', - Heading1: 'Heading1', - Heading2: 'Heading2', - Heading3: 'Heading3', - ImageIcon: 'ImageIcon', - Italic: 'Italic', - Link: 'Link', - List: 'List', - ListOrdered: 'ListOrdered', - ListTodo: 'ListTodo', - Pilcrow: 'Pilcrow', - Quote: 'Quote', - Strikethrough: 'Strikethrough' -})) - -import { MobileRichMarkdownToolbar } from './MobileRichMarkdownToolbar' -import type { MobileRichMarkdownCommand } from './mobile-rich-markdown-editor-contract' - -let renderer: ReactTestRenderer | null = null - -afterEach(() => { - act(() => renderer?.unmount()) - renderer = null -}) - -function render(editable: boolean, onCommand: (command: MobileRichMarkdownCommand) => void) { - act(() => { - renderer = create(createElement(MobileRichMarkdownToolbar, { editable, onCommand })) - }) - return renderer!.root.findAll((node) => String(node.type) === 'Pressable') -} - -describe('the rich Markdown toolbar', () => { - it('routes named controls to their editor commands', () => { - const onCommand = vi.fn() - const buttons = render(true, onCommand) - for (const [label, command] of [ - ['Bold', 'bold'], - ['Link', 'link'], - ['Inline code', 'inlineCode'] - ] as const) { - onCommand.mockClear() - const button = buttons.find((candidate) => candidate.props.accessibilityLabel === label) - expect(button).toBeDefined() - act(() => button!.props.onPress()) - expect(onCommand.mock.calls).toEqual([[command]]) - } - }) - - it('disables every button against a document that cannot be edited', () => { - const buttons = render(false, vi.fn()) - expect(buttons.filter((button) => button.props.disabled !== true)).toEqual([]) - }) -}) diff --git a/mobile/src/components/ProtocolBlockScreen.test.ts b/mobile/src/components/ProtocolBlockScreen.test.ts index f8560e28cbe..3b79cc9543e 100644 --- a/mobile/src/components/ProtocolBlockScreen.test.ts +++ b/mobile/src/components/ProtocolBlockScreen.test.ts @@ -72,34 +72,6 @@ describe('ProtocolBlockScreen', () => { renderer = null }) - // Why: the protocol wall shipped before the bundle one; its copy is what users already see. - it('keeps the existing protocol wall rendering unchanged', () => { - const mobile = render({ - kind: 'blocked', - reason: 'mobile-too-old', - desktopVersion: 5, - requiredMobileVersion: 99 - }) - expect(mobile).toContain('Update Orca Mobile') - expect(mobile).toContain( - 'This desktop needs a newer Orca Mobile app. Update Orca Mobile from the App Store, then try this host again.' - ) - expect(mobile).toContain('Open App Store') - act(() => renderer?.unmount()) - - const desktop = render({ - kind: 'blocked', - reason: 'desktop-too-old', - desktopVersion: 0, - requiredDesktopVersion: 2 - }) - expect(desktop).toContain('Update Orca on your computer') - expect(desktop).toContain( - 'This paired desktop app is too old for your current Orca Mobile app. Update Orca on your computer, then try this host again.' - ) - expect(desktop).toContain('Open GitHub Releases') - }) - it('tells a host without a bundle, or without this screen, the desktop is too old', () => { for (const reason of ['bundle-unavailable', 'page-route-unlisted'] as const) { const output = render({ kind: 'blocked', reason }) @@ -112,12 +84,6 @@ describe('ProtocolBlockScreen', () => { } }) - it('sends a screen that needs a grant this app lacks to the mobile update', () => { - const output = render({ kind: 'blocked', reason: 'page-route-grant-missing' }) - expect(output).toContain('Update Orca Mobile') - expect(output).toContain("This desktop's mobile workspace needs a newer Orca Mobile app.") - }) - it('sends an unknown manifest schema to the mobile update', () => { const output = render({ kind: 'blocked', @@ -169,44 +135,13 @@ describe('ProtocolBlockScreen', () => { expect(primaryActionUrl()).toBe(RELEASES_URL) }) - it('sends a desktop whose page is older than this shell to the desktop update', () => { - const output = render({ - kind: 'blocked', - reason: 'bundle-incompatible', - side: 'desktop', - pageVersion: 0, - requiredPageVersion: 1 - }) - expect(output).toContain('Update Orca on your computer') - expect(output).toContain('This paired desktop app is too old for your current Orca Mobile app') - expect(primaryActionUrl()).toBe(RELEASES_URL) - }) - - it('routes an Android bundle wall to GitHub Releases, not a store that has no listing', () => { - nativeTestState.platform.OS = 'android' - const output = render({ - kind: 'blocked', - reason: 'bundle-shell-too-old', - schemaVersion: 2 - }) - expect(output).toContain('Update Orca Mobile from GitHub Releases') - expect(primaryActionUrl()).toBe(RELEASES_URL) - }) - - it('keeps the update walls on two buttons and the full recovery note', () => { - const output = render({ kind: 'blocked', reason: 'bundle-unavailable' }) - expect(output).toContain('Already updated? Go back to Hosts and refresh the connection.') - // The presence precondition for the absence asserted on the refresh wall above. - expect(pressableCount()).toBe(2) - }) - describe('with the newest release known', () => { const release = { version: '0.0.52', url: 'https://github.com/stablyai/orca/releases/tag/mobile-v0.0.52' } - it.each(['ios', 'android'] as const)('opens that exact release on %s', (os) => { + it.each(['android'] as const)('opens that exact release on %s', (os) => { nativeTestState.platform.OS = os const output = render( { kind: 'blocked', reason: 'bundle-shell-too-old', schemaVersion: 2 }, diff --git a/mobile/src/components/WorktreeAgentList.runtime-lineage.test.tsx b/mobile/src/components/WorktreeAgentList.runtime-lineage.test.tsx deleted file mode 100644 index a8043236b5d..00000000000 --- a/mobile/src/components/WorktreeAgentList.runtime-lineage.test.tsx +++ /dev/null @@ -1,90 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { beforeEach, expect, it, vi } from 'vitest' -import { clearDisclosuresForTests } from '../worktree/agent-child-disclosure' -import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' -import { WorktreeAgentSummary } from './WorktreeAgentSummary' -import { WorktreeAgentList } from './WorktreeAgentList' - -// Disclosures persist in a module cache across list remounts; isolate each test. -beforeEach(clearDisclosuresForTests) - -vi.mock('react-native', () => ({ - AppState: { currentState: 'active', addEventListener: () => ({ remove: () => {} }) }, - Pressable: 'Pressable', - StyleSheet: { create: (styles: T) => styles }, - Text: 'Text', - View: 'View' -})) -vi.mock('lucide-react-native', () => ({ - ChevronDown: 'ChevronDown', - ChevronRight: 'ChevronRight' -})) -vi.mock('./AgentStateDot', () => ({ AgentStateDot: () => null })) -vi.mock('./MobileAgentIcon', () => ({ MobileAgentIcon: () => null })) - -it('renders production-built canonical assignments as nested rows and groups only roots', async () => { - const clock = vi.spyOn(Date, 'now').mockReturnValue(1_800_000_000_000) - const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = - await import('../../../src/main/runtime/workspaces/process-listing/runtime-agent-lineage.test-fixture') - const { flattenAgentRowLineage } = await import('../worktree/agent-row-lineage') - const f = publicLineageFixture() - let tree: ReactTestRenderer | undefined - try { - const agents = f.build().agents - expect(flattenAgentRowLineage(agents).map((node) => [node.row.paneKey, node.depth])).toEqual([ - [canonicalChatRow(LINEAGE_PARENT), 0], - [canonicalChatRow(LINEAGE_CHILD), 1] - ]) - await act(async () => { - tree = create( - createElement(WorktreeAgentList, { - agents, - unvisited: false, - statusLive: true - }) - ) - }) - const toggle = tree?.root.find( - (node) => node.props.accessibilityLabel === 'Show 1 child agent' && node.props.onPress - ) - await act(async () => toggle?.props.onPress({ stopPropagation: vi.fn() })) - expect( - tree?.root - .findAll((node) => node.props.agent !== undefined) - .map((node) => [node.props.agent.paneKey, node.props.depth]) - ).toEqual([ - [canonicalChatRow(LINEAGE_PARENT), 0], - [canonicalChatRow(LINEAGE_CHILD), 1] - ]) - expect(tree?.root.findAllByType(WorktreeAgentSummary)).toHaveLength(0) - expect(agents[1].taskTitle).toBe('Build the worker result') - expect(JSON.stringify(tree?.toJSON())).toContain('Coordinate work') - expect(JSON.stringify(tree?.toJSON())).toContain('Implement work') - expect(JSON.stringify(tree?.toJSON())).not.toContain('2 agents') - expect(JSON.stringify(tree?.toJSON())).not.toContain(f.privateHandle) - expect(JSON.stringify(tree?.toJSON())).not.toContain(f.privatePane) - const orphan = { - ...agents[1], - paneKey: 'missing-parent-worker', - parentPaneKey: 'missing-parent' - } - await act(async () => - tree?.update( - createElement(WorktreeAgentList, { - agents: [...agents, orphan], - unvisited: false - }) - ) - ) - expect( - tree?.root - .findByType(WorktreeAgentSummary) - .props.agents.map((row: RuntimeWorktreeAgentRow) => row.paneKey) - ).toEqual([canonicalChatRow(LINEAGE_PARENT), orphan.paneKey]) - } finally { - await act(async () => tree?.unmount()) - f.db.close() - clock.mockRestore() - } -}) diff --git a/mobile/src/components/mobile-markdown-visual-lines.test.ts b/mobile/src/components/mobile-markdown-visual-lines.test.ts deleted file mode 100644 index 62dd3318518..00000000000 --- a/mobile/src/components/mobile-markdown-visual-lines.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { NATIVE_CHAT_VISUAL_MAX_PER_MESSAGE } from '../../../src/shared/native-chat/native-chat-visual-directive' -import { plainText } from './mobile-markdown-plain-text' -import { parseMobileMarkdownTree } from './mobile-markdown-tree' -import { - mobileMarkdownVisualPlaceholderIndex, - protectMobileMarkdownVisualLines -} from './mobile-markdown-visual-lines' - -/** The top-level blocks drawn, with a lone placeholder paragraph read as its visual. */ -function topLevelBlocks(text: string, visualCount: number) { - return parseMobileMarkdownTree(text, false).children.map((node) => { - const visual = - node.type === 'paragraph' - ? mobileMarkdownVisualPlaceholderIndex(plainText(node), visualCount) - : null - if (visual !== null) { - return { type: 'visual', index: visual } - } - return node.type === 'code' - ? { type: 'code', text: node.value, language: node.lang } - : { type: node.type, text: plainText(node) } - }) -} - -/** The same steps MobileMarkdown runs when a transcript renders visuals. */ -function blocksOf(content: string) { - const { text, directives } = protectMobileMarkdownVisualLines(content) - return { directives, blocks: topLevelBlocks(text, directives.length) } -} - -describe('native-chat visual lines in mobile markdown', () => { - it('turns a directive line into its own block between prose', () => { - const { directives, blocks } = blocksOf( - 'Here is the chart.\n::orca-visual{file="usage-3f2a.html" title="Usage"}\nIt shows a dip.' - ) - expect(directives).toEqual([{ file: 'usage-3f2a.html', title: 'Usage' }]) - expect(blocks).toEqual([ - { type: 'paragraph', text: 'Here is the chart.' }, - { type: 'visual', index: 0 }, - { type: 'paragraph', text: 'It shows a dip.' } - ]) - }) - - it('keeps the title exactly as written, before entity decoding and tag stripping', () => { - const { directives } = blocksOf('::orca-visual{file="a.html" title="Q1 & Q2"}') - expect(directives).toEqual([{ file: 'a.html', title: 'Q1 & Q2' }]) - }) - - it('accepts CRLF line endings and up to three leading spaces', () => { - const { blocks } = blocksOf('intro\r\n ::orca-visual{file="a.html"}\r\nend') - expect(blocks.map((block) => block.type)).toEqual(['paragraph', 'visual', 'paragraph']) - }) - - it('leaves directives inside fenced code, quotes, list items and inline code as text', () => { - const fenced = blocksOf('```md\n::orca-visual{file="a.html"}\n```') - expect(fenced.directives).toEqual([]) - expect(fenced.blocks).toEqual([ - { type: 'code', text: '::orca-visual{file="a.html"}', language: 'md' } - ]) - expect(blocksOf('> ::orca-visual{file="a.html"}').directives).toEqual([]) - expect(blocksOf('- ::orca-visual{file="a.html"}').directives).toEqual([]) - expect(blocksOf('see `::orca-visual{file="a.html"}`').directives).toEqual([]) - expect(blocksOf(' ::orca-visual{file="a.html"}').directives).toEqual([]) - }) - - it('resumes recognizing directives after a fence closes', () => { - const { directives } = blocksOf('```\ncode\n```\n::orca-visual{file="after.html"}') - expect(directives).toEqual([{ file: 'after.html', title: null }]) - }) - - it('renders directives past the per-message cap as text', () => { - const lines = Array.from( - { length: NATIVE_CHAT_VISUAL_MAX_PER_MESSAGE + 1 }, - (_, index) => `::orca-visual{file="v${index}.html"}` - ) - const { directives, blocks } = blocksOf(lines.join('\n')) - expect(directives).toHaveLength(NATIVE_CHAT_VISUAL_MAX_PER_MESSAGE) - expect(blocks.at(-1)).toEqual({ type: 'paragraph', text: lines.at(-1) }) - }) - - it('renders no visuals for text that already spells a placeholder', () => { - const { directives } = blocksOf('\uE000ORCA_VISUAL_0\uE000\n::orca-visual{file="a.html"}') - expect(directives).toEqual([]) - }) - - it('never treats a placeholder-looking line as a visual when none were protected', () => { - expect(topLevelBlocks('\uE000ORCA_VISUAL_0\uE000', 0)).toEqual([ - { type: 'paragraph', text: '\uE000ORCA_VISUAL_0\uE000' } - ]) - }) -}) diff --git a/mobile/src/components/pr-sidebar/pr-actions-state.test.ts b/mobile/src/components/pr-sidebar/pr-actions-state.test.ts deleted file mode 100644 index dfc489ea490..00000000000 --- a/mobile/src/components/pr-sidebar/pr-actions-state.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { summarizeProviderChecks } from '../../../../src/shared/source-control/checks/provider-check-summary' -import { describe, expect, it } from 'vitest' -import type { PRInfo } from '../../../../src/shared/github/pull-request-types' -import { presentPrMerge } from './pr-actions-state' - -describe('presentPrMerge', () => { - const pr: PRInfo = { - number: 202, - title: 'API', - state: 'open', - url: 'https://example.test/202', - checksStatus: 'success', - updatedAt: '', - mergeable: 'CONFLICTING' - } - const entry = { - title: '', - url: '', - state: 'open' as const, - checksStatus: 'success' as const, - mergeable: 'MERGEABLE' as const - } - - it('lets a complete stack merge through, and names a blocking downstack PR', () => { - const stack = { - number: 51, - position: 2, - size: 3, - baseRefName: 'main', - entries: [ - { ...entry, position: 1, number: 201 }, - { ...entry, position: 2, number: 202 } - ] - } - expect(presentPrMerge({ ...pr, stack }, 'squash')).toMatchObject({ - enabled: true, - label: 'Merge through #202 · 2 PRs' - }) - const blocked = { - ...stack, - entries: [{ ...entry, position: 1, number: 201, state: 'draft' as const }, stack.entries[1]] - } - expect(presentPrMerge({ ...pr, stack: blocked }, 'squash')).toMatchObject({ - enabled: false, - hint: '#201 is still a draft.' - }) - }) - it('keeps the provider-authorized merge action available with cancelled checks', () => { - const checksSummary = summarizeProviderChecks([ - { status: 'completed', conclusion: 'success' }, - { status: 'completed', conclusion: 'cancelled' } - ]) - expect( - presentPrMerge( - { - ...pr, - mergeable: 'MERGEABLE', - mergeStateStatus: 'CLEAN', - checksStatus: 'failure', - checksSummary - }, - 'squash' - ) - ).toMatchObject({ - label: 'Squash and merge', - hint: null, - enabled: true - }) - }) -}) diff --git a/mobile/src/components/pr-sidebar/pr-checks-presentation.test.ts b/mobile/src/components/pr-sidebar/pr-checks-presentation.test.ts deleted file mode 100644 index f34823dcdf1..00000000000 --- a/mobile/src/components/pr-sidebar/pr-checks-presentation.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { expect, it } from 'vitest' -import type { PRCheckDetail } from '../../../../src/shared/github/check-types' -import { summarizePRChecks } from './pr-checks-presentation' - -function check(over: Partial): PRCheckDetail { - return { - name: 'ci', - status: 'completed', - conclusion: 'success', - url: null, - ...over - } -} - -it('presents cancellations without hiding real failure or pending checks', () => { - const cancelled = check({ conclusion: 'cancelled' }) - expect(summarizePRChecks([cancelled, check({})])).toMatchObject({ - outcome: 'cancelled', - failed: 0, - cancelled: 1, - label: '1 Cancelled · 1 passed' - }) - expect(summarizePRChecks([cancelled, check({ conclusion: 'pending' })]).outcome).toBe('pending') - expect(summarizePRChecks([cancelled, check({ conclusion: 'failure' })]).outcome).toBe('failure') -}) diff --git a/mobile/src/components/use-connected-host-picker.test.ts b/mobile/src/components/use-connected-host-picker.test.ts index 40e23a8f684..052c1b4a5f2 100644 --- a/mobile/src/components/use-connected-host-picker.test.ts +++ b/mobile/src/components/use-connected-host-picker.test.ts @@ -50,21 +50,6 @@ describe('useConnectedHostPicker', () => { act(() => handle.current!.pickHost(action, hosts)) } - it('disambiguates path-routed hosts without exposing endpoint paths', () => { - render([ - host('desk-a', 'Desk', 'wss://gateway.example.com/v1/connect/bearer-secret-a'), - host('desk-b', 'Desk', 'wss://gateway.example.com/v1/connect/bearer-secret-b') - ]) - - pickHost(vi.fn()) - - expect(picker().options).toEqual([ - { value: 'desk-a', label: 'Desk', subtitle: 'gateway.example.com · desk-a' }, - { value: 'desk-b', label: 'Desk', subtitle: 'gateway.example.com · desk-b' } - ]) - expect(JSON.stringify(picker().options)).not.toContain('bearer-secret') - }) - it('closes a stale picker when an offered host disconnects', () => { const rerender = render([desk, laptop]) diff --git a/mobile/src/components/use-detail-card-scope.web.test.tsx b/mobile/src/components/use-detail-card-scope.web.test.tsx deleted file mode 100644 index e615d52d926..00000000000 --- a/mobile/src/components/use-detail-card-scope.web.test.tsx +++ /dev/null @@ -1,193 +0,0 @@ -// @vitest-environment happy-dom -import { act, useRef } from 'react' -import { createRoot } from 'react-dom/client' -import { expect, it, vi } from 'vitest' -import { - DetailCardHostProvider, - DetailCardLayer, - DetailCardFocusBoundary -} from './detail-card-host.web' -import { useDetailCardScope } from './use-detail-card-scope.web' - -it('keeps outside actions and finite focus order while releasing a retained visual', () => { - const root = document.createElement('div') - document.body.append(root) - const node = (id: string) => { - const value = document.getElementById(id) - if (!(value instanceof HTMLElement)) { - throw new Error(id) - } - return value - } - const renderer = createRoot(root) - const dismiss = vi.fn() - const action = vi.fn() - function Scope({ active, obscured = false }: { active: boolean; obscured?: boolean }) { - const contentRef = useRef(null) - const boundaryRefs = useRef([]) - const openerRef = useRef(null) - const backRef = useRef(null) - useDetailCardScope({ active, obscured, openerRef, backRef, contentRef, boundaryRefs, dismiss }) - return ( - <> - - - - - - - - -
-
- Details -
-
- -
- - ) - } - const render = (active: boolean, obscured = false) => - act(() => - renderer.render( - - - - ) - ) - const focusBoundary = (id: string, backwards: boolean) => { - const boundary = backwards ? node(id).previousElementSibling : node(id).nextElementSibling - if (!(boundary instanceof HTMLElement)) { - throw new Error(`Missing focus boundary beside ${id}`) - } - boundary.focus() - } - - const key = (type: string, name: string, shiftKey = false) => - document.activeElement?.dispatchEvent( - new KeyboardEvent(type, { key: name, shiftKey, bubbles: true, cancelable: true }) - ) - const terminalKeys = vi.fn() - window.addEventListener('keydown', terminalKeys) - try { - render(false) - expect(document.activeElement).toBe(document.body) - const opener = node('opener') - const host = node('card').parentElement - expect(host?.parentElement).toBe(document.body) - node('terminal').focus() - render(true) - expect(node('terminal').inert).toBe(false) - expect(document.activeElement).toBe(node('terminal')) - node('back').click() - expect(dismiss).not.toHaveBeenCalled() - key('keydown', 'Escape') - key('keyup', 'Escape') - expect(terminalKeys).not.toHaveBeenCalled() - key('keydown', 'a') - expect(terminalKeys).toHaveBeenCalledTimes(1) - render(false) - expect(node('card').inert).toBe(true) - expect(opener.previousElementSibling).toBe(node('back')) - expect(opener.nextElementSibling).toBe(node('files')) - expect(node('card').nextElementSibling).toBeNull() - expect(document.activeElement).toBe(node('terminal')) - render(true) - key('keydown', 'Tab') - focusBoundary('opener', false) - expect(document.activeElement).toBe(node('scroll')) - key('keydown', 'Tab', true) - focusBoundary('card', true) - expect(document.activeElement).toBe(opener) - key('keydown', 'Tab', true) - focusBoundary('opener', true) - expect(document.activeElement).toBe(node('back')) - render(false) - render(true) - key('keydown', 'Tab') - focusBoundary('card', false) - expect(document.activeElement).toBe(node('files')) - expect(dismiss).toHaveBeenCalledTimes(3) - render(false) - render(true) - node('files').click() - expect(action).toHaveBeenCalledTimes(1) - expect(dismiss).toHaveBeenCalledTimes(4) - node('files').focus() - render(false) - expect(document.activeElement).toBe(node('files')) - render(true) - node('files').focus() - expect(dismiss).toHaveBeenCalledTimes(5) - render(false) - expect(document.activeElement).toBe(node('files')) - render(true) - render(false, true) - expect(node('card').inert).toBe(true) - expect(node('opener')).toBe(opener) - act(() => renderer.unmount()) - expect(host?.isConnected).toBe(false) - } finally { - window.removeEventListener('keydown', terminalKeys) - root.remove() - } -}) - -it('yields to a higher sheet while an earlier card contact is still in flight', () => { - const root = document.createElement('div') - document.body.append(root) - const mount = document.createElement('div') - root.append(mount) - const renderer = createRoot(mount) - const dismiss = vi.fn() - const action = vi.fn() - const openerRef = { current: document.createElement('button') } - const contentRef = { current: document.createElement('div') } - const backRef = { current: document.createElement('button') } - const boundaryRefs = { current: [] } - const sheet = document.createElement('button') - contentRef.current.tabIndex = -1 - sheet.addEventListener('click', action) - root.append(openerRef.current, backRef.current, contentRef.current, sheet) - function Scope({ obscured }: { obscured: boolean }) { - useDetailCardScope({ - active: !obscured, - obscured, - openerRef, - contentRef, - backRef, - boundaryRefs, - dismiss - }) - return null - } - const contact = (target: HTMLElement, type: string, pointerId: number) => - target.dispatchEvent( - new PointerEvent(type, { pointerId, pointerType: 'touch', bubbles: true, cancelable: true }) - ) - try { - openerRef.current.focus() - act(() => renderer.render()) - expect(contact(contentRef.current, 'pointerdown', 1)).toBe(true) - act(() => renderer.render()) - sheet.focus() - expect(contentRef.current.inert).toBe(true) - expect(contact(sheet, 'pointerdown', 2)).toBe(true) - expect(contact(contentRef.current, 'pointerup', 1)).toBe(true) - expect(contact(sheet, 'pointerup', 2)).toBe(true) - sheet.click() - expect(action).toHaveBeenCalledTimes(1) - expect(dismiss).not.toHaveBeenCalled() - expect(document.activeElement).toBe(sheet) - } finally { - act(() => renderer.unmount()) - root.remove() - } -}) diff --git a/mobile/src/diagnostics/connection/connection-log-buffer.test.ts b/mobile/src/diagnostics/connection/connection-log-buffer.test.ts index 631d5af747b..39712e28e54 100644 --- a/mobile/src/diagnostics/connection/connection-log-buffer.test.ts +++ b/mobile/src/diagnostics/connection/connection-log-buffer.test.ts @@ -31,64 +31,6 @@ describe('connection log buffer', () => { expect(JSON.stringify(save.mock.calls)).not.toContain('legacy-secret') }) - it('redacts quoted credential values when the object key is unquoted', async () => { - const store = createConnectionLogStore(3, { load: async () => [], save: async () => {} }) - - store.append('host-a', { - ...entry(1), - detail: `resumeToken: 'secret-one' deviceToken="secret-two"` - }) - await store.hydrate('host-a') - - expect(store.get('host-a')[0]?.detail).toBe( - `resumeToken: '[redacted]' deviceToken="[redacted]"` - ) - }) - - it('redacts the full quoted credential when its value contains an escaped quote', async () => { - const store = createConnectionLogStore(3, { load: async () => [], save: async () => {} }) - - store.append('host-a', { - ...entry(1), - detail: String.raw`{"token":"secret\"tail"} token: 'secret\'tail'` - }) - await store.hydrate('host-a') - - expect(store.get('host-a')[0]?.detail).toBe(`{"token":"[redacted]"} token: '[redacted]'`) - }) - - it('redacts unterminated quoted credentials', async () => { - const store = createConnectionLogStore(3, { load: async () => [], save: async () => {} }) - - store.append('host-a', { - ...entry(1), - message: 'token="secret', - detail: '{"authorization":"Bearer also-secret' - }) - await store.hydrate('host-a') - - expect(store.get('host-a')[0]).toMatchObject({ - message: 'token="[redacted]', - detail: '{"authorization":"[redacted]' - }) - }) - - it('redacts URL userinfo through the last authority separator', async () => { - const store = createConnectionLogStore(3, { load: async () => [], save: async () => {} }) - - store.append('host-a', { - ...entry(1), - message: 'wss://user:p@ss@example.com/x', - detail: 'https://user:pass@example.com/x' - }) - await store.hydrate('host-a') - - expect(store.get('host-a')[0]).toMatchObject({ - message: 'wss://[redacted]@example.com/x', - detail: 'https://[redacted]@example.com/x' - }) - }) - it('does not overwrite persisted history when hydration fails and retries later', async () => { const load = vi .fn<() => Promise>() diff --git a/mobile/src/diagnostics/native-diagnostics-operations.test.ts b/mobile/src/diagnostics/native-diagnostics-operations.test.ts index f87c0f062bc..38cbb6e3ab2 100644 --- a/mobile/src/diagnostics/native-diagnostics-operations.test.ts +++ b/mobile/src/diagnostics/native-diagnostics-operations.test.ts @@ -60,23 +60,4 @@ describe('native connection diagnostic reports', () => { expect(report).toContain('Host Orca version: unknown') expect(report).not.toContain('1.4.197') }) - - it('does not promote a disconnected version when a connection opens during hydration', async () => { - let finishHydration = () => {} - logStore.hydrate.mockReturnValue( - new Promise((resolve) => { - finishHydration = resolve - }) - ) - const context = createContext() - context.setConnection('disconnected', 1_000) - const device = createNativeDiagnosticsOperations(host, context, '1.4.197') - const pendingReport = device.report() - context.setConnection('connected', 1_000) - finishHydration() - const { report } = await pendingReport - expect(report).toContain('State: connected') - expect(report).toContain('Host Orca version: unknown') - expect(report).not.toContain('1.4.197') - }) }) diff --git a/mobile/src/diagnostics/native-render-log.test.ts b/mobile/src/diagnostics/native-render-log.test.ts index b6a82eb4b6f..fb00974e5af 100644 --- a/mobile/src/diagnostics/native-render-log.test.ts +++ b/mobile/src/diagnostics/native-render-log.test.ts @@ -1,6 +1,5 @@ import AsyncStorage from '@react-native-async-storage/async-storage' import { beforeEach, expect, it, vi } from 'vitest' -import type { HostProfile } from '../transport/hosts/host-profile' vi.mock('react-native', () => ({ Platform: { OS: 'ios', Version: '27' } })) vi.mock('expo-constants', () => ({ default: { expoConfig: { version: '0.0.60' } } })) @@ -8,22 +7,6 @@ vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: vi.fn(), setItem: vi.fn() } })) -const context = { - getState: () => 'disconnected' as const, - getReconnectAttempt: () => 0, - getLastConnectedAt: () => null, - getActivePath: () => 'lan' as const, - getPendingPath: () => null -} -const pairedHost: HostProfile = { - id: 'desktop', - name: 'Desktop', - endpoint: 'ws://desktop.invalid:6768', - deviceToken: 'device-secret', - publicKeyB64: 'key', - lastConnected: 0 -} - beforeEach(() => { vi.resetModules() const storage = new Map() @@ -33,30 +16,6 @@ beforeEach(() => { }) }) -it.each([null, pairedHost])( - 'retains a native render failure in the copied report after restart, host %s', - async (host) => { - const { recordNativeRenderError, NATIVE_APP_LOG_ID } = await import('./native-render-log') - const { connectionLogStore } = await import('./connection/persisted-connection-log-store') - const failure = new Error('Private prompt\n at PRIVATE PROMPT\ntoken=do-not-share') - failure.stack = `${failure.name}: ${failure.message}\n at UnauthorizedAboutRoute (/Users/private/project/about.tsx:12:3)` - recordNativeRenderError(failure, 'about') - await connectionLogStore.hydrate(NATIVE_APP_LOG_ID) - await connectionLogStore.flush() - vi.resetModules() - - const { createNativeDiagnosticsOperations } = await import('./native-diagnostics-operations') - const { report, incidentId } = await createNativeDiagnosticsOperations(host, context).report() - expect(report).toContain('Native screen failed to render') - expect(report).toContain('UnauthorizedAboutRoute') - expect(report).not.toContain('Private prompt') - expect(report).not.toContain('PRIVATE PROMPT') - expect(report).not.toContain('do-not-share') - expect(report).not.toContain('/Users/private') - expect(incidentId).toBeNull() - } -) - it('keeps a log entry when the thrown error has an unreadable stack', async () => { const { recordNativeRenderError, NATIVE_APP_LOG_ID } = await import('./native-render-log') const failure = new Error('bad stack') diff --git a/mobile/src/diagnostics/use-troubleshoot-diagnostics.test.tsx b/mobile/src/diagnostics/use-troubleshoot-diagnostics.test.tsx deleted file mode 100644 index b1c00c11225..00000000000 --- a/mobile/src/diagnostics/use-troubleshoot-diagnostics.test.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as HostReachability from './host-reachability' - -const hosts = vi.hoisted(() => ({ - catalog: vi.fn<() => Promise<{ endpoint: string }[]>>(), - profiles: vi.fn<() => Promise<{ name: string; endpoint: string }[]>>() -})) -vi.mock('react-native', () => ({ Platform: { OS: 'ios', Version: '27' } })) -vi.mock('../transport/hosts/host-store', () => ({ - loadHostCatalog: hosts.catalog, - loadHosts: hosts.profiles -})) -vi.mock('./host-reachability', async (importOriginal) => ({ - ...(await importOriginal()), - testHostReachability: async () => true -})) - -import { useTroubleshootDiagnostics } from './use-troubleshoot-diagnostics' - -let tree: ReactTestRenderer | undefined -const state: { current: ReturnType | null } = { current: null } -function Harness() { - state.current = useTroubleshootDiagnostics() - return null -} - -afterEach(async () => { - await act(async () => tree?.unmount()) - state.current = null - vi.resetAllMocks() - vi.unstubAllGlobals() -}) - -describe('troubleshooting paired endpoints', () => { - it('retains saved port advice after a run when the host credential is unavailable', async () => { - hosts.catalog.mockResolvedValue([{ endpoint: 'ws://desktop.local:6769' }]) - hosts.profiles.mockResolvedValue([]) - vi.stubGlobal('fetch', async () => ({ ok: true })) - await act(async () => { - tree = create(createElement(Harness)) - }) - expect(state.current?.hostEndpoints).toEqual(['ws://desktop.local:6769']) - await act(async () => { - await state.current?.runDiagnostics() - }) - expect(state.current?.hostEndpoints).toEqual(['ws://desktop.local:6769']) - }) -}) diff --git a/mobile/src/dictation/dictation-reply-schema.ts b/mobile/src/dictation/dictation-reply-schema.ts index f50061d06e6..9298651bd11 100644 --- a/mobile/src/dictation/dictation-reply-schema.ts +++ b/mobile/src/dictation/dictation-reply-schema.ts @@ -32,6 +32,8 @@ export const dictationSetupSchema = z.looseObject({ enabled: salvagedOptional('enabled', z.boolean()), selectedModelId: salvagedOptional('selectedModelId', z.string()), dictationMode: salvagedOptional('dictationMode', z.string()), + // Absent from older hosts, which remove no fillers either; the phone then keeps them on, the host default. + removeFillerWords: salvagedOptional('removeFillerWords', z.boolean()), models: salvagingArray(speechModelSchema) }) diff --git a/mobile/src/dictation/use-mobile-dictation-silence-stop.test.tsx b/mobile/src/dictation/use-mobile-dictation-silence-stop.test.tsx deleted file mode 100644 index 89981c8538c..00000000000 --- a/mobile/src/dictation/use-mobile-dictation-silence-stop.test.tsx +++ /dev/null @@ -1,56 +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 { createMobileDictationMeter } from '../hooks/mobile-dictation-meter' -import { useMobileDictationSilenceStop } from './use-mobile-dictation-silence-stop' - -// 16 kHz 16-bit little-endian PCM, as both shells deliver it. -function pcm(milliseconds: number, amplitude: number): Uint8Array { - const samples = (16_000 * milliseconds) / 1000 - const bytes = new Uint8Array(samples * 2) - const view = new DataView(bytes.buffer) - for (let index = 0; index < samples; index += 1) { - view.setInt16(index * 2, index % 2 === 0 ? amplitude : -amplitude, true) - } - return bytes -} - -function record(dictationMode: string) { - const meter = createMobileDictationMeter() - meter.start() - const dictation = { isRecording: true, meter } - const stop = vi.fn() - const showToast = vi.fn() - function Probe() { - useMobileDictationSilenceStop(dictation, dictationMode, stop, showToast) - return null - } - let renderer: ReactTestRenderer | undefined - act(() => { - renderer = create(createElement(Probe)) - }) - // Feed the mic the way the page shell drains it: 500 ms batches at the given amplitude. - const play = (seconds: number, amplitude: number) => { - for (let batch = 0; batch < seconds * 2; batch += 1) { - act(() => { - meter.push(pcm(500, amplitude)) - vi.advanceTimersByTime(500) - }) - } - } - return { stop, showToast, play, unmount: () => act(() => renderer?.unmount()) } -} - -describe('dictation silence stop', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => vi.useRealTimers()) - - it('never stops a hold-mode recording', () => { - const { stop, unmount } = record('hold') - act(() => { - vi.advanceTimersByTime(120_000) - }) - expect(stop).not.toHaveBeenCalled() - unmount() - }) -}) diff --git a/mobile/src/files/MobileFilePreviewEditDraft.tsx b/mobile/src/files/MobileFilePreviewEditDraft.tsx index 13ede3827b2..bea1c2ab81b 100644 --- a/mobile/src/files/MobileFilePreviewEditDraft.tsx +++ b/mobile/src/files/MobileFilePreviewEditDraft.tsx @@ -6,9 +6,11 @@ import { } from '../drafts/use-document-edit-draft' import { useClipboardWriter } from '../platform/clipboard' import { triggerError, triggerSuccess } from '../platform/haptics' +import { useKeyboardOcclusion } from '../platform/keyboard-occlusion' import { spacing } from '../theme/mobile-theme' import { useSafeAreaInsets } from 'react-native-safe-area-context' import type { MobileFilePreviewSource } from './mobile-file-preview-request' +import { resolveMarkdownFloatingActionsBottom } from './session-documents/markdown-floating-actions-layout' /** Only terminal artifacts are editable in the file preview. */ export function filePreviewEditDraftKey( @@ -43,10 +45,15 @@ function OfferBar(props: { }) { const clipboard = useClipboardWriter() const insets = useSafeAreaInsets() + const keyboardHeight = useKeyboardOcclusion() return ( void clipboard.writeText(props.offer.content).then(triggerSuccess, triggerError) } diff --git a/mobile/src/files/MobileMarkdownPreviewImage.test.tsx b/mobile/src/files/MobileMarkdownPreviewImage.test.tsx deleted file mode 100644 index 3bd696f63bd..00000000000 --- a/mobile/src/files/MobileMarkdownPreviewImage.test.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import { createElement } from 'react' -import type { ImageProps } from 'react-native' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, expect, it, vi } from 'vitest' -import { MobileMarkdownPreviewImage } from './MobileMarkdownPreviewImage' - -vi.mock('react-native', () => ({ - ActivityIndicator: 'ActivityIndicator', - Image: Object.assign((props: ImageProps) => createElement('Image', props), { - getSize: (_uri: string, loaded: (width: number, height: number) => void) => loaded(600, 220) - }), - Pressable: 'Pressable', - StyleSheet: { create: (styles: unknown) => styles }, - Text: 'Text', - View: 'View' -})) -vi.mock('../components/MobileStateView', () => ({ MobileLoadErrorState: 'LoadError' })) -vi.mock('../session/native-chat/visual/MobileNativeChatImageViewer', () => ({ - MobileNativeChatImageViewer: 'ImageViewer' -})) -vi.mock('../session/native-chat/visual/MobileImageViewerActions', () => ({ - MobileImageViewerActions: 'ImageViewerActions' -})) -const loader = vi.hoisted(() => vi.fn()) -vi.mock('./mobile-markdown-image-source', () => ({ loadMarkdownPreviewImage: loader })) -let tree: ReactTestRenderer | null = null -afterEach(() => { - act(() => tree?.unmount()) - tree = null - vi.resetAllMocks() -}) -const props = { - client: null, - worktreeId: 'wt', - documentPath: 'notes.md', - href: 'a.png', - alt: 'Architecture' -} - -it('retries a refused image without hiding the surrounding document', async () => { - loader - .mockRejectedValueOnce(new Error('Unable to reach the desktop filesystem')) - .mockResolvedValueOnce('data:image/png;base64,cG5n') - await act(async () => { - tree = create(createElement(MobileMarkdownPreviewImage, props)) - }) - expect(tree!.root.find((node) => String(node.type) === 'LoadError').props.error).toContain( - 'Unable to reach' - ) - await act(async () => - tree!.root.find((node) => String(node.type) === 'LoadError').props.onRetry() - ) - expect(tree!.root.find((node) => String(node.type) === 'Image').props.source.uri).toBe( - 'data:image/png;base64,cG5n' - ) -}) diff --git a/mobile/src/files/session-documents/MobileMarkdownReader.tsx b/mobile/src/files/session-documents/MobileMarkdownReader.tsx deleted file mode 100644 index 5dcecdbb970..00000000000 --- a/mobile/src/files/session-documents/MobileMarkdownReader.tsx +++ /dev/null @@ -1,188 +0,0 @@ -import { useRef, useState } from 'react' -import { ActivityIndicator, Pressable, Text, View } from 'react-native' -import { ChevronDown, Keyboard as KeyboardIcon, RefreshCw } from 'lucide-react-native' -import { - MobileRichMarkdownEditor, - type MobileRichMarkdownEditorHandle -} from '../../components/MobileRichMarkdownEditor' -import { colors, spacing, pressedStyle } from '../../theme/mobile-theme' -import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' -import { - resolveMarkdownFloatingActionsBottom, - shouldShowMarkdownFloatingActions -} from './markdown-floating-actions-layout' -import type { MarkdownDocState } from './session-document-state' -import { styles } from '../../session/mobile-session-styles' -import { MobileLoadErrorState, MobileStateView } from '../../components/MobileStateView' -import { useMobileTranslation } from '../../i18n/use-mobile-translation' - -type Props = { - documentId: string - doc: MarkdownDocState | undefined - onRefresh: () => void - onChange: (content: string) => void - onSave: () => void - onCopy: () => void - onDiscard: () => void - keyboardLift: number -} - -export function MobileMarkdownReader({ - documentId, - doc, - onRefresh, - onChange, - onSave, - onCopy, - onDiscard, - keyboardLift -}: Props) { - useMobileColorScheme() - const t = useMobileTranslation() - const editorRef = useRef(null) - // Native Keyboard events under-report the WebView editor's covered area, so prefer the larger WebView-measured inset. - const [webviewKeyboardInset, setWebviewKeyboardInset] = useState(0) - const effectiveKeyboardLift = Math.max(keyboardLift, webviewKeyboardInset) - const keyboardOpen = effectiveKeyboardLift > 0 - - if (!doc || doc.status === 'loading') { - return ( - - ) - } - if (doc.status === 'error') { - return - } - - const statusText = doc.saveError - ? doc.saveError - : doc.readOnlyReason - ? t('session.markdownReader.readOnly', 'Read only') - : doc.stale - ? t('session.markdownReader.changedOnDesktop', 'Changed on desktop') - : null - const showRefresh = Boolean((doc.stale && !doc.isDirty) || !doc.editable) - const showCopy = Boolean(doc.saveError || !doc.editable) - const showSave = Boolean(doc.isDirty || doc.saving) - const showFloatingActions = shouldShowMarkdownFloatingActions({ - keyboardLift: effectiveKeyboardLift, - hasStatus: statusText != null, - showRefresh, - showCopy, - showSave - }) - - return ( - - - {showFloatingActions ? ( - - {statusText ? ( - - {statusText} - - ) : null} - - {keyboardOpen ? ( - [ - styles.markdownFloatingButton, - styles.markdownKeyboardDismissButton, - pressed && pressedStyle - ]} - onPress={() => editorRef.current?.dismissKeyboard()} - hitSlop={8} - accessibilityRole="button" - accessibilityLabel={t('session.markdownReader.dismissKeyboard', 'Dismiss keyboard')} - accessibilityHint={t( - 'session.markdownReader.dismissKeyboardHint', - 'Hides the software keyboard and keeps the markdown editor open.' - )} - > - - - - - - ) : null} - {showCopy ? ( - [styles.markdownFloatingButton, pressed && pressedStyle]} - onPress={onCopy} - > - {t('common.copy', 'Copy')} - - ) : null} - {showRefresh ? ( - [styles.markdownFloatingButton, pressed && pressedStyle]} - onPress={onRefresh} - > - - - {t('common.refresh', 'Refresh')} - - - ) : null} - {doc.isDirty ? ( - [styles.markdownFloatingButton, pressed && pressedStyle]} - onPress={onDiscard} - > - - {t('session.markdownReader.discard', 'Discard')} - - - ) : null} - {showSave ? ( - [ - styles.markdownFloatingButton, - styles.markdownSaveButton, - (!doc.editable || !doc.isDirty || doc.saving) && styles.markdownButtonDisabled, - pressed && pressedStyle - ]} - disabled={!doc.editable || !doc.isDirty || doc.saving} - onPress={onSave} - > - {doc.saving ? ( - - ) : ( - {t('common.save', 'Save')} - )} - - ) : null} - - - ) : null} - - ) -} diff --git a/mobile/src/files/session-documents/markdown-floating-actions-layout.ts b/mobile/src/files/session-documents/markdown-floating-actions-layout.ts index bc506a88a9d..06aa5b9223f 100644 --- a/mobile/src/files/session-documents/markdown-floating-actions-layout.ts +++ b/mobile/src/files/session-documents/markdown-floating-actions-layout.ts @@ -9,19 +9,3 @@ export function resolveMarkdownFloatingActionsBottom({ }): number { return keyboardLift > 0 ? keyboardLift + liftedClearance : restingBottom } - -export function shouldShowMarkdownFloatingActions({ - keyboardLift, - hasStatus, - showRefresh, - showCopy, - showSave -}: { - keyboardLift: number - hasStatus: boolean - showRefresh: boolean - showCopy: boolean - showSave: boolean -}): boolean { - return keyboardLift > 0 || hasStatus || showRefresh || showCopy || showSave -} diff --git a/mobile/src/files/session-documents/mobile-markdown-reader-status.ts b/mobile/src/files/session-documents/mobile-markdown-reader-status.ts index 9e79d7adce9..e238cda5922 100644 --- a/mobile/src/files/session-documents/mobile-markdown-reader-status.ts +++ b/mobile/src/files/session-documents/mobile-markdown-reader-status.ts @@ -1,3 +1,4 @@ +import { translate } from '../../i18n/mobile-i18n' import { formatPreviewByteLength } from '../mobile-file-preview-response' import type { MarkdownDocState } from './session-document-state' @@ -9,11 +10,17 @@ export function markdownReaderStatusText( } if (doc.truncated) { return doc.byteLength === undefined - ? 'Preview truncated.' - : `Preview truncated. File size: ${formatPreviewByteLength(doc.byteLength)}.` + ? translate('session.markdownReader.previewTruncated', 'Preview truncated.') + : translate( + 'files.filePreviewSourceText.truncatedNote', + 'Preview truncated. File size: {{size}}.', + { size: formatPreviewByteLength(doc.byteLength) } + ) } if (doc.readOnlyReason) { - return 'Read only' + return translate('session.markdownReader.readOnly', 'Read only') } - return doc.stale ? 'Changed on desktop' : null + return doc.stale + ? translate('session.markdownReader.changedOnDesktop', 'Changed on desktop') + : null } diff --git a/mobile/src/home/MobileHomeScreen.tsx b/mobile/src/home/MobileHomeScreen.tsx index fadfbfcd5aa..11c0274f3a1 100644 --- a/mobile/src/home/MobileHomeScreen.tsx +++ b/mobile/src/home/MobileHomeScreen.tsx @@ -29,6 +29,7 @@ import { useOpenMobileHostEdit } from '../host-screen/use-open-mobile-host-edit' import { mobileConnectionPathLabel } from '../transport/connection/mobile-connection-path-label' import { newWorkspaceOverlayHref } from '../new-workspace/new-workspace-overlay-route' import { useMobileHomeData } from './use-mobile-home-data' +import { useHomeSparePage } from './use-home-spare-page' import { HOME_TABS, type HomeTabId } from './tabs/home-tabs' import { MobileHomeAgentsTab } from './tabs/MobileHomeAgentsTab' import { MobileHomeAutomationsTab } from './tabs/MobileHomeAutomationsTab' @@ -45,6 +46,7 @@ export function MobileHomeScreen() { const t = useMobileTranslation() useMobileColorScheme() const data = useMobileHomeData() + useHomeSparePage(data.hostCatalogLoaded ? data.sortedHosts.map((host) => host.id) : []) const insets = useSafeAreaInsets() const openMobileHostEdit = useOpenMobileHostEdit() const openMobileTasks = useOpenMobileTasks() diff --git a/mobile/src/home/use-home-spare-page.ts b/mobile/src/home/use-home-spare-page.ts new file mode 100644 index 00000000000..58aa55953c6 --- /dev/null +++ b/mobile/src/home/use-home-spare-page.ts @@ -0,0 +1,48 @@ +import { useFocusEffect } from 'expo-router' +import { useCallback } from 'react' +import { AppState } from 'react-native' +import { setForegroundTimer } from '../mobile-web-shell/foreground-timer' +import { + enterHomeSparePage, + leaveHomeSparePage, + prepareHomeSparePage +} from '../mobile-web-shell/home-spare-page' +import { processGenerationStore } from '../mobile-web-shell/process-generation-store' + +// Past Home's first paint and its first reads, so the boot never competes with them. +const HOME_SPARE_IDLE_MS = 1000 + +const HOST_ID_SEPARATOR = '\n' + +// While Home is shown, keep one page booted for the most recently connected host with a cached build. +// Native drops it when the app leaves the foreground, so every return to it arms again. +export function useHomeSparePage(hostIds: readonly string[]): void { + const hosts = hostIds.join(HOST_ID_SEPARATOR) + useFocusEffect( + useCallback(() => { + if (hosts === '') { + return undefined + } + enterHomeSparePage() + let cancelTimer = (): void => undefined + const arm = (): void => { + cancelTimer() + cancelTimer = setForegroundTimer( + () => void prepareHomeSparePage(processGenerationStore(), hosts.split(HOST_ID_SEPARATOR)), + HOME_SPARE_IDLE_MS + ) + } + arm() + const subscription = AppState.addEventListener('change', (state) => { + if (state === 'active') { + arm() + } + }) + return () => { + subscription.remove() + cancelTimer() + leaveHomeSparePage() + } + }, [hosts]) + ) +} diff --git a/mobile/src/hooks/mobile-dictation-session-state.ts b/mobile/src/hooks/mobile-dictation-session-state.ts index a3272f3fc88..0caaeadc144 100644 --- a/mobile/src/hooks/mobile-dictation-session-state.ts +++ b/mobile/src/hooks/mobile-dictation-session-state.ts @@ -11,6 +11,8 @@ export type UseMobileDictationOptions = { enabled: boolean onTranscript: (text: string) => void onError?: (error: Error) => void + // The computer's filler switch, for text the phone recognizes itself; unknown means on. + removeFillerWords?: boolean } export type UseMobileDictationResult = { diff --git a/mobile/src/hooks/use-mobile-dictation.ts b/mobile/src/hooks/use-mobile-dictation.ts index 348702c8fec..1d0e1746482 100644 --- a/mobile/src/hooks/use-mobile-dictation.ts +++ b/mobile/src/hooks/use-mobile-dictation.ts @@ -33,10 +33,10 @@ export type { UseMobileDictationResult } from './mobile-dictation-session-state' export function useMobileDictation(options: UseMobileDictationOptions): UseMobileDictationResult { useMobileTranslation() - const { client, enabled, onTranscript, onError } = options + const { client, enabled, onTranscript, onError, removeFillerWords } = options // Both capture seams hold the screen while the microphone is open; native uses the device directly and page uses shell audio verbs. const capture = useDictationCapture() - const speech = useOnDeviceSpeech() + const speech = useOnDeviceSpeech(removeFillerWords) const [status, setStatus] = useState('idle') const [error, setError] = useState(null) const [transcriptSoFar, setTranscriptSoFar, keptTranscript] = useMobileDictationTranscriptSoFar() diff --git a/mobile/src/host-screen/host-list-queries.ts b/mobile/src/host-screen/host-list-queries.ts index c65ded233ea..caa752201fd 100644 --- a/mobile/src/host-screen/host-list-queries.ts +++ b/mobile/src/host-screen/host-list-queries.ts @@ -1,5 +1,10 @@ import * as z from 'zod' -import { getRepoExecutionHostId, parseExecutionHostId } from '../../../src/shared/execution-host' +import { + getRepoExecutionHostId, + parseExecutionHostId, + type ExecutionHostId +} from '../../../src/shared/execution-host' +import { MOBILE_RELAY_HOST_WORKTREE_DELTAS_RUNTIME_CAPABILITY } from '../../../src/shared/mobile-desktop-relay-contract' import type { MobileRelayHost } from '../../../src/shared/remote-runtime/relay/mobile-relay-hosts-contract' import type { Query, QueryClient } from '@tanstack/react-query' import { defineHostQuery } from '../query/host-query' @@ -18,8 +23,13 @@ import { } from '../worktree/worktree-catalog-snapshot-client' import type { Worktree } from '../worktree/workspace-list-types' import { getCachedWorktrees } from '../cache/worktree-cache' -import { hostRepoCatalogRepos, type HostRepoCatalogRow } from './host-screen-reply-schema' +import { + hostRepoCatalogRepos, + hostSshTargetSummarySchema, + type HostRepoCatalogRow +} from './host-screen-reply-schema' import { hostPlatformRead, hostRepoCatalogSnapshotRead } from './host-screen-operations' +import { NODE_PLATFORM_NAMES } from '../transport/connection/mobile-runtime-host-platform' import { acceptedMetadata, readHostSshTargetLabels, @@ -119,6 +129,18 @@ const serverRowSnapshots = { full: new ServerRowSnapshots(false) } +/** + * The server rows' input. Before the host's status is read it names the key a current desktop stores them + * under, so they paint from the store: the page came from that desktop, which sends the deltas capability. + */ +export function hostServerWorkspacesInput(hostCapabilities: readonly string[] | null): { + deltas: boolean +} { + return { + deltas: hostCapabilities?.includes(MOBILE_RELAY_HOST_WORKTREE_DELTAS_RUNTIME_CAPABILITY) ?? true + } +} + // Workspaces on the servers this desktop relays to; a server whose read fails keeps its rows. export const hostServerWorkspacesQuery = defineHostQuery<{ deltas: boolean }, ServerWorkspaces>({ family: 'relayHosts.workspaces', @@ -187,10 +209,18 @@ export function catalogNeedsHostLabels(catalog: readonly HostRepoCatalogRow[]): return hostIds.size > 1 || [...hostIds].some((id) => parseExecutionHostId(id)?.kind === 'ssh') } -export type HostRepoLabels = Awaited> & { +export type HostRepoLabels = { + sshTargetSummaries: z.output[] + // Entries rather than a Map, so the record can be stored. + hostLabels: [ExecutionHostId, string][] platform: NodeJS.Platform | null } +const storedHostLabelSchema = z.tuple([ + z.custom((id) => typeof id === 'string' && parseExecutionHostId(id) !== null), + z.string() +]) + export const hostRepoLabelsQuery = defineHostQuery({ family: 'repo.hostLabels', fetch: async (client) => { @@ -198,13 +228,25 @@ export const hostRepoLabelsQuery = defineHostQuery hostPlatformRead.request(client)) ]) - return { ...labels, platform: acceptedMetadata(platform, hostPlatformRead.interpret) ?? null } + return { + sshTargetSummaries: labels.sshTargetSummaries, + hostLabels: [...labels.hostLabelById], + platform: acceptedMetadata(platform, hostPlatformRead.interpret) ?? null + } }, staleTime: 60_000, gcTime: 30 * 60_000, refetchOnWindowFocus: true, // SSH health and the host's own label overrides. - signal: { events: ['reposChanged', 'sshStateChanged'] } + signal: { events: ['reposChanged', 'sshStateChanged'] }, + persist: { + version: 1, + dataSchema: z.object({ + sshTargetSummaries: z.array(hostSshTargetSummarySchema), + hostLabels: z.array(storedHostLabelSchema), + platform: z.enum(NODE_PLATFORM_NAMES).nullable() + }) + } }) // The host list's own reads, which pull to refresh repeats; project.sections lives with its hook. diff --git a/mobile/src/host-screen/host-screen-reply-schema.ts b/mobile/src/host-screen/host-screen-reply-schema.ts index 7afeb0e3cea..171400b27eb 100644 --- a/mobile/src/host-screen/host-screen-reply-schema.ts +++ b/mobile/src/host-screen/host-screen-reply-schema.ts @@ -83,20 +83,17 @@ export const hostRepoCatalogSnapshotSchema = z.union([ ]) // Keep target parsing total: absent/malformed targets yield [] and labels degrade to host ids on older hosts. A throw here would also skip the subsequent platform write. +export const hostSshTargetSummarySchema = z.looseObject({ + id: z.string(), + label: z.string(), + // Read raw: an arm a newer desktop adds must leave the badge as it is, not read as a verdict. + connected: salvagedOptional('connected', z.boolean()), + connectionStatus: salvagedOptional('connectionStatus', z.string()) +}) + export const hostSshTargetSummariesSchema = z .looseObject({ - targets: salvagedOptional( - 'targets', - salvagingArray( - z.looseObject({ - id: z.string(), - label: z.string(), - // Read raw: an arm a newer desktop adds must leave the badge as it is, not read as a verdict. - connected: salvagedOptional('connected', z.boolean()), - connectionStatus: salvagedOptional('connectionStatus', z.string()) - }) - ) - ) + targets: salvagedOptional('targets', salvagingArray(hostSshTargetSummarySchema)) }) .transform((reply) => reply.targets ?? []) .catch(() => []) diff --git a/mobile/src/host-screen/use-host-repo-metadata.ts b/mobile/src/host-screen/use-host-repo-metadata.ts index 6a7475b1dd3..2d306455441 100644 --- a/mobile/src/host-screen/use-host-repo-metadata.ts +++ b/mobile/src/host-screen/use-host-repo-metadata.ts @@ -66,7 +66,7 @@ export function useHostRepoMetadata(args: { useEffect(() => { if (needsLabels && labels.data) { setHostHealthById(buildSshHostHealthById(labels.data.sshTargetSummaries)) - setHostLabelById(labels.data.hostLabelById) + setHostLabelById(new Map(labels.data.hostLabels)) setHostPlatform(labels.data.platform) } else if (repos.data && !needsLabels) { // Clear labels for departed hosts so stale metadata cannot badge remaining rows. diff --git a/mobile/src/host-screen/use-host-screen-controller.ts b/mobile/src/host-screen/use-host-screen-controller.ts index 8d9b449a25e..983fa99eb96 100644 --- a/mobile/src/host-screen/use-host-screen-controller.ts +++ b/mobile/src/host-screen/use-host-screen-controller.ts @@ -60,7 +60,8 @@ export function useHostScreenController({ const relayRecovery = useRelayRecoveryStatus(hostId) const forgetHostClient = useForgetHostClient() const forceReconnectHost = useForceReconnect() - const { hostCapabilities, floatingWorkspaceEnabled, hostInstallationId } = useHostProtocolGates() + const { hostCapabilities, statusReadable, floatingWorkspaceEnabled, hostInstallationId } = + useHostProtocolGates() const state = useHostScreenState(hostId, peekStoredHost(hostId)) const settings = useHostViewSettings({ client, connState, state }) const connectionVerdict = classifyConnection({ @@ -83,6 +84,7 @@ export function useHostScreenController({ connState, embedded, hostCapabilities, + hostStatusReadable: statusReadable, hostId, sidebarFeed: sidebarFeed?.triggers ?? null, state, diff --git a/mobile/src/host-screen/use-host-worktree-catalog.ts b/mobile/src/host-screen/use-host-worktree-catalog.ts index c4cd1db1da9..ca3715baef2 100644 --- a/mobile/src/host-screen/use-host-worktree-catalog.ts +++ b/mobile/src/host-screen/use-host-worktree-catalog.ts @@ -1,4 +1,3 @@ -import { MOBILE_RELAY_HOST_WORKTREE_DELTAS_RUNTIME_CAPABILITY } from '../../../src/shared/mobile-desktop-relay-contract' import { WORKTREE_ROWS_CHANGED_EVENT_RUNTIME_CAPABILITY } from '../../../src/shared/worktree-runtime-capabilities' import { readWorktreeFirstPage } from '../worktree/worktree-catalog-first-page' import type { Worktree } from '../worktree/workspace-list-types' @@ -32,6 +31,7 @@ import { HOST_LIST_BACKSTOP_POLL_MS, HOST_LIST_POLL_MS, HOST_LIST_TARGET, + hostServerWorkspacesInput, hostServerWorkspacesQuery, hostWorktreeCatalogKey, hostWorktreeCatalogQuery, @@ -54,6 +54,8 @@ export function useHostWorktreeCatalog(args: { connState: ConnectionState embedded: boolean hostCapabilities: readonly string[] + // Whether the host answered its status: capabilities are unknown, not absent, until it has. + hostStatusReadable: boolean hostId: string | undefined sidebarFeed: HostSidebarFeedTriggers | null state: HostScreenState @@ -64,6 +66,7 @@ export function useHostWorktreeCatalog(args: { connState, embedded, hostCapabilities, + hostStatusReadable, hostId, sidebarFeed, state, @@ -117,11 +120,13 @@ export function useHostWorktreeCatalog(args: { ) // An older desktop or shell lists no server rows, rather than rows that could not open. const relays = client !== null && relaysToServers(client, hostCapabilities) + // Until the host's status is read, stored server rows paint and nothing reads them. + const relaysRuledOut = hostStatusReadable && !relays const servers = useHostQuery( hostServerWorkspacesQuery, host, HOST_LIST_TARGET, - { deltas: hostCapabilities.includes(MOBILE_RELAY_HOST_WORKTREE_DELTAS_RUNTIME_CAPABILITY) }, + hostServerWorkspacesInput(hostStatusReadable ? hostCapabilities : null), // Execution hosts' notices are not relayed, so server rows keep the full poll. { enabled: !!hostId && relays, subscribed, refetchInterval: pollMs } ) @@ -210,12 +215,13 @@ export function useHostWorktreeCatalog(args: { }, [catalog.status, catalog.errorUpdatedAt]) useEffect(() => { - if (!relays) { - setServerWorkspaces(NO_SERVER_WORKSPACES) - } else if (servers.data) { + if (servers.data && !relaysRuledOut) { setServerWorkspaces(servers.data) + } else if (!relays) { + // Also drops a previous host's rows when the sidebar switches to one with none stored. + setServerWorkspaces(NO_SERVER_WORKSPACES) } - }, [relays, servers.data]) + }, [relays, relaysRuledOut, servers.data]) const fetchWorktrees = useCallback( async (options: { allowDuringModal?: boolean } = {}) => { diff --git a/mobile/src/i18n/locales/de.json b/mobile/src/i18n/locales/de.json index a2da39a8e47..2a9c0de8508 100644 --- a/mobile/src/i18n/locales/de.json +++ b/mobile/src/i18n/locales/de.json @@ -2193,8 +2193,7 @@ "copyPathLabel": "Pfad der Markdown-Datei kopieren", "copySource": "Markdown-Quelltext kopieren", "discard": "Verwerfen", - "dismissKeyboard": "Tastatur ausblenden", - "dismissKeyboardHint": "Blendet die Bildschirmtastatur aus und lässt den Markdown-Editor geöffnet.", + "previewTruncated": "Vorschau gekürzt.", "readOnly": "Schreibgeschützt" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 92a11862440..f6d1543f0c5 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -1962,8 +1962,7 @@ "markdownReader": { "readOnly": "Read only", "changedOnDesktop": "Changed on desktop", - "dismissKeyboard": "Dismiss keyboard", - "dismissKeyboardHint": "Hides the software keyboard and keeps the markdown editor open.", + "previewTruncated": "Preview truncated.", "discard": "Discard", "copyLoadedSource": "Copy loaded Markdown source", "copySource": "Copy Markdown source", @@ -3586,6 +3585,12 @@ "unavailableTitle": "Source Control Unavailable", "loading": "Loading changes…" }, + "folder": { + "emptyTitle": "No attached worktrees yet", + "emptyCopy": "Worktrees created from this workspace will show up here.", + "statusUnavailable": "Unavailable", + "backToFolder": "Back to folder" + }, "hostedReviewCopy": { "updatingBranch": "Updating branch...", "stagingChanges": "Staging changes...", diff --git a/mobile/src/i18n/locales/es.json b/mobile/src/i18n/locales/es.json index 615bc3008fa..2afe3233ac1 100644 --- a/mobile/src/i18n/locales/es.json +++ b/mobile/src/i18n/locales/es.json @@ -2260,8 +2260,7 @@ "copyPathLabel": "Copiar la ruta del archivo Markdown", "copySource": "Copiar el código fuente Markdown", "discard": "Descartar", - "dismissKeyboard": "Ocultar teclado", - "dismissKeyboardHint": "Oculta el teclado en pantalla y mantiene abierto el editor de Markdown.", + "previewTruncated": "Vista previa truncada.", "readOnly": "Solo lectura" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/fr.json b/mobile/src/i18n/locales/fr.json index b4968d0c4b4..fbfb961983b 100644 --- a/mobile/src/i18n/locales/fr.json +++ b/mobile/src/i18n/locales/fr.json @@ -2260,8 +2260,7 @@ "copyPathLabel": "Copier le chemin du fichier Markdown", "copySource": "Copier la source Markdown", "discard": "Abandonner", - "dismissKeyboard": "Masquer le clavier", - "dismissKeyboardHint": "Masque le clavier virtuel et laisse l'éditeur Markdown ouvert.", + "previewTruncated": "Aperçu tronqué.", "readOnly": "Lecture seule" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/ja.json b/mobile/src/i18n/locales/ja.json index 41b59f00545..954f8547baf 100644 --- a/mobile/src/i18n/locales/ja.json +++ b/mobile/src/i18n/locales/ja.json @@ -2189,8 +2189,7 @@ "copyPathLabel": "Markdown ファイルのパスをコピー", "copySource": "Markdown ソースをコピー", "discard": "破棄", - "dismissKeyboard": "キーボードを閉じる", - "dismissKeyboardHint": "Markdown エディターを開いたまま、ソフトウェアキーボードを非表示にします。", + "previewTruncated": "プレビューは一部省略されています。", "readOnly": "読み取り専用" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/ko.json b/mobile/src/i18n/locales/ko.json index 7c34395812a..826352f43aa 100644 --- a/mobile/src/i18n/locales/ko.json +++ b/mobile/src/i18n/locales/ko.json @@ -2189,8 +2189,7 @@ "copyPathLabel": "Markdown 경로 복사", "copySource": "Markdown 소스 복사", "discard": "버리기", - "dismissKeyboard": "키보드 닫기", - "dismissKeyboardHint": "소프트웨어 키보드를 숨기고 Markdown 편집기를 열린 상태로 유지합니다.", + "previewTruncated": "미리보기가 일부만 표시됩니다.", "readOnly": "읽기 전용" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/pt.json b/mobile/src/i18n/locales/pt.json index fb83a84674d..ffa929cb422 100644 --- a/mobile/src/i18n/locales/pt.json +++ b/mobile/src/i18n/locales/pt.json @@ -2260,8 +2260,7 @@ "copyPathLabel": "Copiar caminho do arquivo Markdown", "copySource": "Copiar código-fonte Markdown", "discard": "Descartar", - "dismissKeyboard": "Ocultar teclado", - "dismissKeyboardHint": "Oculta o teclado virtual e mantém o editor Markdown aberto.", + "previewTruncated": "Pré-visualização truncada.", "readOnly": "Somente leitura" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/ru.json b/mobile/src/i18n/locales/ru.json index 9ced7c69b59..946c5ce0a27 100644 --- a/mobile/src/i18n/locales/ru.json +++ b/mobile/src/i18n/locales/ru.json @@ -2327,8 +2327,7 @@ "copyPathLabel": "Скопировать путь к файлу Markdown", "copySource": "Скопировать исходный текст Markdown", "discard": "Отменить изменения", - "dismissKeyboard": "Скрыть клавиатуру", - "dismissKeyboardHint": "Скрывает экранную клавиатуру и оставляет редактор Markdown открытым.", + "previewTruncated": "Показана часть файла.", "readOnly": "Только чтение" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/tr.json b/mobile/src/i18n/locales/tr.json index f103d17aec0..5e3a4d21824 100644 --- a/mobile/src/i18n/locales/tr.json +++ b/mobile/src/i18n/locales/tr.json @@ -2193,8 +2193,7 @@ "copyPathLabel": "Markdown yolunu kopyala", "copySource": "Markdown kaynağını kopyala", "discard": "Vazgeç", - "dismissKeyboard": "Klavyeyi gizle", - "dismissKeyboardHint": "Ekran klavyesini gizler ve Markdown düzenleyicisini açık tutar.", + "previewTruncated": "Önizleme kısaltıldı.", "readOnly": "Salt okunur" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/zh-Hant.json b/mobile/src/i18n/locales/zh-Hant.json index b41f7765fec..9c74b7b9ccd 100644 --- a/mobile/src/i18n/locales/zh-Hant.json +++ b/mobile/src/i18n/locales/zh-Hant.json @@ -2189,8 +2189,7 @@ "copyPathLabel": "複製 Markdown 路徑", "copySource": "複製 Markdown 原始碼", "discard": "放棄", - "dismissKeyboard": "收起鍵盤", - "dismissKeyboardHint": "隱藏螢幕鍵盤,並保持 Markdown 編輯器開啟。", + "previewTruncated": "預覽內容已截斷。", "readOnly": "唯讀" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/zh.json b/mobile/src/i18n/locales/zh.json index b99d10462d5..0e08b7072b4 100644 --- a/mobile/src/i18n/locales/zh.json +++ b/mobile/src/i18n/locales/zh.json @@ -2189,8 +2189,7 @@ "copyPathLabel": "复制 Markdown 文件路径", "copySource": "复制 Markdown 源码", "discard": "放弃", - "dismissKeyboard": "关闭键盘", - "dismissKeyboardHint": "隐藏软键盘,并保持 Markdown 编辑器打开。", + "previewTruncated": "预览已截断。", "readOnly": "只读" }, "nativeChatAttachActions": { diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts index f36beea592f..57c5300af27 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts @@ -20,6 +20,7 @@ export type BridgeInboundFramePort = { acceptState: (connection: BridgeConnectionSnapshot) => void acceptConnectionPath: (connection: BridgeConnectionSnapshot) => void acceptBack: () => void + acceptParked: () => void acceptTerminalKey: (key: BridgeTerminalKeyId, inputOwner?: string) => void } @@ -66,6 +67,9 @@ export function createBridgeInboundFrameReader( case 'back': port.acceptBack() return + case 'parked': + port.acceptParked() + return case 'terminalKey': port.acceptTerminalKey(message.key, message.inputOwner) return diff --git a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts index 2cef127bfe6..31458b9f69d 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts @@ -236,6 +236,8 @@ const BridgeHostMessageSchema = z.union([ }), // Back names no destination; only the native stack knows what screen lies beneath. z.object({ v: versionSchema, type: z.literal(BRIDGE_BACK_FRAME) }), + // Native booted this page ahead of its screen and keeps its ready for the screen that adopts it. + z.object({ v: versionSchema, type: z.literal('parked') }), // One press on the shell's key rail. Sent only to a page granted the rail, which knows the frame. z.object({ v: versionSchema, diff --git a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts index 11cc2190538..e9a62282aa2 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts @@ -198,6 +198,8 @@ export function createBridgeRpcClient(options: BridgeRpcClientOptions): BridgeRp acceptState: (connection) => acceptState(cache.apply(connection)), acceptConnectionPath: (connection) => acceptState(cache.applyPath(connection)), acceptBack: back.press, + // Only a page booted before its screen, with no init yet, is parked; the shell answers its ready on adoption. + acceptParked: handshake.stop, acceptTerminalKey: (key, inputOwner) => terminalKeys.accept(key, inputOwner) }) diff --git a/mobile/src/mobile-web-shell/generation-host-directories.ts b/mobile/src/mobile-web-shell/generation-host-directories.ts new file mode 100644 index 00000000000..fa56421bd66 --- /dev/null +++ b/mobile/src/mobile-web-shell/generation-host-directories.ts @@ -0,0 +1,27 @@ +import { joinUri } from './generation-cache-uri' +import type { GenerationDirectoryEntry, GenerationFileSystem } from './generation-store-file-system' +import { isHostCacheKey } from './host-cache-key' + +export const GENERATIONS_DIRECTORY_NAME = 'generations' + +// One directory per host under the cache root; anything else there is not the store's. +export async function listGenerationHostDirectories( + fs: GenerationFileSystem +): Promise { + const entries = await fs.list(fs.rootUri) + return entries.filter((entry) => entry.isDirectory && isHostCacheKey(entry.name)) +} + +// Count/evict only hosts with generations; evicting staged-only hosts would delete a tree awaiting commit. Sweeps still visit them. +export async function listActivatedGenerationHosts( + fs: GenerationFileSystem +): Promise { + const activated: string[] = [] + for (const host of await listGenerationHostDirectories(fs)) { + const generations = await fs.list(joinUri(fs.rootUri, host.name, GENERATIONS_DIRECTORY_NAME)) + if (generations.some((entry) => entry.isDirectory)) { + activated.push(host.name) + } + } + return activated +} diff --git a/mobile/src/mobile-web-shell/generation-store.test.ts b/mobile/src/mobile-web-shell/generation-store.test.ts index 257aeb9f58f..4d381f688ba 100644 --- a/mobile/src/mobile-web-shell/generation-store.test.ts +++ b/mobile/src/mobile-web-shell/generation-store.test.ts @@ -544,4 +544,22 @@ describe('an update staged behind a live page', () => { expect((await relaunched.readActiveGeneration(HOST))?.buildId).toBe(SECOND_BUILD) expect(await fs.fileExists(`${ROOT}/${HOST}/generations/${SECOND_BUILD}/index.html`)).toBe(true) }) + + it('lets a reader of a host’s build go before a commit or a removal deletes it', async () => { + const fs = createFakeFileSystem() + const onDisk: boolean[] = [] + let reading = BUILD + const store = createGenerationStore({ + fileSystem: fs, + beforeHostFilesDeleted: async (hostKey) => { + onDisk.push(await fs.fileExists(`${ROOT}/${hostKey}/generations/${reading}/manifest.json`)) + } + }) + await activate(store, HOST) + onDisk.length = 0 + await activate(store, HOST, buildResult(SECOND)) + reading = SECOND_BUILD + await store.deleteHostCache(HOST) + expect(onDisk).toEqual([true, true]) + }) }) diff --git a/mobile/src/mobile-web-shell/generation-store.ts b/mobile/src/mobile-web-shell/generation-store.ts index 73d2d0bcf91..67da4168d49 100644 --- a/mobile/src/mobile-web-shell/generation-store.ts +++ b/mobile/src/mobile-web-shell/generation-store.ts @@ -10,7 +10,12 @@ import { MANIFEST_FILE_NAME } from './generation-asset-path' import { parseGenerationManifest, readWaitingStage } from './generation-manifest-read' import { reusableAssetsOf, reusableAssetsOfHosts } from './generation-reuse' import { stagingAssetsOf } from './generation-staging-assets' -import type { GenerationDirectoryEntry, GenerationFileSystem } from './generation-store-file-system' +import type { GenerationFileSystem } from './generation-store-file-system' +import { + GENERATIONS_DIRECTORY_NAME, + listActivatedGenerationHosts, + listGenerationHostDirectories +} from './generation-host-directories' import { isHostCacheKey } from './host-cache-key' import type { MobileWebShellUpdateFailure } from './mobile-web-shell-update-failure' import { @@ -19,7 +24,6 @@ import { recordUpdateFailureIn } from './mobile-web-shell-update-failure-log' -const GENERATIONS_DIRECTORY_NAME = 'generations' const STAGING_DIRECTORY_NAME = 'tmp' export const MAX_CACHED_HOSTS = 6 @@ -66,6 +70,8 @@ export type GenerationStore = { export function createGenerationStore(options: { fileSystem: GenerationFileSystem + // Runs before a host's built files are deleted, so nothing still reading them outlives them. + beforeHostFilesDeleted?: (hostKey: string) => Promise }): GenerationStore { const fs = options.fileSystem const hostOrder = createGenerationHostOrder(fs) @@ -87,31 +93,15 @@ export function createGenerationStore(options: { const stagingRoot = (hostKey: string): string => joinUri(hostRoot(hostKey), STAGING_DIRECTORY_NAME) - async function listHostDirectories(): Promise { - const entries = await fs.list(fs.rootUri) - return entries.filter((entry) => entry.isDirectory && isHostCacheKey(entry.name)) - } - - // Count/evict only hosts with generations; evicting staged-only hosts would delete a tree awaiting commit. Sweeps still visit them. - async function listActivatedHosts(): Promise { - const activated: string[] = [] - for (const host of await listHostDirectories()) { - const generations = await fs.list(joinUri(fs.rootUri, host.name, GENERATIONS_DIRECTORY_NAME)) - if (generations.some((entry) => entry.isDirectory)) { - activated.push(host.name) - } - } - return activated - } - async function dropHostTree(hostKey: string): Promise { activeMemo.delete(hostKey) deferred.drop(hostKey) + await options.beforeHostFilesDeleted?.(hostKey) await fs.delete(hostRoot(hostKey)) } async function enforceHostLimit(order: readonly string[]): Promise { - const hosts = await listActivatedHosts() + const hosts = await listActivatedGenerationHosts(fs) // Unlisted hosts sort first after index loss; keep the just-activated host last so it survives eviction. const evicted = new Set( [...hosts] @@ -238,6 +228,7 @@ export function createGenerationStore(options: { if (!(await fs.fileExists(joinUri(staged.directory, MANIFEST_FILE_NAME)))) { throw new Error(`staged generation ${staged.buildId} is no longer on disk`) } + await options.beforeHostFilesDeleted?.(staged.hostKey) // Delete old generations before rename: a crash then leaves no activation, whereas renaming first can leave two with no way to choose. for (const entry of entries) { await fs.delete(joinUri(generations, entry.name)) @@ -276,7 +267,9 @@ export function createGenerationStore(options: { async function openReusable(hostKey: string): Promise { const hosts = [ hostKey, - ...(await listHostDirectories()).map((host) => host.name).filter((key) => key !== hostKey) + ...(await listGenerationHostDirectories(fs)) + .map((host) => host.name) + .filter((key) => key !== hostKey) ] // Reuse discovery must not clean up another shell's active or staged files. const reusable = await reusableAssetsOfHosts(fs, hosts, (key) => readActive(key, false)) @@ -290,7 +283,7 @@ export function createGenerationStore(options: { return } // Interrupted downloads may belong to a host this launch never opens, so visit every host's tmp tree. - for (const host of await listHostDirectories()) { + for (const host of await listGenerationHostDirectories(fs)) { // Unreadable (undefined) is not corrupt: leave that tree for a later launch rather than fail every read. const waiting = await readWaitingStage(fs, host.name, stagingRoot(host.name)).catch( () => undefined diff --git a/mobile/src/mobile-web-shell/home-spare-page.ts b/mobile/src/mobile-web-shell/home-spare-page.ts new file mode 100644 index 00000000000..1456e5909b1 --- /dev/null +++ b/mobile/src/mobile-web-shell/home-spare-page.ts @@ -0,0 +1,91 @@ +import { + claimSpareDocument, + discardSpareDocument, + prepareSpareDocument +} from '../../modules/orca-mobile-web-shell/src/spare-document' +import type { GenerationStore } from './generation-store' +import { generationDirectoryPath } from './generation-store-file-system' +import { deriveHostCacheKey } from './host-cache-key' +import { mintShellSessionId } from './shell-session-id' + +// A Home entry claims the spare about 0.2 s after the tap on a simulator; a native screen keeps it no longer. +const HOME_SPARE_CLAIM_GRACE_MS = 2000 + +// What JS last asked native to park, until a claim or a drop. Native may since have dropped it on +// its own (background, memory); this only saves the claim's native round trip when nothing can match. +let parkedDirectory: string | null = null +let dropTimer: ReturnType | null = null +// A prepare still reading the store when Home goes must not park a spare after the drop ran. +let homeShown = false + +function cancelDrop(): void { + if (dropTimer !== null) { + clearTimeout(dropTimer) + dropTimer = null + } +} + +// Boot one page from the first of `hostIds` (most recently connected first) that has a cached build. +export async function prepareHomeSparePage( + store: GenerationStore, + hostIds: readonly string[] +): Promise { + try { + for (const hostId of hostIds) { + const hostKey = deriveHostCacheKey(hostId) + const active = await store.readActiveGeneration(hostKey) + if (active === null) { + continue + } + if (!homeShown) { + return + } + const directory = generationDirectoryPath(active.directory) + const prepared = await prepareSpareDocument(directory, mintShellSessionId()) + if (prepared && !homeShown) { + await dropHomeSparePage() + } else if (prepared) { + parkedDirectory = directory + } + return + } + } catch { + // A spare only saves time; the next entry boots its own page without one. + } +} + +// The spare's session id when Home booted it from `directory`; the view mounted with it adopts that page. +export async function claimHomeSparePage(directory: string): Promise { + if (parkedDirectory !== directory) { + return null + } + parkedDirectory = null + cancelDrop() + try { + return await claimSpareDocument(directory) + } catch { + return null + } +} + +// Home is shown; a spare still inside the grace after leaving it stays. +export function enterHomeSparePage(): void { + homeShown = true + cancelDrop() +} + +// Home lost focus: a page opening from it claims the spare within the grace, anything else drops it. +export function leaveHomeSparePage(): void { + homeShown = false + cancelDrop() + dropTimer = setTimeout(() => { + dropTimer = null + void dropHomeSparePage() + }, HOME_SPARE_CLAIM_GRACE_MS) +} + +// Also runs before any host's built files go: that is rare, and a spare must not outlive its files. +export function dropHomeSparePage(): Promise { + parkedDirectory = null + return discardSpareDocument().catch(() => undefined) +} diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts index 1d7d38cdab3..d4c7b198524 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts @@ -165,6 +165,7 @@ async function mountRoute(fileSystem: FakeGenerationFileSystem): Promise createGenerationStore({ fileSystem }), mintSessionId: () => 'session-id', + claimSpareSessionId: async () => null, now: () => 0, setForegroundTimer: () => () => {} } diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts b/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts index e9aff1ac061..44e53bfd614 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts @@ -1,12 +1,9 @@ -import * as ExpoCrypto from 'expo-crypto' -import { encodeBase64Url } from '../transport/encryption/mobile-session-id-encoding' import { BRIDGE_READY_RETRY_MAX_MS } from './bridge/bridge-client-init-handshake' import type { GenerationStore } from './generation-store' import { processGenerationStore } from './process-generation-store' import { setForegroundTimer } from './foreground-timer' - -// Use 32 random base64url bytes: each mount/remount needs a fresh id for the view’s private origin. -const SESSION_ID_BYTES = 32 +import { claimHomeSparePage } from './home-spare-page' +import { mintShellSessionId } from './shell-session-id' // Allow five ready-backoff ceilings before treating a loaded document as silent; startup import failures may prevent every ready attempt. export const PAGE_READY_DEADLINE_MS = BRIDGE_READY_RETRY_MAX_MS * 5 @@ -17,6 +14,8 @@ export const DOCUMENT_LOAD_DEADLINE_MS = 20_000 export type MobileWebShellRuntime = { createStore(): GenerationStore mintSessionId(): string + // The session id of a page Home booted from this directory, so the view adopts it instead of a new one. + claimSpareSessionId(directory: string): Promise now(): number // Count only foreground time and return cancellation; tests replace this seam instead of waiting on wall time. setForegroundTimer(run: () => void, delayMs: number): () => void @@ -25,7 +24,8 @@ export type MobileWebShellRuntime = { export function createMobileWebShellRuntime(): MobileWebShellRuntime { return { createStore: processGenerationStore, - mintSessionId: () => encodeBase64Url(ExpoCrypto.getRandomBytes(SESSION_ID_BYTES)), + mintSessionId: mintShellSessionId, + claimSpareSessionId: claimHomeSparePage, now: Date.now, setForegroundTimer } diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts index 5af588e13bc..b023ae70955 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts @@ -103,6 +103,7 @@ describe('a download that reuses the cached generation', () => { runtime: { createStore: () => store, mintSessionId: () => 's', + claimSpareSessionId: async () => null, now: () => 0, setForegroundTimer: () => () => {} }, diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts index 05605735d45..c5995d21023 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts @@ -264,17 +264,20 @@ export async function runShellEffect( context.manifest.current = null await (effect.kind === 'download' ? download : stageUpdate)({ ...context, opened }) return - case 'open-generation': + case 'open-generation': { + // A remount mints its own id below; only a first open adopts a page Home booted. + const spare = await runtime.claimSpareSessionId(effect.directory) send({ type: 'activated', flow, generationDirectory: effect.directory, - sessionId: runtime.mintSessionId(), + sessionId: spare ?? runtime.mintSessionId(), buildId: effect.buildId, totalBytes: effect.totalBytes, elapsedMs: runtime.now() - context.startedAt }) return + } case 'remount': { const remount = (): void => send({ type: 'remounted', flow, sessionId: runtime.mintSessionId() }) diff --git a/mobile/src/mobile-web-shell/page-frames-without-host.ts b/mobile/src/mobile-web-shell/page-frames-without-host.ts new file mode 100644 index 00000000000..86e6c55ce88 --- /dev/null +++ b/mobile/src/mobile-web-shell/page-frames-without-host.ts @@ -0,0 +1,40 @@ +import { readBridgeClientMessage } from './bridge/bridge-envelope' +import { frameWithoutHostLine } from './shell-bridge-log-lines' +import { recordShellLifecycleLine } from './shell-lifecycle-line-recorder' + +export type FrameWithoutHostFacts = { hostId: string; clientReady: boolean; snapshotReady: boolean } + +export type PageFramesWithoutHost = { + /** A frame no host serves yet; `facts` is null when a retired session's host is still mounted. */ + receive: (sessionId: string, json: string, facts: FrameWithoutHostFacts | null) => void + /** Hands the page's latest ready for this session to the host just built for it, once. */ + replayReady: (sessionId: string, host: { receive: (json: string) => void }) => void +} + +// Keep the ready instead of dropping it, so init does not wait on the page's 50 ms to 2 s backoff. +export function createPageFramesWithoutHost(): PageFramesWithoutHost { + let loggedSessionId: string | null = null + let ready: { sessionId: string; json: string } | null = null + return { + receive: (sessionId, json, facts) => { + if (facts !== null && loggedSessionId !== sessionId) { + loggedSessionId = sessionId + recordShellLifecycleLine(facts.hostId, frameWithoutHostLine(facts)) + } + const read = readBridgeClientMessage(json) + if (read.ok && read.message.type === 'ready') { + ready = { sessionId, json } + } else if (read.ok && read.message.type === 'close') { + // The document that asked is gone, so its ready must not be answered. + ready = null + } + }, + replayReady: (sessionId, host) => { + const kept = ready + ready = null + if (kept?.sessionId === sessionId) { + host.receive(kept.json) + } + } + } +} diff --git a/mobile/src/mobile-web-shell/process-generation-store.ts b/mobile/src/mobile-web-shell/process-generation-store.ts index 205abf1145c..1087603b3e0 100644 --- a/mobile/src/mobile-web-shell/process-generation-store.ts +++ b/mobile/src/mobile-web-shell/process-generation-store.ts @@ -1,11 +1,15 @@ import { createGenerationStore, type GenerationStore } from './generation-store' import { createExpoGenerationFileSystem } from './generation-store-file-system' +import { dropHomeSparePage } from './home-spare-page' let processStore: GenerationStore | null = null // Share one store queue across native callers so host removal cannot interleave with generation/index/failure-log writes. export function processGenerationStore(): GenerationStore { - processStore ??= createGenerationStore({ fileSystem: createExpoGenerationFileSystem() }) + processStore ??= createGenerationStore({ + fileSystem: createExpoGenerationFileSystem(), + beforeHostFilesDeleted: dropHomeSparePage + }) return processStore } diff --git a/mobile/src/mobile-web-shell/shell-session-id.ts b/mobile/src/mobile-web-shell/shell-session-id.ts new file mode 100644 index 00000000000..3b28baf87e4 --- /dev/null +++ b/mobile/src/mobile-web-shell/shell-session-id.ts @@ -0,0 +1,9 @@ +import * as ExpoCrypto from 'expo-crypto' +import { encodeBase64Url } from '../transport/encryption/mobile-session-id-encoding' + +// Use 32 random base64url bytes: each mount/remount needs a fresh id for the view’s private origin. +const SESSION_ID_BYTES = 32 + +export function mintShellSessionId(): string { + return encodeBase64Url(ExpoCrypto.getRandomBytes(SESSION_ID_BYTES)) +} diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts index d18449d42b9..95ce881b9e4 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts @@ -14,6 +14,7 @@ import { import type { BridgeErrorCapture } from './bridge/bridge-error-capture' import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' import type { FakeRpcClient } from './bridge-host-test-fakes' +import type { PageHostSnapshot } from './use-page-host-snapshot' const doubles = vi.hoisted((): { client: FakeRpcClient | null } => ({ client: null })) @@ -82,6 +83,7 @@ function FakeShellView(props: { function Harness(props: { session: MobileWebShellSessionState sessionEstablished?: boolean + snapshot?: PageHostSnapshot | null posted: PostedFrame[] probe: Probe faults: BridgeErrorCapture[] @@ -121,7 +123,7 @@ function Harness(props: { props.probe.backPops += 1 return 'popped' }, - snapshot: SNAPSHOT, + snapshot: props.snapshot === undefined ? SNAPSHOT : props.snapshot, readStorage: () => ({ storage: STORAGE, storageOversize: [] }), onStorageWrite: (key, value) => props.probe.storageWrites.push({ key, value }), // Use fresh callbacks each render; rebuilding for them would settle pending requests. @@ -198,7 +200,8 @@ afterEach(async () => { async function mount( session: MobileWebShellSessionState, - sessionEstablished?: boolean + sessionEstablished?: boolean, + snapshot?: PageHostSnapshot | null ): Promise { const posted: PostedFrame[] = [] const probe: Probe = { @@ -219,6 +222,7 @@ async function mount( createElement(Harness, { session: next, ...(sessionEstablished === undefined ? {} : { sessionEstablished }), + ...(snapshot === undefined ? {} : { snapshot }), posted, probe, faults, @@ -312,3 +316,26 @@ describe('a session that handshook before this host existed', () => { expect(fakeClient().requests).toEqual([]) }) }) + +describe('a ready the page sent before its host existed', () => { + it('is answered with one init as soon as the host snapshot arrives', async () => { + const mounted = await mount(readyState('session-one'), undefined, null) + await mounted.deliver(clientFrame({ type: 'ready' })) + expect(mounted.posted).toEqual([]) + await act(async () => { + mounted.tree.update( + createElement(Harness, { + session: readyState('session-one'), + snapshot: SNAPSHOT, + posted: mounted.posted, + probe: mounted.probe, + faults: mounted.faults, + readies: mounted.readies + }) + ) + }) + expect(mounted.frames('session-one')).toEqual([ + expect.objectContaining({ type: 'init', sessionId: 'session-one', buildId: 'build-a' }) + ]) + }) +}) diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts index 04bfaa84363..07a5f2cba67 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts @@ -5,14 +5,14 @@ import type { BridgeTerminalKeyRail } from './bridge/bridge-terminal-key' import type { BridgePageGeometry } from './bridge/bridge-page-geometry' -import { useCallback, useEffect, useLayoutEffect, useRef } from 'react' +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import type { MobileWebShellBridgeMessagePayload, OrcaMobileWebShellViewHandle } from '../../modules/orca-mobile-web-shell/src' import { useHostClient } from '../transport/connection/host-client-hooks' import { createBridgeDiagnosticReporter } from './bridge-diagnostic-log' -import { bridgeDiagnosticLine, frameWithoutHostLine } from './shell-bridge-log-lines' +import { bridgeDiagnosticLine } from './shell-bridge-log-lines' import { recordShellLifecycleLine } from './shell-lifecycle-line-recorder' import type { BridgeColorScheme, BridgeInitRoute, BridgeUiLocale } from './bridge/bridge-envelope' import type { BridgeClearableRouteParam } from './bridge/bridge-route-update' @@ -27,6 +27,7 @@ import type { BridgeErrorCapture } from './bridge/bridge-error-capture' import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' import type { PageHostSnapshot } from './use-page-host-snapshot' import type { PageStorageForInit } from './page-storage-keys' +import { createPageFramesWithoutHost } from './page-frames-without-host' class BridgeViewGoneError extends Error { constructor() { @@ -135,7 +136,7 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW // Read identity lazily without rebuilding a live host just to refresh a string. const clientIdRef = useRef(clientId) const clientRef = useRef(client) - const droppedFrameLoggedRef = useRef(null) + const [framesWithoutHost] = useState(createPageFramesWithoutHost) // Update refs on every commit before host construction; native frames may arrive before passive effects. useLayoutEffect(() => { argsRef.current = args @@ -207,13 +208,14 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW hostRef.current = { sessionId, host } // Reset host-owned drop totals on rebuild so a new lower count cannot look like frames being recovered. latest.onBinaryFramesDropped(0) + framesWithoutHost.replayReady(sessionId, host) return () => { // Capture Back before disposal so the next host for this document inherits it. establishedBackRef.current = { sessionId, back: host.readSessionBack() } hostRef.current = null host.dispose() } - }, [buildId, client, sessionId, snapshot]) + }, [buildId, client, framesWithoutHost, sessionId, snapshot]) useEffect(() => { const mounted = hostRef.current @@ -246,25 +248,24 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW (event: MobileWebShellBridgeMessageEvent) => { const mounted = hostRef.current if (mounted === null || mounted.sessionId !== sessionId) { - if ( - mounted === null && - sessionId !== null && - droppedFrameLoggedRef.current !== sessionId - ) { - droppedFrameLoggedRef.current = sessionId - recordShellLifecycleLine( - argsRef.current.hostId, - frameWithoutHostLine({ - clientReady: clientRef.current !== null, - snapshotReady: argsRef.current.snapshot !== null - }) + if (sessionId !== null) { + framesWithoutHost.receive( + sessionId, + event.nativeEvent.json, + mounted === null + ? { + hostId: argsRef.current.hostId, + clientReady: clientRef.current !== null, + snapshotReady: argsRef.current.snapshot !== null + } + : null ) } return } mounted.host.receive(event.nativeEvent.json) }, - [sessionId] + [framesWithoutHost, sessionId] ), // Fenced on the session the same way inbound frames are: a host left over from a session this // render has moved past must not be handed this one's route. diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts index 65f65113c20..c5b70b1822f 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts @@ -264,7 +264,8 @@ afterEach(async () => { async function mount( store: GenerationStore, - setForegroundTimer?: MobileWebShellRuntime['setForegroundTimer'] + setForegroundTimer?: MobileWebShellRuntime['setForegroundTimer'], + claimSpareSessionId: MobileWebShellRuntime['claimSpareSessionId'] = async () => null ): Promise { const timers = createTimerSeam() // Mint distinct ids so a remount's replacement view can be told from the one it retires. @@ -297,6 +298,7 @@ async function mount( runtime: { createStore: () => store, mintSessionId: () => `session-${++minted}`, + claimSpareSessionId, now: () => 0, setForegroundTimer: setForegroundTimer ?? timers.setTimer } @@ -374,6 +376,19 @@ describe('the wait for the page to speak', () => { expect(mounted.states().at(-1)?.kind).toBe('ready') }) + it('opens a page Home booted under its session id, and remounts under a fresh one', async () => { + const fake = createFakeStore() + const mounted = await mount(fake.store, undefined, async () => 'home-spare') + fake.settleCacheRead(activeGeneration()) + await flush() + expect(mounted.states().at(-1)).toMatchObject({ kind: 'ready', sessionId: 'home-spare' }) + await act(async () => { + mounted.shellFailed('document-load-failed') + }) + await flush() + expect(mounted.states().at(-1)).toMatchObject({ kind: 'ready', sessionId: 'session-1' }) + }) + it('stays ready when the page speaks after document load and the timers fire', async () => { const mounted = await ready() await act(async () => { @@ -401,6 +416,7 @@ describe('the wait for the page to speak', () => { runtime: { createStore: () => fake.store, mintSessionId: () => 'session-id', + claimSpareSessionId: async () => null, now: () => 0, setForegroundTimer: createTimerSeam().setTimer } diff --git a/mobile/src/navigation/workspace-route.tsx b/mobile/src/navigation/workspace-route.tsx index 3e96d0a901d..5444a215ed5 100644 --- a/mobile/src/navigation/workspace-route.tsx +++ b/mobile/src/navigation/workspace-route.tsx @@ -1,6 +1,6 @@ -import type { ReactNode } from 'react' +import { useContext, type ReactNode } from 'react' import { useLocalSearchParams } from 'expo-router' -import { normalizeExecutionHostId } from '../../../src/shared/execution-host' +import { normalizeExecutionHostId, type ExecutionHostId } from '../../../src/shared/execution-host' import { firstParam } from './route-param-reader' import { WorkspaceExecutionHostContext } from './workspace-execution-host' import { @@ -22,14 +22,36 @@ export function WorkspaceRoute({ children }: { children: ReactNode }) { hostId?: string | string[] executionHost?: string | string[] }>() - const hostId = firstParam(params.hostId) - const executionHost = normalizeExecutionHostId(firstParam(params.executionHost)) ?? undefined + return ( + + {children} + + ) +} + +/** A route's execution scope for one workspace; screens that show another workspace in place nest their own. */ +export function WorkspaceExecutionScope({ + hostId, + executionHost, + children +}: { + hostId: string + executionHost: ExecutionHostId | undefined + children: ReactNode +}) { const { client, state } = useHostClient(hostId) - const desktopGates = useOptionalHostProtocolGates() + const outerServer = useContext(WorkspaceServerContext) + const contextGates = useOptionalHostProtocolGates() + // Nested in a server's scope, the gates in context are that server's, not the desktop's. + const desktopGates = outerServer ? (outerServer.desktopGates ?? null) : contextGates const { routeHost, server } = useWorkspaceServer({ client, connState: state, desktopCapabilities: desktopGates?.hostCapabilities ?? NO_CAPABILITIES, + desktopGates, executionHost }) // Settled desktop status cannot become reachable by keeping this spinner open. @@ -41,9 +63,19 @@ export function WorkspaceRoute({ children }: { children: ReactNode }) { {children} ) - return server ? ( - - + if (server) { + return ( + + + {screens} + + + ) + } + // A desktop workspace shown inside a server's scope goes back to desktop routing and gates. + return outerServer ? ( + + {screens} diff --git a/mobile/src/new-workspace/NewWorkspacePageScreen.tsx b/mobile/src/new-workspace/NewWorkspacePageScreen.tsx index 87d2dd18388..c067d406cfa 100644 --- a/mobile/src/new-workspace/NewWorkspacePageScreen.tsx +++ b/mobile/src/new-workspace/NewWorkspacePageScreen.tsx @@ -20,7 +20,7 @@ export function NewWorkspacePageScreen() { const { hostCapabilities } = useHostProtocolGates() const connected = connState === 'connected' const worktrees = useHostWorktreeRows(client, connected, hostId) - const hostLabelById = useHostLabelById(client, connected) + const hostLabelById = useHostLabelById(client, connected, hostId) const worktreePaths = useMemo(() => worktrees.map((worktree) => worktree.path), [worktrees]) return ( diff --git a/mobile/src/new-workspace/use-host-label-by-id.ts b/mobile/src/new-workspace/use-host-label-by-id.ts index 40f56029255..6ea165fc630 100644 --- a/mobile/src/new-workspace/use-host-label-by-id.ts +++ b/mobile/src/new-workspace/use-host-label-by-id.ts @@ -1,32 +1,26 @@ -import { useEffect, useState } from 'react' +import { useMemo } from 'react' import type { ExecutionHostId } from '../../../src/shared/execution-host' -import { readHostSshTargetLabels } from '../host-screen/host-ssh-target-labels-read' +import { + HOST_LIST_TARGET, + hostRepoLabelsQuery, + NO_HOST_LIST_INPUT +} from '../host-screen/host-list-queries' +import { useHostQuery } from '../query/host-query' import type { RpcClient } from '../transport/rpc/rpc-client-contract' const NO_HOST_LABELS: ReadonlyMap = new Map() +// The host list's labels: the drawer shows the stored ones at once and the read refreshes them. export function useHostLabelById( client: RpcClient | null, - connected: boolean + connected: boolean, + hostId: string ): ReadonlyMap { - const [labels, setLabels] = useState(NO_HOST_LABELS) - - useEffect(() => { - if (!client || !connected) { - return - } - let live = true - readHostSshTargetLabels(client) - .then(({ hostLabelById }) => { - if (live) { - setLabels(hostLabelById) - } - }) - .catch(() => {}) - return () => { - live = false - } - }, [client, connected]) - - return labels + const { data } = useHostQuery( + hostRepoLabelsQuery, + { hostId, client: connected ? client : null }, + HOST_LIST_TARGET, + NO_HOST_LIST_INPUT + ) + return useMemo(() => (data ? new Map(data.hostLabels) : NO_HOST_LABELS), [data]) } diff --git a/mobile/src/platform/on-device-speech.ts b/mobile/src/platform/on-device-speech.ts index 06c08ca49ce..143c56c3317 100644 --- a/mobile/src/platform/on-device-speech.ts +++ b/mobile/src/platform/on-device-speech.ts @@ -1,6 +1,6 @@ import type { OnDeviceSpeech } from './on-device-speech-contract' // The session screen is a page in the shell (on-device-speech.web.ts); native screens dictate through the computer. -export function useOnDeviceSpeech(): OnDeviceSpeech | null { +export function useOnDeviceSpeech(_removeFillerWords?: boolean): OnDeviceSpeech | null { return null } diff --git a/mobile/src/platform/on-device-speech.web.test.tsx b/mobile/src/platform/on-device-speech.web.test.tsx new file mode 100644 index 00000000000..03da733f3f7 --- /dev/null +++ b/mobile/src/platform/on-device-speech.web.test.tsx @@ -0,0 +1,67 @@ +// Text the phone recognizes itself gets the computer's filler removal, in the language the recognizer started in. +import { createElement } from 'react' +import { act, create } from 'react-test-renderer' +import { describe, expect, it, vi } from 'vitest' +import type { OnDeviceSpeech } from './on-device-speech-contract' + +vi.mock('../mobile-web-shell/bridge/use-native-verbs', () => { + const verbs = { + canRecognizeSpeech: true, + speechStatus: async () => ({ status: 'ready', locale: 'de-DE', preference: 'automatic' }), + speechStart: async () => ({ started: true, locale: 'de-DE', reason: null }), + speechRead: async () => ({ + revision: 1, + committed: 'Äh, das ist um fünf Uhr.', + tentative: 'ähm', + failure: null + }), + speechFinish: async () => ({ + text: 'Äh, das ist, ähm, um fünf Uhr fertig.', + failure: null + }), + speechCancel: async () => ({}) + } + return { useNativeVerbs: () => verbs } +}) + +vi.mock('./on-device-speech-locale', () => ({ onDeviceSpeechLocale: () => 'de-DE' })) + +import { useOnDeviceSpeech } from './on-device-speech.web' + +function mountSpeech(removeFillerWords: boolean): OnDeviceSpeech { + let speech: OnDeviceSpeech | null = null + function Probe(): null { + speech = useOnDeviceSpeech(removeFillerWords) + return null + } + act(() => { + create(createElement(Probe)) + }) + if (speech === null) { + throw new Error('no on-device speech') + } + return speech +} + +describe('on-device dictation text', () => { + it('drops the fillers of the language the recognizer started in', async () => { + const speech = mountSpeech(true) + await speech.start() + + expect(await speech.read()).toMatchObject({ committed: 'Das ist um fünf Uhr.', tentative: '' }) + expect(await speech.finish()).toEqual({ + text: 'Das ist um fünf Uhr fertig.', + failure: null + }) + }) + + it('keeps every word when the computer turned filler removal off', async () => { + const speech = mountSpeech(false) + await speech.start() + + expect(await speech.finish()).toEqual({ + text: 'Äh, das ist, ähm, um fünf Uhr fertig.', + failure: null + }) + }) +}) diff --git a/mobile/src/platform/on-device-speech.web.ts b/mobile/src/platform/on-device-speech.web.ts index b11eed5ddda..00a8c777803 100644 --- a/mobile/src/platform/on-device-speech.web.ts +++ b/mobile/src/platform/on-device-speech.web.ts @@ -1,14 +1,43 @@ -import { useMemo } from 'react' +import { useLayoutEffect, useMemo, useRef } from 'react' +import { createDictationTextPipeline } from '../../../src/shared/dictation-text-pipeline' import { useNativeVerbs, type NativeVerbs } from '../mobile-web-shell/bridge/use-native-verbs' import type { OnDeviceSpeech } from './on-device-speech-contract' import { onDeviceSpeechLocale } from './on-device-speech-locale' -function createPageOnDeviceSpeech(verbs: NativeVerbs): OnDeviceSpeech { +const keepText = (text: string): string => text + +// The phone's recognizer transcribes only the locale it started in, so that locale's language picks the fillers, as the host does for its model. +function phoneDictationTextCleaner( + locale: string | null, + removeFillerWords: boolean +): (text: string) => string { + const language = locale?.split('-')[0].toLowerCase() + const clean = createDictationTextPipeline(language ? { language } : undefined, { + removeFillerWords + }) + return clean ?? keepText +} + +function createPageOnDeviceSpeech( + verbs: NativeVerbs, + removeFillerWords: () => boolean +): OnDeviceSpeech { + let clean = keepText return { status: () => verbs.speechStatus(onDeviceSpeechLocale()), - start: () => verbs.speechStart(onDeviceSpeechLocale()), - read: verbs.speechRead, - finish: verbs.speechFinish, + start: async () => { + const started = await verbs.speechStart(onDeviceSpeechLocale()) + clean = phoneDictationTextCleaner(started.locale, removeFillerWords()) + return started + }, + read: async () => { + const read = await verbs.speechRead() + return { ...read, committed: clean(read.committed), tentative: clean(read.tentative) } + }, + finish: async () => { + const finished = await verbs.speechFinish() + return finished.text === null ? finished : { ...finished, text: clean(finished.text) } + }, // Cancel has no reply anyone waits on; a shell that lost the session has nothing to stop. cancel: () => { void verbs.speechCancel().catch(() => undefined) @@ -17,7 +46,18 @@ function createPageOnDeviceSpeech(verbs: NativeVerbs): OnDeviceSpeech { } // Null on a shell without the verb, so dictation stays on the computer exactly as before. -export function useOnDeviceSpeech(): OnDeviceSpeech | null { +// removeFillerWords is the computer's switch, read at each start. +export function useOnDeviceSpeech(removeFillerWords = true): OnDeviceSpeech | null { const verbs = useNativeVerbs() - return useMemo(() => (verbs.canRecognizeSpeech ? createPageOnDeviceSpeech(verbs) : null), [verbs]) + const removeFillerWordsRef = useRef(removeFillerWords) + useLayoutEffect(() => { + removeFillerWordsRef.current = removeFillerWords + }, [removeFillerWords]) + return useMemo( + () => + verbs.canRecognizeSpeech + ? createPageOnDeviceSpeech(verbs, () => removeFillerWordsRef.current) + : null, + [verbs] + ) } diff --git a/mobile/src/query/first-paint-query-keys.ts b/mobile/src/query/first-paint-query-keys.ts index 609962e2284..b916cae5a07 100644 --- a/mobile/src/query/first-paint-query-keys.ts +++ b/mobile/src/query/first-paint-query-keys.ts @@ -2,6 +2,9 @@ import { normalizeExecutionHostId } from '../../../src/shared/execution-host' import { HOST_LIST_TARGET, hostRepoCatalogQuery, + hostRepoLabelsQuery, + hostServerWorkspacesInput, + hostServerWorkspacesQuery, hostWorktreeCatalogKey, hostWorktreeCatalogQuery, NO_HOST_LIST_INPUT @@ -37,15 +40,38 @@ export function firstPaintQueryKeys(hostId: string, route: URL): PersistedHostQu if (screen === 'tasks') { return firstPaintTaskKeys(hostId) } + if (screen === 'new-workspace') { + // The drawer's existing-workspace check and host labels. + return [ + persistedHostQueryKey(hostWorktreeCatalogQuery, hostWorktreeCatalogKey(hostId)), + persistedHostQueryKey( + hostRepoLabelsQuery, + hostQueryKey(hostId, hostRepoLabelsQuery.family, HOST_LIST_TARGET, NO_HOST_LIST_INPUT) + ) + ].filter((key) => key !== null) + } const keys = screen === undefined ? [ persistedHostQueryKey(hostWorktreeCatalogQuery, hostWorktreeCatalogKey(hostId)), persistedHostQueryKey(hostViewFamily, hostViewKey(hostId)), + persistedHostQueryKey( + hostServerWorkspacesQuery, + hostQueryKey( + hostId, + hostServerWorkspacesQuery.family, + HOST_LIST_TARGET, + hostServerWorkspacesInput(null) + ) + ), persistedHostQueryKey( hostRepoCatalogQuery, hostQueryKey(hostId, hostRepoCatalogQuery.family, HOST_LIST_TARGET, NO_HOST_LIST_INPUT) ), + persistedHostQueryKey( + hostRepoLabelsQuery, + hostQueryKey(hostId, hostRepoLabelsQuery.family, HOST_LIST_TARGET, NO_HOST_LIST_INPUT) + ), persistedHostQueryKey( hostProjectSectionsQuery, hostQueryKey( diff --git a/mobile/src/query/host-query-persistence.test.ts b/mobile/src/query/host-query-persistence.test.ts index 2095297f0c4..4439806d94c 100644 --- a/mobile/src/query/host-query-persistence.test.ts +++ b/mobile/src/query/host-query-persistence.test.ts @@ -1,8 +1,12 @@ -import { QueryClient } from '@tanstack/react-query' +import { hashKey, QueryClient } from '@tanstack/react-query' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { OrcaQueryStoreBackend } from '../device-store/query-storage' import { hostWorktreeCatalogKey, hostWorktreeCatalogQuery } from '../host-screen/host-list-queries' -import { createHostQueryPersistence, persistedHostQueryKey } from './host-query-persistence' +import { + createHostQueryPersistence, + holdsRestoredHostQueryData, + persistedHostQueryKey +} from './host-query-persistence' vi.mock('react-native', () => ({ AppState: {} })) @@ -119,4 +123,44 @@ describe('createHostQueryPersistence', () => { expect(relaunched.getQueryData(key)).toBe(live) }) + + it.each([ + { replaceOnHearing: false, expected: [true, false] }, + { replaceOnHearing: true, expected: [true, false, false] } + ])( + "marks restored data as an earlier launch's before anyone hears of it, until this launch's own answer (a listener's replacement: $replaceOnHearing)", + async ({ replaceOnHearing, expected }) => { + const store = memoryStore('host-a') + await storeFromEarlierLaunch(store, [liveRow]) + + const relaunched = new QueryClient() + const persistence = createHostQueryPersistence(relaunched, store.backend) + relaunched.getQueryCache().build(relaunched, { + queryKey: key, + meta: { persist: hostWorktreeCatalogQuery.persist } + }) + const heard: boolean[] = [] + const replacement = { snapshotId: 'snap-8', worktrees: [liveRow] } + relaunched.getQueryCache().subscribe((event) => { + if (event.type === 'updated' && event.action.type === 'success') { + heard.push(holdsRestoredHostQueryData(relaunched, hashKey(key))) + // A listener replacing the restored rows as it hears of them. + if (replaceOnHearing && heard.length === 1) { + relaunched.setQueryData(key, replacement, { updatedAt: SAVED_AT - 2 }) + } + } + }) + const restoring = persistence.restore(firstPaint) + await vi.runAllTimersAsync() + await restoring + // A live answer timed before the stored one, as after a clock correction, is still this launch's. + relaunched.setQueryData( + key, + { snapshotId: 'snap-8', worktrees: [liveRow] }, + { updatedAt: SAVED_AT - 1 } + ) + + expect(heard).toEqual(expected) + } + ) }) diff --git a/mobile/src/query/host-query-persistence.ts b/mobile/src/query/host-query-persistence.ts index 9edf0f556df..ccca23f3207 100644 --- a/mobile/src/query/host-query-persistence.ts +++ b/mobile/src/query/host-query-persistence.ts @@ -136,6 +136,8 @@ export function createHostQueryPersistence( const missedAtBoot = new Set() const triedOnMiss = new WeakSet() const restored = new Set() + // The key a restore is writing, so its own success leaves the mark. + let applyingRestore: string | null = null restoredKeys.set(queryClient, restored) function storedData(queryHash: string, data: unknown, persist: HostQueryPersist) { @@ -204,8 +206,14 @@ export function createHostQueryPersistence( if (queryClient.getQueryData(queryKey) === undefined) { const { data, dataUpdatedAt } = record.state settledAt.set(queryHash, dataUpdatedAt) - queryClient.setQueryData(queryKey, data, { updatedAt: dataUpdatedAt }) + // Marked first: listeners told of this write must already see it as an earlier launch's. restored.add(queryHash) + applyingRestore = queryHash + try { + queryClient.setQueryData(queryKey, data, { updatedAt: dataUpdatedAt }) + } finally { + applyingRestore = null + } } settle() }) @@ -252,7 +260,12 @@ export function createHostQueryPersistence( if (event.type !== 'updated' || event.action.type !== 'success') { return } - restored.delete(query.queryHash) + // Any write but the restore's own is this launch's, whatever its clock says; a listener's write during it included. + if (query.queryHash === applyingRestore) { + applyingRestore = null + } else { + restored.delete(query.queryHash) + } const family = familyOf(query.queryKey) const at = query.state.dataUpdatedAt if (family === null || at <= (settledAt.get(query.queryHash) ?? 0)) { diff --git a/mobile/src/query/host-query.ts b/mobile/src/query/host-query.ts index 4d65785430e..209ad828d2e 100644 --- a/mobile/src/query/host-query.ts +++ b/mobile/src/query/host-query.ts @@ -141,6 +141,28 @@ export async function readHostQueryLive( return data } +// A cached read through the screen's `read`: reuses a fresh answer and joins a read already out. An answer +// an event marked stale as it landed predates that change, so it is read again. +export async function fetchHostQuery( + queryClient: QueryClient, + query: HostQuery, + host: { hostId: string; client: RpcClient }, + target: HostQueryTarget, + input: TInput, + read: () => Promise +): Promise { + const options = { + ...hostQueryOptions(query, host.client, host.hostId, target, input), + queryFn: read + } + let data = await queryClient.fetchQuery(options) + // Each pass needs a newer event, so this ends with the event burst. + while (queryClient.getQueryState(options.queryKey)?.isInvalidated) { + data = await queryClient.fetchQuery(options) + } + return data +} + // A read ahead of the user: skipped while the key holds current data, joins a read already out. export function prefetchHostQuery( queryClient: QueryClient, diff --git a/mobile/src/session/MobileSessionHeader.tsx b/mobile/src/session/MobileSessionHeader.tsx index a37b0d2499d..c7593258e42 100644 --- a/mobile/src/session/MobileSessionHeader.tsx +++ b/mobile/src/session/MobileSessionHeader.tsx @@ -30,7 +30,6 @@ export function MobileSessionHeader({ const t = useMobileTranslation() const { hostId, - isFolderWorkspaceRoute, isFloatingWorkspaceRoute, presentedConnState, forceReconnectHost, @@ -61,8 +60,7 @@ export function MobileSessionHeader({ const tabsInTopBar = (layout.isLandscapePhone || sideRail) && hasTabs // Bar buttons otherwise leave less than two readable tabs on a narrow header. const actionsCollapsed = tabsInTopBar && (headerWidth ?? layout.width) < 600 - const sourceControlInBar = - !isFolderWorkspaceRoute && !isFloatingWorkspaceRoute && !actionsCollapsed + const sourceControlInBar = !isFloatingWorkspaceRoute && !actionsCollapsed const tabStrip = hasTabs ? ( boolean /** `refusedWhile`: what the phone showed the refused command waiting on. */ onError: MobileNativeChatSendErrorReporter + /** Called as a /clear goes out; the returned restore runs unless the host accepts it. */ + onClearSent?: () => () => void timeoutMs: number }): Promise { if ( @@ -98,6 +100,8 @@ export async function dispatchMobileStructuredCommand(input: { } } input.pending.current = true + const restoreClear = command === 'clear' ? input.onClearSent?.() : undefined + let accepted = false try { const result = await requestStructuredAgentSessionMutation({ @@ -133,6 +137,7 @@ export async function dispatchMobileStructuredCommand(input: { startFailures: input.startFailures(), say: sayMobileAgentSessionFailure }) + accepted = reply.accepted // A refusal names its cause only when the phone showed it, as on desktop. return { accepted: reply.accepted, @@ -146,6 +151,9 @@ export async function dispatchMobileStructuredCommand(input: { } } finally { input.pending.current = false + if (!accepted) { + restoreClear?.() + } } } }) diff --git a/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx b/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx index 434cdbfddd3..649307a056f 100644 --- a/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx +++ b/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx @@ -285,6 +285,7 @@ function MobileNativeChatOverlayContent({ status={session.status} error={session.error} readFailedFinally={session.readFailedFinally === true} + clearing={session.clearing === true} agent={controller.nativeChatAgent} sessionLive={controller.nativeChatSessionLive} agentWorking={controller.nativeChatTurnActive} diff --git a/mobile/src/session/native-chat/MobileNativeChatView.tsx b/mobile/src/session/native-chat/MobileNativeChatView.tsx index a98345f4ea4..b3eead5e801 100644 --- a/mobile/src/session/native-chat/MobileNativeChatView.tsx +++ b/mobile/src/session/native-chat/MobileNativeChatView.tsx @@ -77,6 +77,8 @@ type ChatViewProps = MobileNativeChatSendProps & error?: string // Permanent read failure replaces the pane because further chat actions cannot succeed. readFailedFinally?: boolean + /** A sent /clear hid the old rows: show a blank list until its divider lands, not the new-chat copy. */ + clearing?: boolean agent?: string | null sessionLive?: boolean /** The turn is live: working, or waiting on the reader. */ @@ -138,6 +140,7 @@ export function MobileNativeChatView({ status, error, readFailedFinally = false, + clearing = false, agent, sessionLive, agentWorking, @@ -235,7 +238,6 @@ export function MobileNativeChatView({ : (ask ?? permission ?? question ?? collapsedPrompt ?? awaitingInput) != null, send: onSend }) - const { lockReason } = offlineQueue const handleSend = useCallback( async (...send: Parameters): Promise => { // Retire the previous notice before this action can report a new one. @@ -313,10 +315,10 @@ export function MobileNativeChatView({ // Changing text scale relays out every row, so preserve the page’s reading anchor. const layoutKey = `${fontScale}` const footer = mobileNativeChatListFooter(liveStatus, turns.waitingRows, renderItem) - const emptyState = mobileNativeChatEmptyState(status, agent ?? null, error, sessionLive) + const emptyState = mobileNativeChatEmptyState(status, agent, error, sessionLive, clearing) const composerPlaceholder = mobileNativeChatComposerPlaceholder( - lockReason, + offlineQueue.lockReason, turnIndicator?.afterStop ) const promptOwnsInput = useMobileNativeChatPromptInputOwner( @@ -346,7 +348,7 @@ export function MobileNativeChatView({ collapsedPrompt={collapsedPrompt} /> diff --git a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.clear.test.tsx b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.clear.test.tsx new file mode 100644 index 00000000000..ba720a54a09 --- /dev/null +++ b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.clear.test.tsx @@ -0,0 +1,160 @@ +import { createElement } from 'react' +import { act, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentJournalRenderItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../../../src/shared/agent-session/agent-session-wire' +import { createWithQueryClient } from '../../../test-support/query-client-test-renderer' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import type { RpcResponse } from '../../../transport/rpc/rpc-wire-types' +import { useMobileStructuredAgentSession } from '../../use-mobile-structured-agent-session' +import { + SESSION_ID, + mutationOk, + ok, + snapshotEvent +} from './use-mobile-structured-agent-session-queued.test-fixture' + +vi.mock('@react-native-async-storage/async-storage', () => ({ + default: { getItem: vi.fn(async () => null), setItem: vi.fn(), removeItem: vi.fn() } +})) + +const row = ( + sequence: number, + role: 'user' | 'assistant', + text: string +): AgentJournalRenderItem => ({ + itemId: `row-${sequence}`, + sequence, + revision: 1, + observedAt: sequence, + body: { kind: 'message', role, blocks: [{ type: 'text', text }] } +}) +const divider = (sequence: number): AgentJournalRenderItem => ({ + ...row(sequence, 'assistant', ''), + body: { + kind: 'status', + text: 'Context cleared', + presentation: 'context-cleared', + contextClear: { operationId: `clear-${sequence}`, afterFence: 3, clearedAt: sequence } + } +}) +const dividerLands = (sequence: number): AgentSessionSubscribeEvent => ({ + type: 'batch', + sessionId: SESSION_ID, + batch: { + cursor: { epoch: 'epoch-1', sequence }, + items: [divider(sequence)], + removedItemIds: [], + submissions: [] + } +}) + +describe('useMobileStructuredAgentSession /clear', () => { + let renderer: ReactTestRenderer | null = null + afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + }) + + async function mount() { + let listener: ((value: unknown) => void) | null = null + let reply: ((response: RpcResponse) => void) | null = null + const client: Pick = { + getState: () => 'connected', + onStateChange: () => () => {}, + sendRequest: vi.fn(async (method: string): Promise => { + if (method === 'agentSession.options') { + return ok({ models: [], current: {}, conversationCommands: ['clear'] }) + } + if (method === 'agentSession.conversationCommand') { + return new Promise((resolve) => { + reply = resolve + }) + } + return ok({}) + }), + subscribe: vi.fn((method: string, _params: unknown, onData: (value: unknown) => void) => { + if (method === 'agentSession.subscribe') { + listener = onData + } + return () => {} + }) + } + const rendered: { hook: ReturnType | null } = { + hook: null + } + function Harness(): null { + rendered.hook = useMobileStructuredAgentSession({ + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the hook's request, subscription and connection members are provided. + client: client as RpcClient, + pairedHostClient: null, + sessionId: SESSION_ID, + enabled: true, + connected: true, + hostSupport: null, + agent: 'claude', + onSendError: vi.fn() + }) + return null + } + act(() => { + renderer = createWithQueryClient(createElement(Harness)) + }) + await vi.waitFor(() => expect(listener).toEqual(expect.any(Function))) + act(() => + listener?.( + snapshotEvent({ items: [row(1, 'user', 'question'), row(2, 'assistant', 'reply')] }) + ) + ) + await vi.waitFor(() => expect(rendered.hook?.conversationCommands).toEqual(['clear'])) + const shown = () => ({ + text: rendered.hook!.session.messages.flatMap((message) => + message.blocks.flatMap((block) => (block.type === 'text' ? [block.text] : [])) + ), + clearing: rendered.hook!.session.clearing + }) + const sendClear = async () => { + let outcome: Promise | undefined + act(() => { + outcome = rendered.hook!.sendWithOutcome('/clear') + }) + await vi.waitFor(() => expect(reply).toEqual(expect.any(Function))) + // Wrapped so awaiting the press does not wait for the reply. + return { outcome: outcome! } + } + return { + shown, + sendClear, + push: (event: AgentSessionSubscribeEvent) => act(() => listener?.(event)), + reply: async (value: unknown) => { + await act(async () => reply?.(mutationOk(value))) + } + } + } + + it('hides the old transcript from the press until the divider lands', async () => { + const chat = await mount() + expect(chat.shown()).toEqual({ text: ['question', 'reply'], clearing: false }) + + const { outcome } = await chat.sendClear() + expect(chat.shown()).toEqual({ text: [], clearing: true }) + + // The host's reply can reach the phone before the divider it already wrote. + await chat.reply({ command: 'clear', state: 'completed' }) + await expect(outcome).resolves.toBe('accepted') + expect(chat.shown()).toEqual({ text: [], clearing: true }) + + chat.push(dividerLands(3)) + expect(chat.shown()).toEqual({ text: ['Context cleared'], clearing: false }) + }) + + it('shows the old transcript again when the host refuses the /clear', async () => { + const chat = await mount() + const { outcome } = await chat.sendClear() + expect(chat.shown()).toEqual({ text: [], clearing: true }) + + await chat.reply({ command: 'clear', state: 'completed', error: 'Could not clear.' }) + await expect(outcome).resolves.toBe('rejected') + expect(chat.shown()).toEqual({ text: ['question', 'reply'], clearing: false }) + }) +}) diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.test.ts index 71281c9ca74..72d5595f366 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.test.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.test.ts @@ -3,14 +3,7 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send' import type { MobileNativeChatInputLockReason } from '../MobileNativeChatView' -import { - readMobileNativeChatDraftInputs, - updateMobileNativeChatDraftInputs -} from './mobile-native-chat-draft-inputs' -import { - resetMobileNativeChatDraftStoreForTests, - setMobileNativeChatDraftText -} from './mobile-native-chat-draft-store' +import { resetMobileNativeChatDraftStoreForTests } from './mobile-native-chat-draft-store' import { readMobileNativeChatOfflineSends, resetMobileNativeChatOfflineSendsForTests @@ -21,7 +14,6 @@ import { } from './use-mobile-native-chat-offline-sends' const SCOPE = 'host\0worktree\0tab' -const IMAGE = { id: 'chip-1', path: '/host/shot.png', previewUri: 'file:///shot.png' } type Send = (text: string, intent?: MobileNativeChatSendIntent) => Promise @@ -57,33 +49,6 @@ describe('useMobileNativeChatOfflineQueue', () => { resetMobileNativeChatDraftStoreForTests() }) - it('holds an offline send with its chips and sends it once on reconnect without touching the composer', async () => { - const send = vi.fn().mockResolvedValue(true) - await mount('disconnected', send) - setMobileNativeChatDraftText(SCOPE, 'check the PR tab') - updateMobileNativeChatDraftInputs(SCOPE, (inputs) => ({ ...inputs, images: [IMAGE] })) - - let accepted: boolean | undefined - await act(async () => { - accepted = await queue?.send('check the PR tab') - }) - - expect(accepted).toBe(true) - expect(send).not.toHaveBeenCalled() - expect(readMobileNativeChatDraftInputs(SCOPE).images).toEqual([]) - expect(readMobileNativeChatOfflineSends(SCOPE).map((queued) => queued.text)).toEqual([ - 'check the PR tab' - ]) - - setMobileNativeChatDraftText(SCOPE, 'a newer draft') - await reconnect(send) - - expect(send).toHaveBeenCalledOnce() - expect(send.mock.calls[0][0]).toBe('check the PR tab') - expect(send.mock.calls[0][1]?.queued?.images).toEqual([IMAGE]) - expect(readMobileNativeChatOfflineSends(SCOPE)).toEqual([]) - }) - it('pauses a queued message whose send fails and holds later sends behind it until Resume', async () => { const send = vi.fn().mockResolvedValue(false) await mount('disconnected', send) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx index b083cdfb3e8..b7cdfdd5a3c 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx @@ -28,14 +28,6 @@ import type { AgentSessionQueuedMessageMoveResult } from '../../../../../src/shared/agent-session/requests/agent-session-queued-message-wire' import type { StructuredAgentSessionMutationResult } from '../../mobile-structured-agent-session-rpc' -import { - MobileAgentMessageContext, - MobileAgentMessageOpenContext, - createMobileAgentMessageSource -} from '../transcript/mobile-agent-message-context' -import type { AgentMessageSource } from '../../../../../src/shared/agent-session/agent-session-message-source' -import { formatOrcaSessionAddress } from '../../../../../src/shared/orca-session-address' -import { testOrcaSessionId } from '../../../../../src/shared/orca-session-address-test-fixture' const rowRenders = vi.hoisted(() => ({ count: 0 })) vi.mock('../../MobileQueuedMessageCardRow', async (importOriginal) => { @@ -170,66 +162,6 @@ describe('MobileNativeChatQueuedMessages', () => { expect(sheet(mounted).props.visible).toBe(false) }) - it("names a queued message's sender as its chat is now titled, and opens that chat", async () => { - const coord = testOrcaSessionId('coord-chat') - const from: AgentMessageSource = { - kind: 'agent', - senders: [ - { - party: { - address: formatOrcaSessionAddress(coord), - terminalHandle: null, - orcaSessionId: coord - }, - name: 'Codex Chat', - relation: 'coordinator' - } - ], - orchestration: null - } - const source = createMobileAgentMessageSource() - source.update( - [ - { - type: 'agent-session', - id: `agent-session:${coord}`, - sessionId: coord, - agent: 'codex', - title: 'Release coordinator', - isActive: false - } - ], - [], - 0 - ) - const open = vi.fn() - const mounted = create(createElement('View')) - renderer = mounted - await act(async () => { - mounted.update( - createElement( - MobileAgentMessageOpenContext.Provider, - { value: open }, - createElement( - MobileAgentMessageContext.Provider, - { value: source }, - createElement(MobileNativeChatQueuedMessages, { - cards: [card({ messageId: 'q', from })] - }) - ) - ) - ) - }) - const sender = mounted.root.find( - (node) => - String(node.type) === 'Pressable' && - node.findAll((child) => child.children.includes('Release coordinator')).length > 0 - ) - expect(sender.props.accessibilityRole).toBe('button') - await act(async () => sender.props.onPress()) - expect(open).toHaveBeenCalledWith(from, from.senders[0]) - }) - it('the empty chord presses only the head card where its own button would, and offers it only while that press would act, across chat switches', async () => { let tray!: MobileNativeChatComposerTray function Tray(props: Parameters[0]['queued']) { diff --git a/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.test.ts b/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.test.ts index f6cc26d6363..676636c583d 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.test.ts +++ b/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.test.ts @@ -160,38 +160,6 @@ describe('MobileNativeChatSessionOptionPickers', () => { renderer = null }) - it('omits interaction mode from the drawer and model summary', async () => { - mount( - [ - MODEL_DESCRIPTOR, - { - id: 'interactionMode', - label: 'Mode', - category: 'mode', - kind: { - type: 'select', - currentValue: 'default', - choices: [ - { value: 'default', label: 'Build' }, - { value: 'plan', label: 'Plan' } - ] - }, - valueSource: 'dispatched', - transport: 'agent-session', - settable: true - } - ], - true, - 'interactionMode' - ) - expect(findAllByHostType(renderer!.root, 'BottomDrawer')).toHaveLength(0) - expect(pill('Model').props.accessibilityLabel).not.toMatch(/Build|Plan/) - act(() => pill('Model').props.onPress()) - expect(() => rowByText('Build')).toThrow('No row labeled Build') - expect(() => rowByText('Plan')).toThrow('No row labeled Plan') - expect(setOption).not.toHaveBeenCalled() - }) - it('consumes a refused page without replay, then permits a fresh open and permission pick', async () => { const placeholder: SessionOptionDescriptor = { ...MODEL_DESCRIPTOR, diff --git a/mobile/src/session/native-chat/mobile-native-chat-render-data.test.ts b/mobile/src/session/native-chat/mobile-native-chat-render-data.test.ts deleted file mode 100644 index 05e017fb0e4..00000000000 --- a/mobile/src/session/native-chat/mobile-native-chat-render-data.test.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' -import { - buildMobileNativeChatTransientData, - foldMobileNativeChatMessages -} from './mobile-native-chat-render-data' - -function assistant(id: string, text: string): NativeChatMessage { - return { - id, - role: 'assistant', - blocks: [{ type: 'text', text }], - timestamp: 0, - source: 'transcript' - } -} - -function user(id: string, text: string): NativeChatMessage { - return { id, role: 'user', blocks: [{ type: 'text', text }], timestamp: 0, source: 'transcript' } -} - -const fold = (messages: NativeChatMessage[]) => foldMobileNativeChatMessages(messages, 'claude') - -describe('buildMobileNativeChatTransientData', () => { - it('keeps the phone-local image visible when the transcript replaces its optimistic echo', () => { - const folded = fold([ - user('source', '[Image: source: /tmp/a.png]'), - user('prompt', '[Image #1] look at this') - ]) - const result = buildMobileNativeChatTransientData({ - folded, - streaming: null, - pending: [], - imagePreviewsByMessageId: { prompt: ['file:///phone-photo.jpg'] } - }) - - expect(result.data).toHaveLength(1) - expect(result.data[0]?.blocks).toEqual([ - { type: 'image-ref', path: '/tmp/a.png', url: 'file:///phone-photo.jpg' }, - { type: 'text', text: 'look at this' } - ]) - }) - - it('restores the local preview onto a marker-only transcript turn', () => { - const result = buildMobileNativeChatTransientData({ - folded: fold([user('prompt', '[Image #1]')]), - streaming: null, - pending: [], - imagePreviewsByMessageId: { prompt: ['file:///phone-photo.jpg'] } - }) - - expect(result.data[0]?.blocks).toEqual([{ type: 'image-ref', url: 'file:///phone-photo.jpg' }]) - }) -}) - -describe('foldMobileNativeChatMessages', () => { - function toolCall(id: string): NativeChatMessage { - return { - id, - role: 'assistant', - blocks: [{ type: 'tool-call', name: 'Bash', input: { command: 'command -v orca-ide' } }], - timestamp: 0, - source: 'transcript' - } - } - - function toolResult(id: string, output: string): NativeChatMessage { - return { - id, - role: 'tool', - blocks: [{ type: 'tool-result', output }], - timestamp: 0, - source: 'transcript' - } - } - - function planFrame(head: string): NativeChatMessage { - return { - id: 'plan', - role: 'system', - timestamp: 0, - source: 'transcript', - blocks: [ - { - type: 'text', - text: 'codex · notification:turn/plan/updated', - providerFrame: { - provider: 'codex', - kind: 'notification:turn/plan/updated', - payload: { head, byteLength: head.length, digest: 'digest', truncated: false } - } - } - ] - } - } - - it('draws a Codex plan update where it happened, as an update_plan call', () => { - const folded = fold([ - assistant('a1', 'Working.'), - toolCall('c1'), - toolResult('r1', 'ok'), - planFrame('{"plan":[{"step":"Port rows","status":"inProgress"}]}'), - toolCall('c2'), - toolResult('r2', 'ok') - ]) - expect(folded.map((message) => message.id)).toEqual(['a1', 'plan', 'c2']) - expect(folded[1]).toMatchObject({ - role: 'assistant', - blocks: [{ type: 'tool-call', name: 'update_plan', state: 'completed' }] - }) - }) -}) - -// Claude may consume queued commands without a user record; unmatched echoes must stay at their send position rather than trail every later turn. -describe("mobile shows the conversation, never a subagent's rows", () => { - it("keeps the spawn's one line and drops what the subagent said and did", () => { - const child = { agentId: 'task-1', producerKind: 'agent' as const } - const folded = fold([ - user('ask', 'review the PR'), - { - id: 'spawn', - role: 'system', - blocks: [{ type: 'text', text: 'Kicked off 1 subagent' }], - timestamp: 0, - source: 'transcript' - }, - { ...assistant('child-said', 'The PR is CLEAN.'), ...child }, - { - id: 'child-grep', - role: 'assistant', - blocks: [{ type: 'tool-call', name: 'Grep', input: {} }], - timestamp: 0, - source: 'transcript', - ...child - }, - assistant('answer', 'Delegated; nothing to fix.') - ]) - - expect(folded.map((message) => message.id)).toEqual(['ask', 'spawn', 'answer']) - expect(folded[2]?.blocks).toEqual([{ type: 'text', text: 'Delegated; nothing to fix.' }]) - }) -}) diff --git a/mobile/src/session/native-chat/mobile-native-chat-render-data.ts b/mobile/src/session/native-chat/mobile-native-chat-render-data.ts index d8f5893538b..9065b441ab8 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-render-data.ts +++ b/mobile/src/session/native-chat/mobile-native-chat-render-data.ts @@ -62,9 +62,11 @@ function mobileNativeChatEmptyStateCopy( export function mobileNativeChatEmptyState( status: MobileNativeChatStatus, - agent: string | null, + agent: string | null | undefined, error?: string, - sessionLive = false + sessionLive = false, + /** A sent /clear hid the old rows: a blank list until its divider lands, not new-chat copy. */ + clearing = false ): NativeChatEmptyStateCopy | null { const agentLabel = agent ? formatAgentTypeLabel(agent) @@ -77,7 +79,7 @@ export function mobileNativeChatEmptyState( case 'awaiting-transcript': return mobileNativeChatEmptyStateCopy(sessionLive ? 'empty' : 'notFound', agentLabel) case 'ready': - return mobileNativeChatEmptyStateCopy('empty', agentLabel) + return clearing ? null : mobileNativeChatEmptyStateCopy('empty', agentLabel) case 'error': { const copy = mobileNativeChatEmptyStateCopy('error', agentLabel) return error ? { ...copy, subtitle: describeLoadError(error, translate).message } : copy diff --git a/mobile/src/session/native-chat/mobile-native-chat-stale-input.test.ts b/mobile/src/session/native-chat/mobile-native-chat-stale-input.test.ts deleted file mode 100644 index 6b5dd57813c..00000000000 --- a/mobile/src/session/native-chat/mobile-native-chat-stale-input.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import '../../../../src/shared/agent-launch/startup/agent-tui-input-clear' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { RpcClient } from '../../transport/rpc/rpc-client-contract' -import { - healMobileNativeChatStaleInput, - isMobileNativeChatInputStale, - markMobileNativeChatInputStale, - resetMobileNativeChatStaleInputForTests -} from './mobile-native-chat-stale-input' - -function sendResult(accepted: boolean) { - return { - id: 'send', - ok: true as const, - result: { send: { accepted } }, - _meta: { runtimeId: 'runtime' } - } -} - -function makeClient(accepted = true): Pick { - return { sendRequest: vi.fn().mockResolvedValue(sendResult(accepted)) } -} - -describe('mobile native chat stale input markers', () => { - beforeEach(() => { - resetMobileNativeChatStaleInputForTests() - }) - - it('writes nothing when the terminal is not marked', async () => { - const client = makeClient() - await expect( - healMobileNativeChatStaleInput({ client, terminal: 'term-1', deviceToken: null }) - ).resolves.toBe(true) - expect(client.sendRequest).not.toHaveBeenCalled() - }) - - it('keeps the marker when the host rejects the clear', async () => { - const client = makeClient(false) - markMobileNativeChatInputStale('term-1') - await expect( - healMobileNativeChatStaleInput({ client, terminal: 'term-1', deviceToken: null }) - ).resolves.toBe(false) - expect(isMobileNativeChatInputStale('term-1')).toBe(true) - }) - - it('keeps the marker when the clear throws', async () => { - const client = { sendRequest: vi.fn().mockRejectedValue(new Error('offline')) } - markMobileNativeChatInputStale('term-1') - await expect( - healMobileNativeChatStaleInput({ client, terminal: 'term-1', deviceToken: null }) - ).resolves.toBe(false) - expect(isMobileNativeChatInputStale('term-1')).toBe(true) - }) -}) diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts index 31f565395c6..a6e395f3ff7 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts @@ -1,19 +1,12 @@ import { createElement, type ReactNode } from 'react' -import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import type { AgentJournalStatusItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' -import { isAdmissibleAgentJournalItemBody } from '../../../../../src/shared/agent-session/journal/agent-session-journal-schemas' import { projectStructuredItemToNativeChat } from '../../../../../src/shared/agent-session/view/structured-agent-session-projection' import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' -import { agentSessionFailureFact } from '../../../../../src/shared/agent-session/failures/agent-session-failure' -import { agentSessionFailureWords } from '../../../../../src/shared/agent-session/failures/agent-session-failure-words' import { colors } from '../../../theme/mobile-theme' import { activateMobileUiLocale } from '../../../i18n/mobile-i18n' import { MarkdownLinkHandlerContext } from '../../../components/markdown-link-handler' -import { - MobileNativeChatNoticeContext, - type MobileNativeChatNoticeView -} from '../../mobile-native-chat-notice-context' vi.mock('react-native', async () => { const React = await import('react') @@ -94,11 +87,6 @@ describe('MobileNativeChatMessage status notices', () => { return renderer! } - const markdownIn = (node: ReactTestInstance): string[] => - node - .findAll((child) => String(child.type) === 'MobileMarkdown') - .map((markdown) => markdown.props.content) - const statusRow = (body: AgentJournalStatusItem): NativeChatMessage => projectStructuredItemToNativeChat({ itemId: 'status', @@ -107,20 +95,6 @@ describe('MobileNativeChatMessage status notices', () => { observedAt: 2, body })! - const renderNotice = (body: AgentJournalStatusItem, names: MobileNativeChatNoticeView) => { - act(() => { - renderer = create( - createElement( - MobileNativeChatNoticeContext.Provider, - { value: names }, - createElement(MobileNativeChatMessage, { message: statusRow(body) }) - ) - ) - }) - return renderer!.root.findAll( - (node) => String(node.type) === 'Text' && node.props.selectable === true - )[0]! - } it('links a CI result line to its pull request and commit through the link sheet', () => { const openLink = vi.fn() @@ -164,93 +138,6 @@ describe('MobileNativeChatMessage status notices', () => { ]) }) - it.each(['with reset', 'from an old host'] as const)( - 'draws an OpenCode usage warning %s', - (source) => { - const hasReset = source === 'with reset' - const resetsAt = new Date(2026, 9, 15, 15, 42).getTime() - const now = vi.spyOn(Date, 'now').mockReturnValue(new Date(2026, 9, 15, 12).getTime()) - try { - const host = agentSessionFailureWords( - agentSessionFailureFact('usageLimitReached', { - detail: { - text: 'Internal error: Rate limit exceeded. Please try again later.', - audience: 'person' - }, - ...(hasReset ? { usageLimit: { resetsAt } } : {}) - }), - { surface: 'row', agentName: 'OpenCode' } - ) - expect(host.text).toBe('OpenCode hit its usage limit.') - const hostText = - source === 'from an old host' - ? 'OpenCode hit its usage limit. Send a message once it resets to continue.' - : host.text - const body: unknown = { kind: 'status', tone: 'warning', ...host, text: hostText } - if (!isAdmissibleAgentJournalItemBody(body) || body.kind !== 'status') { - throw new Error('Status fixture was not admitted') - } - const text = renderNotice(body, { hostName: null, agentName: 'OpenCode' }) - const tree = renderer! - // An old host's stored advice gives way to the headline from the fact; the reset sits below it. - expect(text.props.children).toBe('OpenCode hit its usage limit.') - expect( - tree.root - .findAll((node) => String(node.type) === 'Text') - .some((node) => /^Resets at \S/u.test(String(node.props.children))) - ).toBe(hasReset) - expect(Object.assign({}, ...text.props.style)).toMatchObject({ color: colors.statusAmber }) - expect(tree.root.find((node) => String(node.type) === 'AlertTriangle').props.color).toBe( - colors.statusAmber - ) - expect(markdownIn(tree.root)).toEqual([]) - const details = tree.root.find( - (node) => String(node.type) === 'Pressable' && node.props.accessibilityLabel === 'Details' - ) - expect(details.props['aria-expanded']).toBe(false) - act(() => details.props.onPress()) - expect( - tree.root - .findAll((node) => String(node.type) === 'Text') - .flatMap((node) => node.props.children) - ).toContain('Internal error: Rate limit exceeded. Please try again later.') - } finally { - now.mockRestore() - } - } - ) - - it.each([ - ['Claude', 'managed', 'claude auth login'], - ['Codex', 'system', 'codex login --device-auth'], - ['Codex', 'managed', null] - ] as const)( - 'offers %s (%s account) sign-in in a host terminal', - (agentName, account, command) => { - const onRunInTerminal = vi.fn() - renderNotice( - { - kind: 'status', - tone: 'error', - ...agentSessionFailureWords( - agentSessionFailureFact('notSignedIn', account ? { account } : {}), - { surface: 'row', agentName } - ) - }, - { hostName: null, agentName, onRunInTerminal } - ) - const signIn = renderer!.root.findAll( - (node) => String(node.type) === 'Pressable' && node.props.accessibilityHint !== undefined - ) - if (command === null) { - expect(signIn).toHaveLength(0) - return - } - act(() => signIn[0]!.props.onPress()) - expect(onRunInTerminal).toHaveBeenCalledWith(command) - } - ) - // Protocol-shaped synthetic frames, not a live-provider reproduction. it.each([ [ diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.test.ts b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.test.ts deleted file mode 100644 index 53b770d5d02..00000000000 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import './mobile-agent-message-renderer.test-fixture' - -import { createElement } from 'react' -import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { - NativeChatBackgroundTaskBlock, - NativeChatMessage -} from '../../../../../src/shared/native-chat/native-chat-types' -import { backgroundTaskJournalBody } from '../../../../../src/shared/native-chat/input/native-chat-background-task-row' -import { projectStructuredItemToNativeChat } from '../../../../../src/shared/agent-session/view/structured-agent-session-projection' - -import type { NativeChatResolvedPrompt } from '../../../../../src/shared/native-chat/native-chat-resolution-receipt' - -import type { AgentMessageSource } from '../../../../../src/shared/agent-session/agent-session-message-source' - -import { MobileNativeChatMessage } from './MobileNativeChatMessage' - -import { findAllByHostType } from '../../../test-support/react-test-renderer-host-nodes' - -vi.mock('@react-native-async-storage/async-storage', () => ({ - default: { getItem: async () => null, setItem: async () => {}, removeItem: async () => {} } -})) - -function userMessage(blocks: NativeChatMessage['blocks']): NativeChatMessage { - return { id: 'u1', role: 'user', blocks, timestamp: null, source: 'transcript' } -} - -describe('MobileNativeChatMessage', () => { - let renderer: ReactTestRenderer | null = null - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - }) - - function render( - message: NativeChatMessage, - props: { - fontScale?: number - structuredActivityUi?: boolean - activeTurnIsWorking?: boolean - trailingRun?: boolean - foldedAway?: boolean - turnExpanded?: boolean - turnStatus?: { - startedAt: number | null - thinking: boolean - workedSeconds: number | null - } | null - onToggleTurn?: () => void - reasoningIsLive?: boolean - unsentNotice?: string - receipt?: NativeChatResolvedPrompt - userMessageOpen?: boolean - onToggleUserMessage?: (messageId: string) => void - awaiting?: boolean - } = {} - ): ReactTestRenderer { - act(() => { - renderer = create(createElement(MobileNativeChatMessage, { message, ...props })) - }) - return renderer! - } - - const markdownIn = (node: ReactTestInstance): string[] => - node - .findAll((child) => String(child.type) === 'MobileMarkdown') - .map((markdown) => markdown.props.content) - const textIn = (node: ReactTestInstance): string[] => - findAllByHostType(node, 'Text').map((text) => String(text.children.join(''))) - - it.each(['task', 'generic'] as const)( - 'expands and refolds %s messages and preserves old-server body', - (kind) => { - const from: AgentMessageSource = { - kind: 'agent', - orchestration: - kind === 'task' ? { message: 'task', runId: 'r', taskId: 't', dispatchId: 'd' } : null, - senders: [] - } - const message = { - ...userMessage([ - { type: 'text' as const, text: 'Long paragraph wrapped over many native lines.' } - ]), - from - } - const tree = render(message) - const toggle = () => - findAllByHostType(tree.root, 'Pressable').find( - (node) => node.props.accessibilityState?.expanded !== undefined - )! - expect(markdownIn(tree.root)).toEqual([]) - expect(toggle().props.accessibilityState.expanded).toBe(false) - act(() => toggle().props.onPress()) - expect(markdownIn(tree.root)).toEqual(['Long paragraph wrapped over many native lines.']) - expect(toggle().props.accessibilityState.expanded).toBe(true) - act(() => toggle().props.onPress()) - expect(markdownIn(tree.root)).toEqual([]) - act(() => tree.unmount()) - const oldServer = render({ ...message, from: undefined }) - expect(oldServer.root.findAllByProps({ testID: 'agent-message-card' })).toHaveLength(0) - expect(markdownIn(oldServer.root)).toEqual([ - message.blocks[0].type === 'text' ? message.blocks[0].text : '' - ]) - } - ) - - it('draws a background task as its row, not the plain sentence written for older clients', () => { - const task = (overrides: Partial): NativeChatMessage => - projectStructuredItemToNativeChat({ - itemId: 'task', - revision: 1, - sequence: 1, - observedAt: 1, - body: backgroundTaskJournalBody({ - type: 'background-task', - taskId: 'b1', - kind: 'command', - label: 'pnpm test', - state: 'working', - startedAt: 1_000, - outputFile: '/tmp/b1.output', - ...overrides - }) - })! - const run = () => render(task({})).root.findByProps({ testID: 'background-task-run' }) - expect(textIn(run())).toEqual(['pnpm test', 'working', 'Output: /tmp/b1.output']) - act(() => renderer?.unmount()) - const settled = render( - task({ state: 'blocked', settledAt: 66_000, summary: 'Exited with code 1' }) - ) - expect(textIn(settled.root)).toEqual([ - 'pnpm test', - 'blocked · failed · 1m 5s', - 'Exited with code 1', - 'Output: /tmp/b1.output' - ]) - }) -}) diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatToolRun.test.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatToolRun.test.tsx index a9b9ddc0095..57f217b8611 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatToolRun.test.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatToolRun.test.tsx @@ -3,7 +3,6 @@ import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'rea import { afterEach, describe, expect, it, vi } from 'vitest' import type { NativeChatBlock } from '../../../../../src/shared/native-chat/native-chat-types' -import { MarkdownLinkHandlerContext } from '../../../components/markdown-link-handler' const scrolls = vi.hoisted(() => ({ toEnd: vi.fn(), to: vi.fn() })) @@ -66,8 +65,6 @@ vi.mock('../../../components/MobileSourceCopyButton', () => ({ })) vi.mock('../../../platform/external-link', () => ({ openExternalLink: vi.fn() })) vi.mock('../../../components/inline-text-selection', () => ({ INLINE_TEXT_SELECTION: false })) - -import { openExternalLink } from '../../../platform/external-link' import { ToolRun } from './MobileNativeChatToolRun' import { MobileNativeChatDisclosureContext, @@ -82,20 +79,6 @@ describe('ToolRun', () => { renderer = null }) - function render(blocks: NativeChatBlock[], onOpenLink: (url: string) => void): ReactTestRenderer { - act(() => { - renderer = create( - createElement( - MarkdownLinkHandlerContext.Provider, - { value: onOpenLink }, - createElement(ToolRun, { blocks }) - ) - ) - }) - openRun(renderer!) - return renderer! - } - function openRun(tree: ReactTestRenderer): void { act(() => { tree.root.findAll((node) => String(node.type) === 'Pressable')[0]!.props.onPress() @@ -107,40 +90,6 @@ describe('ToolRun', () => { .findAll((node) => String(node.type) === 'Text') .map((text) => String(text.children.join(''))) - describe('web search hits, handed to the chat link sheet', () => { - const openRow = (tree: ReactTestRenderer, label: string): void => { - act(() => { - tree.root - .findAll((node) => String(node.type) === 'Pressable') - .findLast((node) => textIn(node).includes(label))! - .props.onPress() - }) - } - - it('hands a web search hit to the chat link sheet when one is provided', () => { - vi.mocked(openExternalLink).mockClear() - const onOpenLink = vi.fn() - const tree = render( - [ - { - type: 'tool-call', - name: 'web_search', - input: { query: 'FlatList docs' }, - webSearchResults: [{ title: 'FlatList', url: 'https://reactnative.dev/docs/flatlist' }] - } - ], - onOpenLink - ) - openRow(tree, 'FlatList docs') - const hit = tree.root.findAll( - (node) => String(node.type) === 'Text' && node.props.accessibilityRole === 'link' - )[0]! - act(() => hit.props.onPress()) - expect(onOpenLink).toHaveBeenCalledWith('https://reactnative.dev/docs/flatlist') - expect(openExternalLink).not.toHaveBeenCalled() - }) - }) - describe("what the reader opened, kept above the list's recycled rows", () => { const blocks: NativeChatBlock[] = [ { type: 'tool-call', name: 'Bash', input: { command: 'ls' }, state: 'completed' }, diff --git a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-pinch-gesture.test.ts b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-pinch-gesture.test.ts deleted file mode 100644 index 8e91d95dcc5..00000000000 --- a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-pinch-gesture.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { createElement } from 'react' -import { act, create } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { quantizeFontScale } from './mobile-native-chat-message-text' - -const handlers: { start?: () => void; update?: (e: { scale: number }) => void } = {} - -vi.mock('react-native-gesture-handler', () => { - const pinch = { - runOnJS: () => pinch, - onStart: (cb: () => void) => { - handlers.start = cb - return pinch - }, - onUpdate: (cb: (e: { scale: number }) => void) => { - handlers.update = cb - return pinch - } - } - return { - Gesture: { Simultaneous: (...g: unknown[]) => g, Native: () => ({}), Pinch: () => pinch } - } -}) - -import { useMobileNativeChatPinchGesture } from './use-mobile-native-chat-pinch-gesture' - -describe('quantizeFontScale', () => { - it('snaps to the commit step and stays inside the supported range', () => { - expect(quantizeFontScale(1)).toBe(1) - expect(quantizeFontScale(1.01)).toBe(1) - expect(quantizeFontScale(1.024)).toBe(1) - expect(quantizeFontScale(1.03)).toBe(1.05) - expect(quantizeFontScale(5)).toBe(1.8) - expect(quantizeFontScale(0.1)).toBe(0.8) - expect(quantizeFontScale(Number.NaN)).toBe(1) - }) -}) - -describe('useMobileNativeChatPinchGesture', () => { - let renderer: ReturnType | null = null - let latest = 1 - - function Probe({ chat }: { chat: string }): null { - latest = useMobileNativeChatPinchGesture(chat).fontScale - return null - } - - beforeEach(() => { - latest = 1 - act(() => { - renderer = create(createElement(Probe, { chat: 'a' })) - }) - }) - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - }) - - // Each committed scale remeasures the whole list; raw/inadvertent pinches expose recycled-paragraph clipping, so commits must be quantized. - it('commits nothing for gesture noise the user cannot see', () => { - act(() => handlers.start?.()) - for (const scale of [1.001, 0.995, 1.008, 1.02, 0.982]) { - act(() => handlers.update?.({ scale })) - } - expect(latest).toBe(1) - }) - - it('commits a real pinch, on the step grid', () => { - act(() => handlers.start?.()) - act(() => handlers.update?.({ scale: 1.34 })) - expect(latest).toBe(1.35) - act(() => handlers.update?.({ scale: 1.37 })) - expect(latest).toBe(1.35) - act(() => handlers.update?.({ scale: 1.42 })) - expect(latest).toBe(1.4) - }) - - it('starts another chat in the same view at the default size', () => { - act(() => handlers.start?.()) - act(() => handlers.update?.({ scale: 1.34 })) - expect(latest).toBe(1.35) - act(() => renderer?.update(createElement(Probe, { chat: 'b' }))) - expect(latest).toBe(1) - }) -}) diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-session.ts b/mobile/src/session/native-chat/use-mobile-native-chat-session.ts index 93f6956dc93..c1952510c32 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-session.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-session.ts @@ -39,6 +39,8 @@ export type MobileNativeChatSession = { /** The read failed for good (damage, or a newer Orca's chat): the error says why, once, and * there is nothing to send into. */ readFailedFinally?: boolean + /** This phone's /clear is out and its divider has not landed: the old rows are hidden. */ + clearing?: boolean hasMore: boolean /** `olderPages === 'loading'`, kept because recorded RPC fixtures read it. */ loadingEarlier: boolean diff --git a/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.test.ts b/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.test.ts deleted file mode 100644 index b43cccdae12..00000000000 --- a/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { isRenderableImageUri } from './mobile-native-chat-image-preview' - -describe('isRenderableImageUri', () => { - it('rejects bare host paths (not loadable on the device) and empty values', () => { - for (const uri of [ - '/tmp/orca-attach.png', - 'C:\\tmp\\a.png', - 'orca-attach.png', - '', - undefined - ]) { - expect(isRenderableImageUri(uri)).toBe(false) - } - }) -}) diff --git a/mobile/src/session/tabs/active-session-tab.test.ts b/mobile/src/session/tabs/active-session-tab.test.ts index a76e257be33..8c16c28e0b3 100644 --- a/mobile/src/session/tabs/active-session-tab.test.ts +++ b/mobile/src/session/tabs/active-session-tab.test.ts @@ -12,35 +12,6 @@ function browserTab(id: string, isActive: boolean): Tab { } describe('resolveActiveSessionTab', () => { - it('keeps the device on its browser tab when a republication flags the agent terminal active', () => { - const result = resolveActiveSessionTab( - [terminalTab('agent', true), browserTab('browser', false)], - { - pendingActiveSessionTabId: null, - selectedSessionTabId: 'browser' - } - ) - - expect(result.activeTab?.id).toBe('browser') - expect(result.selectionSource).toBe('selected-tab') - expect(result.retainSelectedSessionTabId).toBe(false) - }) - - it('follows the host when it explicitly navigates this device', () => { - const result = resolveActiveSessionTab( - [terminalTab('agent', true), browserTab('browser', false)], - { - pendingActiveSessionTabId: null, - selectedSessionTabId: 'browser', - navigationIntent: 'follow' - } - ) - - expect(result.activeTab?.id).toBe('agent') - expect(result.selectionSource).toBe('navigation-intent') - expect(result.retainSelectedSessionTabId).toBe(false) - }) - it('lets explicit follow supersede an in-flight local activation', () => { const result = resolveActiveSessionTab( [terminalTab('agent', true), browserTab('browser', false)], @@ -71,41 +42,4 @@ describe('resolveActiveSessionTab', () => { ) expect(restored.activeTab?.id).toBe('browser') }) - - it('lets a pending activation win until the snapshot catches up', () => { - const result = resolveActiveSessionTab( - [terminalTab('agent', true), browserTab('browser', false)], - { - pendingActiveSessionTabId: 'browser', - selectedSessionTabId: 'agent' - } - ) - - expect(result.activeTab?.id).toBe('browser') - expect(result.selectionSource).toBe('pending-tab') - expect(result.clearPendingActiveSessionTabId).toBe(false) - }) - - it('clears the pending marker once the snapshot acknowledges it', () => { - const result = resolveActiveSessionTab( - [terminalTab('agent', false), browserTab('browser', true)], - { - pendingActiveSessionTabId: 'browser', - selectedSessionTabId: 'agent' - } - ) - - expect(result.activeTab?.id).toBe('browser') - expect(result.clearPendingActiveSessionTabId).toBe(true) - }) - - it('clears a stale pending marker whose tab is gone', () => { - const result = resolveActiveSessionTab([terminalTab('agent', true)], { - pendingActiveSessionTabId: 'removed', - selectedSessionTabId: null - }) - - expect(result.activeTab?.id).toBe('agent') - expect(result.clearPendingActiveSessionTabId).toBe(true) - }) }) diff --git a/mobile/src/session/tabs/mobile-session-create-warning-state.test.ts b/mobile/src/session/tabs/mobile-session-create-warning-state.test.ts deleted file mode 100644 index 123e1eacd12..00000000000 --- a/mobile/src/session/tabs/mobile-session-create-warning-state.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - createMobileSessionCreateWarningState, - dismissMobileSessionCreateWarningState, - reconcileMobileSessionCreateWarningState -} from './mobile-session-create-warning-state' - -describe('mobile session create warning state', () => { - it('preserves a dismissed warning while the route warning is unchanged', () => { - const dismissed = dismissMobileSessionCreateWarningState( - createMobileSessionCreateWarningState('Created, but setup failed') - ) - - expect(dismissed).toEqual({ source: 'Created, but setup failed', visible: '' }) - expect(reconcileMobileSessionCreateWarningState(dismissed, 'Created, but setup failed')).toBe( - dismissed - ) - }) - - it('shows a new warning when the route warning changes', () => { - const dismissed = dismissMobileSessionCreateWarningState( - createMobileSessionCreateWarningState('Old warning') - ) - - expect(reconcileMobileSessionCreateWarningState(dismissed, 'New warning')).toEqual({ - source: 'New warning', - visible: 'New warning' - }) - }) -}) diff --git a/mobile/src/session/tabs/mobile-tab-close-selection.test.ts b/mobile/src/session/tabs/mobile-tab-close-selection.test.ts deleted file mode 100644 index bfd912b16a8..00000000000 --- a/mobile/src/session/tabs/mobile-tab-close-selection.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { selectBulkCloseTabs } from './mobile-tab-close-selection' - -const tab = (id: string, isDirty?: boolean, isPinned?: boolean) => ({ - id, - ...(isDirty === undefined ? {} : { isDirty }), - ...(isPinned === undefined ? {} : { isPinned }) -}) - -describe('selectBulkCloseTabs', () => { - it('skips dirty tabs so unsaved edits survive a bulk close', () => { - const withDirty = [tab('a', true), tab('b'), tab('c', false), tab('d')] - expect(selectBulkCloseTabs(withDirty, 'b').map((t) => t.id)).toEqual(['c', 'd']) - }) - - it('skips pinned tabs', () => { - const withPinned = [tab('a', undefined, true), tab('b'), tab('c', undefined, true), tab('d')] - expect(selectBulkCloseTabs(withPinned, 'b').map((t) => t.id)).toEqual(['d']) - }) -}) diff --git a/mobile/src/session/tabs/opened-mobile-session-tab.test.ts b/mobile/src/session/tabs/opened-mobile-session-tab.test.ts deleted file mode 100644 index a20a9219477..00000000000 --- a/mobile/src/session/tabs/opened-mobile-session-tab.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { shouldActivateOpenedMobileSessionTab } from './opened-mobile-session-tab' - -describe('shouldActivateOpenedMobileSessionTab', () => { - const currentTerminalState = { - activationSeq: 2, - latestActivationSeq: 2, - sourceTerminalHandle: 'pty-1', - activeTerminalHandle: 'pty-1', - activeTabType: 'terminal' - } - - it('prevents an older tap from stealing focus from a newer tap', () => { - expect( - shouldActivateOpenedMobileSessionTab({ - ...currentTerminalState, - activated: false, - activationSeq: 1 - }) - ).toBe(false) - }) - - it('does not activate after the user leaves the source terminal', () => { - expect( - shouldActivateOpenedMobileSessionTab({ - ...currentTerminalState, - activated: false, - activeTabType: 'file', - activeTerminalHandle: null - }) - ).toBe(false) - expect( - shouldActivateOpenedMobileSessionTab({ - ...currentTerminalState, - activated: false, - activeTerminalHandle: 'pty-2' - }) - ).toBe(false) - }) - - it('allows a structured agent-session tab to anchor chat file activation', () => { - expect( - shouldActivateOpenedMobileSessionTab({ - activated: false, - activationSeq: 2, - latestActivationSeq: 2, - sourceTerminalHandle: null, - activeTerminalHandle: null, - sourceSessionTabId: 'agent-tab-1', - activeSessionTabId: 'agent-tab-1', - activeTabType: 'agent-session' - }) - ).toBe(true) - expect( - shouldActivateOpenedMobileSessionTab({ - ...currentTerminalState, - activated: false, - sourceTerminalHandle: null, - activeTerminalHandle: null, - sourceSessionTabId: 'agent-tab-1', - activeSessionTabId: 'agent-tab-2', - activeTabType: 'agent-session' - }) - ).toBe(false) - }) -}) diff --git a/mobile/src/session/tabs/pending-session-selection.test.ts b/mobile/src/session/tabs/pending-session-selection.test.ts index f35fb3edf4c..7ce839613dc 100644 --- a/mobile/src/session/tabs/pending-session-selection.test.ts +++ b/mobile/src/session/tabs/pending-session-selection.test.ts @@ -9,19 +9,6 @@ import { type PendingSessionSelection } from './pending-session-selection' -function terminalTab(id: string, terminal: string): MobileSessionTab { - const tab: MobileSessionTab = { - type: 'terminal', - id, - parentTabId: id, - leafId: 'leaf', - title: 'Terminal', - terminal, - isActive: false - } - return tab -} - function chatTab(id: string, sessionId: string): MobileSessionTab { const tab: MobileSessionTab = { type: 'agent-session', @@ -52,45 +39,12 @@ function reservedTerminalTab(terminal: string | null): MobileSessionTab { } describe('resolveLaunchedSelection', () => { - it('finds a launched chat by its session id, whatever its tab id is', () => { - const tabs = [chatTab('opaque-tab-7', 'claude_s1')] - expect( - resolveLaunchedSelection(launchedSelection('l1', { sessionId: 'claude_s1' }), tabs) - ).toEqual({ - selection: { kind: 'tab', tabId: 'opaque-tab-7' }, - landedTabId: 'opaque-tab-7' - }) - }) - - it('finds a launched terminal by the pane this device reserved, before any reply', () => { - const selection = launchedSelection('l1', { pane: PANE }, null) - expect(resolveLaunchedSelection(selection, [reservedTerminalTab('term_9')])).toEqual({ - selection: { kind: 'terminal', handle: 'term_9', tabId: `${PANE.tabId}::${PANE.leafId}` }, - landedTabId: `${PANE.tabId}::${PANE.leafId}` - }) - expect(resolveLaunchedSelection(selection, [reservedTerminalTab(null)]).selection).toEqual({ - kind: 'tab', - tabId: `${PANE.tabId}::${PANE.leafId}` - }) - }) - it('never takes a chat for the reserved pane: a chat is listed under its session', () => { const selection = launchedSelection('l1', { pane: PANE }, null) expect( resolveLaunchedSelection(selection, [chatTab(PANE.tabId, 'claude_other')]).landedTabId ).toBeNull() }) - - it("finds a terminal by the reply's handle when the host ignored the reservation", () => { - const tabs = [terminalTab('tab-2', 'term_9')] - const selection = withLaunchReply(launchedSelection('l1', { pane: PANE }, null), 'l1', { - handle: 'term_9' - }) - expect(resolveLaunchedSelection(selection, tabs)).toEqual({ - selection: { kind: 'terminal', handle: 'term_9', tabId: 'tab-2' }, - landedTabId: 'tab-2' - }) - }) }) describe("a launch's own reply and end", () => { @@ -103,13 +57,6 @@ describe("a launch's own reply and end", () => { expect(withoutUnansweredLaunch(pick, 'l1')).toBe(pick) expect(withoutUnansweredLaunch(newer, 'l1')).toBe(newer) }) - - it('drops a launch that ended unanswered and keeps one its reply named', () => { - const waiting = launchedSelection('l1', { pane: PANE }, null) - expect(withoutUnansweredLaunch(waiting, 'l1')).toBeNull() - const answered = withLaunchReply(waiting, 'l1', { handle: 'term_9' }) - expect(withoutUnansweredLaunch(answered, 'l1')).toBe(answered) - }) }) describe('isLaunchedSurfaceListed', () => { diff --git a/mobile/src/session/tabs/session-tab-snapshot-gate.test.ts b/mobile/src/session/tabs/session-tab-snapshot-gate.test.ts deleted file mode 100644 index 157972bf843..00000000000 --- a/mobile/src/session/tabs/session-tab-snapshot-gate.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - acceptSessionSnapshot, - applyClosedTabTombstones, - type AppliedSnapshotMarker -} from './session-tab-snapshot-gate' - -describe('acceptSessionSnapshot', () => { - it('rejects a strictly older version from the same publisher without moving the floor', () => { - const marker: AppliedSnapshotMarker = { epoch: 'renderer:a', version: 42 } - expect( - acceptSessionSnapshot({ publicationEpoch: 'renderer:a', snapshotVersion: 41 }, marker) - ).toBe(false) - expect(marker).toEqual({ epoch: 'renderer:a', version: 42 }) - }) - - it('accepts any version from a new publisher (epoch change) and resets the floor', () => { - const marker: AppliedSnapshotMarker = { epoch: 'renderer:a', version: 99 } - expect( - acceptSessionSnapshot({ publicationEpoch: 'headless:b', snapshotVersion: 1 }, marker) - ).toBe(true) - expect(marker).toEqual({ epoch: 'headless:b', version: 1 }) - }) -}) - -describe('applyClosedTabTombstones', () => { - const tab = (id: string): { id: string } => ({ id }) - - it('suppresses a tombstoned tab while it is still present and not expired', () => { - const tombstones = new Map([['a', 5000]]) - const result = applyClosedTabTombstones([tab('a'), tab('b')], tombstones, 1000) - expect(result.map((t) => t.id)).toEqual(['b']) - expect(tombstones.has('a')).toBe(true) - }) - - it('clears the tombstone once the publisher snapshot no longer includes the tab', () => { - const tombstones = new Map([['a', 5000]]) - const result = applyClosedTabTombstones([tab('b')], tombstones, 1000) - expect(result.map((t) => t.id)).toEqual(['b']) - expect(tombstones.has('a')).toBe(false) - }) - - it('stops suppressing and clears an expired tombstone even if still present', () => { - const tombstones = new Map([['a', 5000]]) - expect( - applyClosedTabTombstones([tab('a'), tab('b')], tombstones, 4999).map((t) => t.id) - ).toEqual(['b']) - expect(tombstones.has('a')).toBe(true) - const result = applyClosedTabTombstones([tab('a'), tab('b')], tombstones, 5000) - expect(result.map((t) => t.id)).toEqual(['a', 'b']) - expect(tombstones.has('a')).toBe(false) - }) -}) diff --git a/mobile/src/session/tabs/use-mobile-session-tab-switching.test.ts b/mobile/src/session/tabs/use-mobile-session-tab-switching.test.ts deleted file mode 100644 index 6f24b4198fb..00000000000 --- a/mobile/src/session/tabs/use-mobile-session-tab-switching.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -vi.mock('../../platform/haptics', () => ({ - triggerSelection: vi.fn() -})) -import type { - FileDocState, - MarkdownDocState -} from '../../files/session-documents/session-document-state' -import type { MobileSessionTab } from './mobile-session-tabs' -import { isCachedActiveDocumentRetap } from '../../files/session-documents/mobile-session-active-document-retap' - -const markdownTab: MobileSessionTab = { - type: 'markdown', - id: 'md', - title: 'Notes', - filePath: '/Notes.md', - relativePath: 'Notes.md', - isDirty: false, - isActive: true, - documentVersion: 'v1' -} - -const fileTab: MobileSessionTab = { - type: 'file', - id: 'file', - title: 'Main', - filePath: '/Main.ts', - relativePath: 'Main.ts', - isDirty: false, - isActive: true -} - -const readyMarkdown: MarkdownDocState = { - status: 'ready', - content: '# Notes', - localContent: '# Notes', - baseVersion: 'v1', - isDirty: false, - editable: true -} - -describe('isCachedActiveDocumentRetap', () => { - it('ignores a retap only while the open markdown or file document is already on screen', () => { - const docs = { - markdownDocs: new Map([['md', readyMarkdown]]), - fileDocs: new Map([ - ['file', { status: 'ready', kind: 'html', content: '

Hi

' }] - ]) - } - expect(isCachedActiveDocumentRetap(markdownTab, 'md', docs)).toBe(true) - expect(isCachedActiveDocumentRetap(fileTab, 'file', docs)).toBe(true) - expect(isCachedActiveDocumentRetap(markdownTab, 'other', docs)).toBe(false) - expect( - isCachedActiveDocumentRetap(markdownTab, 'md', { - ...docs, - markdownDocs: new Map([['md', { status: 'error', message: 'Missing' }]]) - }) - ).toBe(false) - expect( - isCachedActiveDocumentRetap( - { - type: 'terminal', - id: 'term', - title: 'Shell', - terminal: 'pty-1', - isActive: true - }, - 'term', - docs - ) - ).toBe(false) - }) -}) diff --git a/mobile/src/session/tabs/use-notification-pane-navigation.test.tsx b/mobile/src/session/tabs/use-notification-pane-navigation.test.tsx index a482b1ede4f..fe4ad3d36f4 100644 --- a/mobile/src/session/tabs/use-notification-pane-navigation.test.tsx +++ b/mobile/src/session/tabs/use-notification-pane-navigation.test.tsx @@ -146,17 +146,6 @@ describe('the page pane hook', () => { expect(switched.map((tab) => tab.id)).toEqual(['second']) }) - it('switches to a pane the host document hands the session already showing', () => { - // A notification for the session on top reaches it as URL params, since a second copy is never pushed. - bridge.route = { pathname: '/h/host-1' } - const tree = render(true) - pageUrl.params = { paneKey: `tab-b:${LEAF}` } - act(() => { - tree.update(createElement(Probe, { terminalsLoaded: true })) - }) - expect(switched.map((tab) => tab.id)).toEqual(['second']) - }) - it('switches to the agent row tapped in the host list when the page opened the session itself', () => { // #34235: the shell route stays the host list, so the tapped pane is only in the page URL. bridge.route = { pathname: '/h/host-1' } diff --git a/mobile/src/session/use-mobile-session-native-chat-dictation.ts b/mobile/src/session/use-mobile-session-native-chat-dictation.ts index a82a2592ad5..e6dace40f3c 100644 --- a/mobile/src/session/use-mobile-session-native-chat-dictation.ts +++ b/mobile/src/session/use-mobile-session-native-chat-dictation.ts @@ -1,4 +1,4 @@ -import { useEffect, useCallback, useRef } from 'react' +import { useEffect, useCallback, useRef, useState } from 'react' import { AppState } from 'react-native' import { useFocusEffect } from 'expo-router' import { useMobileDictation } from '../hooks/use-mobile-dictation' @@ -136,9 +136,12 @@ export function useMobileSessionNativeChatDictation( const dictationCanStart = showNativeChat ? connState === 'connected' || phoneDictation.ready : canSend + // The host's filler switch, kept from its last setup read; on until one says otherwise. + const [removeFillerWords, setRemoveFillerWords] = useState(true) const dictation = useMobileDictation({ client, enabled: (showNativeChat || canCompose) && dictationEnabled, + removeFillerWords, onTranscript: (text) => { // Chat dictation is inserted locally; a terminal's words are typed into it live. if (destination.landsInChat(showNativeChatRef.current)) { @@ -246,6 +249,7 @@ export function useMobileSessionNativeChatDictation( const setup = await fetchDictationSetup(client) if (read === dictationSettingsReadRef.current) { setDictationMode(setup.dictationMode) + setRemoveFillerWords(setup.removeFillerWords !== false) setDictationEnabled(!dictationMicHidden(setup)) dictationNeedsSetupRef.current = dictationNeedsSetup(setup) } diff --git a/mobile/src/session/use-mobile-structured-agent-options.test.ts b/mobile/src/session/use-mobile-structured-agent-options.test.ts index 5a5c9b59d31..6cc5bdc886b 100644 --- a/mobile/src/session/use-mobile-structured-agent-options.test.ts +++ b/mobile/src/session/use-mobile-structured-agent-options.test.ts @@ -26,29 +26,6 @@ import { BASE } from './use-mobile-structured-agent-options.test-fixture' -describe('useMobileStructuredAgentOptions post-write refresh', () => { - it.each([true, false])( - 'revalidates an accepted operation with sameFence=%s', - async (sameFence) => { - const client = optionsClient(queuedReads(FAST_OPTIONS, FAST_OPTIONS_ON)) - // The reply settles the operation; only the query installs the chat's selection. - const { mutate } = recordingMutate(async () => - accepted({ key: 'fastMode', value: 'true', options: {} }, sameFence) - ) - const harness = await mountOptions({ ...BASE, client: client.client, mutate }) - expect(client.optionReads()).toBe(1) - expect(currentValueOf(harness.current().optionSnapshot, 'fastMode')).toBe(false) - await act(async () => { - await harness.current().setStructuredOption('fastMode', true) - }) - await settle() - expect(client.optionReads()).toBe(2) - expect(currentValueOf(harness.current().optionSnapshot, 'fastMode')).toBe(true) - await harness.unmount() - } - ) -}) - describe('useMobileStructuredAgentOptions generation fencing', () => { it('drops an options read a later write superseded', async () => { const stale = deferred() diff --git a/mobile/src/session/use-mobile-structured-agent-session.ts b/mobile/src/session/use-mobile-structured-agent-session.ts index d0011546821..f15182b48eb 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.ts +++ b/mobile/src/session/use-mobile-structured-agent-session.ts @@ -128,11 +128,8 @@ export function useMobileStructuredAgentSession( onSendError, confirmRecorded: useMobileStructuredSendRecorded(client, sessionId, hostSupport) }) - const { transcriptItems, messages, receipts } = useMobileStructuredTranscript( - agent, - state, - sends.optimistic - ) + const transcript = useMobileStructuredTranscript(agent, state, sends.optimistic, sessionKey) + const { clearing, transcriptItems, messages, receipts } = transcript const turnTiming = useMobileStructuredAgentTurnTiming( { ...state, items: transcriptItems }, turnId @@ -190,6 +187,7 @@ export function useMobileStructuredAgentSession( stopping: turnIndicator.stopping, ...sends, commandPending: commandPendingRef, + onClearSent: transcript.onClearSent, sendsOut, controller: goal.commands, sessionCommands: args.sessionCommands, @@ -273,7 +271,8 @@ export function useMobileStructuredAgentSession( transcriptLoading: status === 'loading', error: state.error, readFailedFinally: status === 'error' && isFinalAgentSessionReadRefusal(state.readRefusal), - hasMore: state.hasOlder && olderPages !== 'unavailable', + clearing, + hasMore: state.hasOlder && olderPages !== 'unavailable' && !clearing, loadingEarlier: olderPages === 'loading', olderPages, loadEarlier diff --git a/mobile/src/session/use-mobile-structured-send-with-outcome.ts b/mobile/src/session/use-mobile-structured-send-with-outcome.ts index 0f3273fc4e6..be4dd2ea649 100644 --- a/mobile/src/session/use-mobile-structured-send-with-outcome.ts +++ b/mobile/src/session/use-mobile-structured-send-with-outcome.ts @@ -63,6 +63,7 @@ export function useMobileStructuredSendWithOutcome(args: { reject: MobileStructuredSends['reject'] holdUnconfirmed: MobileStructuredSends['holdUnconfirmed'] commandPending: { current: boolean } + onClearSent: () => () => void /** This chat's message sends still out, which a command waits behind as on desktop. */ sendsOut: MobileStructuredSendsOut controller: Pick< @@ -99,6 +100,7 @@ export function useMobileStructuredSendWithOutcome(args: { commandsWait, controller, enabled, + onClearSent, reject, holdUnconfirmed, onSendError, @@ -193,6 +195,7 @@ export function useMobileStructuredSendWithOutcome(args: { selectAgentSessionCurrentRequests(stateRef.current) ), onError: onSendError, + onClearSent, timeoutMs }) if (commandOutcome !== null) { @@ -275,6 +278,7 @@ export function useMobileStructuredSendWithOutcome(args: { commandsWait, controller, enabled, + onClearSent, reject, holdUnconfirmed, onSendError, diff --git a/mobile/src/session/use-mobile-structured-transcript.ts b/mobile/src/session/use-mobile-structured-transcript.ts index 992e9a9495f..f4fa032ca3c 100644 --- a/mobile/src/session/use-mobile-structured-transcript.ts +++ b/mobile/src/session/use-mobile-structured-transcript.ts @@ -1,5 +1,9 @@ -import { useMemo } from 'react' -import { agentSessionTranscriptRows } from '../../../src/shared/agent-session/agent-session-context-clear' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { + agentSessionContextClearOutstanding, + agentSessionTranscriptRows, + latestAgentSessionContextClearSequence +} from '../../../src/shared/agent-session/agent-session-context-clear' import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' import { projectStructuredAgentSessionMessages } from '../../../src/shared/agent-session/view/structured-agent-session-message-projection' import { tuiAgentDisplayName } from '../../../src/shared/agent-launch/catalog/tui-agent-display-names' @@ -12,18 +16,50 @@ const mobileStructuredTranscript = createStructuredQuestionProjection( projectStructuredAgentStartItem ) -/** The chat's transcript rows, its messages with this phone's sends in flight, and the prompts they resolved. */ +/** The chat's transcript rows, its messages with this phone's sends in flight, and the prompts they resolved. + * From this phone's /clear press until its divider lands, the rows drawn at the press stay hidden: + * the host stops the old agent before it writes the divider. */ export function useMobileStructuredTranscript( agent: string | null, - state: Pick, - optimistic: Parameters[1] + state: Pick, + optimistic: Parameters[1], + sessionKey: string ) { + const [clearSent, setClearSent] = useState<{ + sessionKey: string + epoch: string | null + tail: number + } | null>(null) + // The newest row the last commit drew: the rows a press hides. + const tail = state.items.at(-1)?.sequence ?? 0 + const drawnTail = useRef(tail) + useEffect(() => { + drawnTail.current = tail + }, [tail]) + const onClearSent = useCallback(() => { + const sent = { sessionKey, epoch: state.epoch, tail: drawnTail.current } + setClearSent(sent) + return () => setClearSent((current) => (current === sent ? null : current)) + }, [sessionKey, state.epoch]) + // A rewind's new epoch restarts sequences, so the press's rows are not in it. + const clearSentTail = + clearSent?.sessionKey === sessionKey && clearSent.epoch === state.epoch ? clearSent.tail : null + const latestClear = useMemo( + () => latestAgentSessionContextClearSequence(state.items), + [state.items] + ) + const clearing = agentSessionContextClearOutstanding(state.items, latestClear, clearSentTail) + // Retire a press that hides nothing (its divider landed, or its rows left), so a later trim cannot re-arm it. + if (clearSent?.sessionKey === sessionKey && !clearing) { + setClearSent(null) + } + const floor = clearing ? clearSentTail + 1 : latestClear const transcriptItems = useMemo( () => - withNativeChatCutTurnNotices(agentSessionTranscriptRows(state.items), { + withNativeChatCutTurnNotices(agentSessionTranscriptRows(state.items, floor), { agentName: agent ? (tuiAgentDisplayName(agent) ?? agent) : undefined }), - [agent, state.items] + [agent, floor, state.items] ) const messages = useMemo( () => @@ -39,6 +75,8 @@ export function useMobileStructuredTranscript( [transcriptItems, optimistic, state.submissions] ) return { + clearing, + onClearSent, transcriptItems, messages, receipts: mobileStructuredTranscript.transcript(transcriptItems).receipts diff --git a/mobile/src/source-control/MobileSourceControlContent.test.tsx b/mobile/src/source-control/MobileSourceControlContent.test.tsx deleted file mode 100644 index 1ce4b3c476d..00000000000 --- a/mobile/src/source-control/MobileSourceControlContent.test.tsx +++ /dev/null @@ -1,321 +0,0 @@ -import { createElement, useState } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { MobileSourceControlContent } from './MobileSourceControlContent' -import { MobileSourceControlNextStepBar } from './MobileSourceControlNextStepBar' -import type { MobileSourceControlPrimaryAction } from './mobile-source-control-primary-action' - -import type { MobileSourceControlState } from './use-mobile-source-control-state' - -type MobileSourceControlContentState = Omit & { - primaryAction: MobileSourceControlPrimaryAction -} -import type { SectionListProps } from 'react-native' -import type { - MobileBranchEntryView, - MobileGitStatusEntryView -} from './mobile-source-control-screen-state' - -vi.mock('react-native', () => ({ - AccessibilityInfo: { - isReduceMotionEnabled: async () => false, - addEventListener: () => ({ remove: () => {} }) - }, - ActivityIndicator: 'ActivityIndicator', - Pressable: 'Pressable', - ScrollView: 'ScrollView', - SectionList: (props: SectionListProps) => - createElement( - 'SectionList', - { ...props, ListHeaderComponent: undefined }, - typeof props.ListHeaderComponent === 'function' ? null : props.ListHeaderComponent, - typeof props.ListFooterComponent === 'function' - ? createElement(props.ListFooterComponent) - : props.ListFooterComponent, - props.sections.map((section) => - createElement( - 'Section', - { key: section.key }, - props.renderSectionHeader?.({ section }), - section.data.slice(0, 20).map((item, index) => - createElement( - 'Row', - { key: item.path }, - props.renderItem?.({ - item, - index, - section, - separators: { highlight: noop, unhighlight: noop, updateProps: noop } - }) - ) - ) - ) - ) - ), - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, - Text: 'Text', - TextInput: 'TextInput', - View: 'View' -})) -vi.mock('expo-clipboard', () => ({ setStringAsync: async () => {} })) -// Counts row renders: every file row draws its line stats once. -const rowRenders = vi.hoisted(() => ({ count: 0 })) -vi.mock('../components/MobileDiffReviewFileSummary', () => ({ - MobileDiffLineStats: () => { - rowRenders.count += 1 - return null - } -})) -vi.mock('react-native-gesture-handler', async () => { - const chain = new Proxy({}, { get: () => () => chain }) - return { - Gesture: { Pan: () => chain }, - GestureDetector: ({ children }: { children: unknown }) => children - } -}) -vi.mock('react-native-reanimated', () => ({ - default: { View: ({ children }: { children: unknown }) => children }, - Easing: { bezier: () => () => 0 }, - ReduceMotion: { Never: 'never' }, - useAnimatedStyle: () => ({}), - useReducedMotion: () => false, - useSharedValue: (value: number) => ({ value }), - withTiming: (value: number) => value -})) -vi.mock('../components/ConfirmModal', () => ({ ConfirmModal: () => null })) -vi.mock('lucide-react-native', () => ({ - ArrowDown: 'ArrowDown', - ArrowDownUp: 'ArrowDownUp', - ArrowUp: 'ArrowUp', - Check: 'Check', - ChevronDown: 'ChevronDown', - ChevronRight: 'ChevronRight', - CloudUpload: 'CloudUpload', - FileText: 'FileText', - GitBranch: 'GitBranch', - GitCommitHorizontal: 'GitCommitHorizontal', - GitMerge: 'GitMerge', - GitPullRequest: 'GitPullRequest', - GitPullRequestArrow: 'GitPullRequestArrow', - History: 'History', - Minus: 'Minus', - MoreHorizontal: 'MoreHorizontal', - Plus: 'Plus', - RefreshCw: 'RefreshCw', - Sparkles: 'Sparkles', - Trash2: 'Trash2', - TriangleAlert: 'TriangleAlert', - Undo2: 'Undo2' -})) - -const noop = () => {} -const unusedAsync = async (): Promise => { - throw new Error('unused action') -} - -function initialState(): MobileSourceControlContentState { - const branchEntries = Array.from({ length: 20 }, (_, index) => ({ - path: `src/file-${index}.ts`, - status: 'modified' as const, - added: 3, - removed: 1, - canOpen: true - })) - const branchCompareResult = { - entries: branchEntries, - summary: { - status: 'ready' as const, - baseRef: 'main', - changedFiles: 20, - commitsAhead: undefined, - errorMessage: undefined - } - } - return { - client: null, - connState: 'connected', - forceReconnect: null, - rebaseBaseRef: 'main', - refreshing: false, - insets: { top: 0, bottom: 0, left: 0, right: 0 }, - router: { - back: noop, - push: noop, - replace: noop, - navigate: noop, - dismiss: noop, - dismissAll: noop, - dismissTo: noop, - prefetch: noop, - canGoBack: () => false, - canDismiss: () => false, - setParams: noop, - reload: noop - }, - setRootRef: noop, - worktreeLabel: 'fixture', - screenState: { kind: 'loading' }, - branchCompareState: { kind: 'ready', result: branchCompareResult }, - busyAction: null, - commitMessage: '', - setCommitMessage: noop, - generatingMessage: false, - showBranchPicker: false, - setShowBranchPicker: noop, - localBranches: null, - createdPrUrl: null, - setCreatedPrUrl: noop, - createdPrWarning: null, - setCreatedPrWarning: noop, - discardTarget: null, - setDiscardTarget: noop, - showActionSheet: false, - setShowActionSheet: noop, - actionError: null, - commitFailureRecovery: null, - commitFailureRecoveryAction: { - summary: null, - hasDetails: false, - launching: false, - availability: 'available', - launchError: null, - launchWarning: null, - launchSuccess: null, - undeliveredPrompt: null, - launch: unusedAsync - }, - keyboardLift: 0, - status: null, - sections: [], - branchCompareResult, - branchEntries, - shouldShowBranchCompareSection: true, - hasVisibleChanges: true, - stageablePaths: [], - unstageablePaths: [], - stagedCount: 1, - unstagedCount: 0, - branchLabel: 'fixture', - upstreamKnown: false, - primaryAction: { - kind: 'commit', - label: 'Commit', - accessibilityLabel: 'Commit', - accessibilityHint: '', - disabled: false, - loading: false, - onPress: noop - }, - createPrAction: { - visible: false, - label: 'Create Pull Request', - reviewLabel: 'pull request', - disabled: true, - loading: false, - pushFirst: false, - onPress: noop - }, - loadStatus: unusedAsync, - openDiffForFile: noop, - runGitAction: unusedAsync, - stageAll: unusedAsync, - unstageAll: unusedAsync, - commit: unusedAsync, - generateCommitMessage: unusedAsync, - cancelGenerateCommitMessage: noop, - createPr: unusedAsync, - openBranchPicker: noop, - openHistory: noop, - checkoutBranch: unusedAsync, - abortConflictOperation: unusedAsync, - resolveConflict: unusedAsync, - completeMerge: unusedAsync, - runActionSheetCommit: unusedAsync, - runActionSheetCommitSequence: unusedAsync, - runActionSheetCommitSync: unusedAsync, - runActionSheetGitSequence: unusedAsync, - runActionSheetGitSync: unusedAsync, - runActionSheetRebase: unusedAsync - } -} - -let renderer: ReactTestRenderer | null = null -const controls: { patch: ((patch: Partial) => void) | null } = { - patch: null -} - -function Fixture({ initial }: { initial: MobileSourceControlContentState }) { - const [state, setState] = useState(initial) - controls.patch = (patch) => setState((previous) => ({ ...previous, ...patch })) - const liveState = { - ...state, - setCommitMessage: (next: string | ((previous: string) => string)) => - setState((previous) => ({ - ...previous, - commitMessage: typeof next === 'function' ? next(previous.commitMessage) : next - })) - } - // Laid out as the panel does: the commit box lives in the bar beside the list. - return createElement( - 'View', - null, - createElement(MobileSourceControlContent, { - state: liveState, - stageAllInBar: state.primaryAction.kind === 'stage', - bottomInset: 0, - onOpenCommits: noop - }), - createElement(MobileSourceControlNextStepBar, { - view: { kind: 'composer' }, - notice: null, - agentNotice: null, - mergeConfirm: null, - composer: liveState, - primaryAction: state.primaryAction, - keyboardLift: state.keyboardLift, - bottomInset: 0, - onHeightChange: noop - }) - ) -} - -function render(initial = initialState()) { - act(() => { - renderer = create(createElement(Fixture, { initial })) - }) -} -function patch(values: Partial) { - act(() => { - controls.patch?.(values) - }) -} - -afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - controls.patch = null - vi.restoreAllMocks() -}) - -describe('next-step bar and the keyboard', () => { - function input() { - return renderer?.root.findAll((node) => String(node.type) === 'TextInput')[0] ?? null - } - - it('rides the keyboard for its own commit box and steps aside for any other field', () => { - render() - // Another field (a PR comment) raised the keyboard: the bar must not cover it. - patch({ keyboardLift: 300 }) - expect(input()).toBeNull() - patch({ keyboardLift: 0 }) - act(() => { - const onFocus = input()?.props.onFocus - if (typeof onFocus !== 'function') { - throw new Error('missing focus handler') - } - onFocus() - }) - patch({ keyboardLift: 300 }) - expect(input()).not.toBeNull() - }) -}) diff --git a/mobile/src/source-control/MobileSourceControlHeader.tsx b/mobile/src/source-control/MobileSourceControlHeader.tsx index 1779be1290e..1f4c3e0c671 100644 --- a/mobile/src/source-control/MobileSourceControlHeader.tsx +++ b/mobile/src/source-control/MobileSourceControlHeader.tsx @@ -15,6 +15,8 @@ type Props = { /** Shown rows are being re-read; the line waits out quick reads. */ refreshing: boolean onBack: () => void + /** Back to the screen this hub was opened over in place, e.g. a folder's list; drawn beside dock Close. */ + backInPlace?: { onPress: () => void; label: string } // Dock dismissal does not pop a route; keep it separate from Back. onClose: () => void onRefresh: () => void @@ -33,6 +35,7 @@ export function MobileSourceControlHeader({ ioBusy, refreshing, onBack, + backInPlace, onClose, onRefresh, onOpenPrWeb, @@ -72,17 +75,26 @@ export function MobileSourceControlHeader({ ] : []) ] + const closeButton = ( + + ) return ( <> + ) : embedded ? ( + closeButton ) : ( setMenuOpen(true)} - active={menuOpen} - accessibilityLabel={t( - 'sourceControl.header.moreActions', - 'More source control actions' - )} - /> + <> + {backInPlace && embedded ? closeButton : null} + setMenuOpen(true)} + active={menuOpen} + accessibilityLabel={t( + 'sourceControl.header.moreActions', + 'More source control actions' + )} + /> + } /> void; label: string } onRequestClose?: () => void } @@ -60,6 +62,7 @@ export function MobileSourceControlPanel({ name = '', embedded = false, initialTab = 'changes', + backInPlace, onRequestClose }: MobileSourceControlPanelProps) { useMobileColorScheme() @@ -251,6 +254,7 @@ export function MobileSourceControlPanel({ // Only Changes reads through the query layer so far; the PR tab keeps its own loading UI. refreshing={activeTab === 'changes' && state.refreshing} onBack={onBack} + backInPlace={backInPlace} onClose={onClose} onRefresh={onRefresh} menuGroups={ diff --git a/mobile/src/source-control/MobileSourceControlRoutePanel.tsx b/mobile/src/source-control/MobileSourceControlRoutePanel.tsx new file mode 100644 index 00000000000..f82fd2915e9 --- /dev/null +++ b/mobile/src/source-control/MobileSourceControlRoutePanel.tsx @@ -0,0 +1,22 @@ +import { parseWorkspaceKey } from '../../../src/shared/workspace-scope' +import { MobileFolderSourceControlPanel } from './folder/MobileFolderSourceControlPanel' +import { + MobileSourceControlPanel, + type MobileSourceControlPanelProps +} from './MobileSourceControlPanel' + +/** Source Control for the workspace a route or dock names: a folder workspace lists its attached worktrees. */ +export function MobileSourceControlRoutePanel(props: MobileSourceControlPanelProps) { + if (parseWorkspaceKey(props.worktreeId)?.type === 'folder') { + return ( + + ) + } + return +} diff --git a/mobile/src/source-control/folder/MobileFolderSourceControlPanel.tsx b/mobile/src/source-control/folder/MobileFolderSourceControlPanel.tsx new file mode 100644 index 00000000000..f27ba094d7b --- /dev/null +++ b/mobile/src/source-control/folder/MobileFolderSourceControlPanel.tsx @@ -0,0 +1,205 @@ +import { useCallback, useState } from 'react' +import { useFocusEffect } from 'expo-router' +import { ScrollView, View } from 'react-native' +import { GitBranch } from 'lucide-react-native' +import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context' +import { + MobileLoadErrorState, + MobileOfflineState, + MobileStateView +} from '../../components/MobileStateView' +import { connectionRetryAction } from '../../transport/connection/connection-retry-action' +import { useForceReconnect } from '../../transport/connection/host-client-hooks' +import { OptionPager, useOptionPager } from '../../components/bottom-drawer/BottomDrawer' +import { ListGroup } from '../../components/list/ListGroup' +import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import { useBackClaim } from '../../navigation/use-back-claim' +import { useWorkspaceRouteHandoff } from '../../navigation/workspace-route-handoff' +import { WorkspaceExecutionScope } from '../../navigation/workspace-route' +import { colors, spacing } from '../../theme/mobile-theme' +import { themedStyleSheet } from '../../theme/themed-styles' +import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' +import type { FolderListRow } from './mobile-folder-attached-worktrees' +import { getWorktreeRowIdentity } from '../../worktree/worktree-host-row-identity' +import { MobileSourceControlHeader } from '../MobileSourceControlHeader' +import { MobileSourceControlPanel } from '../MobileSourceControlPanel' +import { styles as sourceControlStyles } from '../mobile-source-control-styles' +import { MobileFolderWorktreeRow } from './MobileFolderWorktreeRow' +import { useMobileFolderAttachedWorktrees } from './use-mobile-folder-attached-worktrees' + +type Props = { + hostId: string + folderWorktreeId: string + name: string + embedded: boolean + onRequestClose?: () => void +} + +/** A folder workspace's Source Control: one row per attached worktree, each opening that worktree's own Source Control in place. */ +export function MobileFolderSourceControlPanel({ + hostId, + folderWorktreeId, + name, + embedded, + onRequestClose +}: Props) { + useMobileColorScheme() + const t = useMobileTranslation() + const router = useWorkspaceRouteHandoff() + const insets = useSafeAreaInsets() + const pager = useOptionPager() + const [opened, setOpened] = useState(null) + const pageOpen = pager.page !== null + // A covered screen stops observing, as the single-worktree screen does, and so does the list under an open child. + const [focused, setFocused] = useState(true) + useFocusEffect( + useCallback(() => { + setFocused(true) + return () => setFocused(false) + }, []) + ) + const observing = focused && !pageOpen + const { folder, worktrees, desktopCapabilities, serverHosts, connState, loadError, refetch } = + useMobileFolderAttachedWorktrees(hostId, folderWorktreeId, observing) + const forceReconnect = useForceReconnect() + const [refreshers] = useState(() => new Set<() => void>()) + const refresh = () => { + refetch() + for (const refreshNow of refreshers) { + refreshNow() + } + } + useBackClaim( + pageOpen + ? () => { + pager.close() + return true + } + : null + ) + const openPage = pager.open + const open = useCallback( + (worktree: FolderListRow) => { + setOpened(worktree) + openPage(getWorktreeRowIdentity(worktree)) + }, + [openPage] + ) + const onClose = onRequestClose ?? (() => router.back()) + + const header = ( + router.back()} + onClose={onClose} + onRefresh={refresh} + /> + ) + const retry = connectionRetryAction({ + hostId, + needsReconnect: connState !== 'connected', + forceReconnect, + reload: refetch + }) + const body = + // A connection still coming up shows loading; offline is for one that dropped or was refused. + folder === undefined && (connState === 'disconnected' || connState === 'auth-failed') ? ( + + ) : folder === undefined && loadError ? ( + + ) : folder === undefined ? ( + + ) : folder === null ? ( + + ) : worktrees.length === 0 ? ( + + ) : ( + // One card per attached worktree, as desktop shows them. + + {worktrees.map((worktree) => ( + + server.hostId === worktree.hostId)?.relay === + 'update-needed' + } + subscribed={observing} + refreshers={refreshers} + onOpen={open} + /> + + ))} + + ) + const main = ( + + {embedded ? ( + {header} + ) : ( + + {header} + + )} + {/* Every state shares the sheet surface the cards sit on, as the phone's option sheets do. */} + {body} + + ) + return ( + + + + ) : null + } + /> + ) +} + +const styles = themedStyleSheet(() => ({ + body: { + flex: 1, + backgroundColor: colors.sheetSurface + }, + list: { + padding: spacing.lg, + gap: spacing.sm + } +})) diff --git a/mobile/src/source-control/folder/MobileFolderWorktreeRow.tsx b/mobile/src/source-control/folder/MobileFolderWorktreeRow.tsx new file mode 100644 index 00000000000..d28e6b0c362 --- /dev/null +++ b/mobile/src/source-control/folder/MobileFolderWorktreeRow.tsx @@ -0,0 +1,82 @@ +import { memo } from 'react' +import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import { ListRow } from '../../components/list/ListGroup' +import { useHostClient } from '../../transport/connection/host-client-hooks' +import { workspaceRouteExecutionHost } from '../../worktree/execution-host-scoped-rpc-client' +import type { FolderListRow } from './mobile-folder-attached-worktrees' +import { formatBranchLabel } from '../mobile-source-control-screen-state' +import { useFolderWorktreeStatus } from './use-folder-worktree-status' + +type Props = { + hostId: string + /** The paired desktop's, which decide whether it relays to the row's server. */ + desktopCapabilities: readonly string[] + worktree: FolderListRow + /** The desktop relays to the row's server but can't reach it (e.g. it needs an update). */ + unreachable: boolean + subscribed: boolean + refreshers: Set<() => void> + onOpen: (worktree: FolderListRow) => void +} + +/** One attached worktree: desktop's card header (repo, name, branch, ahead/behind, change count); tapping opens its Source Control. */ +// Memoized: the host catalog changes often, and a row only re-renders when its own inputs do. +export const MobileFolderWorktreeRow = memo(function MobileFolderWorktreeRow({ + hostId, + desktopCapabilities, + worktree, + unreachable, + subscribed, + refreshers, + onOpen +}: Props) { + const t = useMobileTranslation() + const { client, state } = useHostClient(hostId) + // A relayed server's row reads through the desktop, as its own Source Control does. + const routeHost = workspaceRouteExecutionHost(client, desktopCapabilities, worktree.hostId) + const openable = routeHost !== null && !unreachable + const status = useFolderWorktreeStatus({ + hostId, + client: state === 'connected' && openable ? client : null, + routeHost: routeHost ?? undefined, + worktreeId: worktree.worktreeId, + subscribed, + refreshers + }) + + const read = status.data?.kind === 'ready' ? status.data.status : undefined + // A failed, partial or unsupported read must not look like a clean worktree, even over an older good read. + const unread = + status.data?.kind === 'unavailable' || status.error !== null || read?.readError !== undefined + const branch = read + ? formatBranchLabel(read.branch, read.head) + : worktree.branch.replace(/^refs\/heads\//, '') + const ahead = read?.upstreamStatus?.ahead ?? 0 + const behind = read?.upstreamStatus?.behind ?? 0 + const changeCount = read?.entries.length ?? 0 + const subtitle = [ + // Same-repo worktrees are told apart by name, as desktop does. + worktree.displayName && worktree.displayName !== branch ? worktree.displayName : null, + branch || null, + ahead > 0 ? `↑${ahead}` : null, + behind > 0 ? `↓${behind}` : null + ] + .filter(Boolean) + .join(' · ') + return ( + 0 + ? String(changeCount) + : undefined + } + navigates={openable} + disabled={!openable} + onPress={() => onOpen(worktree)} + /> + ) +}) diff --git a/mobile/src/source-control/folder/folder-lineage-serialization.ts b/mobile/src/source-control/folder/folder-lineage-serialization.ts new file mode 100644 index 00000000000..fc4a7f686bb --- /dev/null +++ b/mobile/src/source-control/folder/folder-lineage-serialization.ts @@ -0,0 +1,19 @@ +import type { Worktree } from '../../worktree/workspace-list-types' + +/** The fields folder membership and order depend on; labels and agent state are left out so their churn rebuilds nothing. */ +export function serializeFolderLineage(row: Worktree): string { + return JSON.stringify([ + row.worktreeId, + row.hostId, + row.repoId, + row.workspaceKind, + row.isArchived, + row.parentWorktreeId, + row.worktreeInstanceId, + row.lineageWorktreeInstanceId, + row.parentWorktreeInstanceId, + row.crossStoreParent, + row.workspaceLineage, + row.createdAt + ]) +} diff --git a/mobile/src/source-control/folder/mobile-folder-attached-worktrees.test.ts b/mobile/src/source-control/folder/mobile-folder-attached-worktrees.test.ts new file mode 100644 index 00000000000..b6f91d3d2a0 --- /dev/null +++ b/mobile/src/source-control/folder/mobile-folder-attached-worktrees.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' +import type { Worktree } from '../../worktree/workspace-list-types' +import { + findFolderWorkspaceRow, + getFolderAttachedWorktrees +} from './mobile-folder-attached-worktrees' + +function worktree(overrides: Partial): Worktree { + return { + workspaceKind: 'git', + worktreeId: 'worktree', + repoId: 'repo-1', + repo: 'api', + branch: 'feature', + displayName: 'worktree', + path: '/tmp/worktree', + liveTerminalCount: 0, + hasAttachedPty: false, + unread: false, + isPinned: false, + linkedPR: null, + ...overrides + } +} + +const folder = worktree({ + workspaceKind: 'folder-workspace', + worktreeId: 'folder:f-1', + repoId: 'folder-project:group-1' +}) +const attachedTo = (worktreeId: `folder:${string}`) => ({ + workspaceLineage: { parentWorkspaceKey: worktreeId, parentInstanceId: 'f-1' } +}) + +describe('getFolderAttachedWorktrees', () => { + it("lists the folder's children and their worktree descendants, oldest first", () => { + const web = worktree({ worktreeId: 'web', createdAt: 20, ...attachedTo('folder:f-1') }) + const api = worktree({ worktreeId: 'api', createdAt: 10, ...attachedTo('folder:f-1') }) + const apiChild = worktree({ worktreeId: 'api-child', createdAt: 30, parentWorktreeId: 'api' }) + const archived = worktree({ + worktreeId: 'archived', + createdAt: 5, + isArchived: true, + ...attachedTo('folder:f-1') + }) + const other = worktree({ worktreeId: 'other', ...attachedTo('folder:f-2') }) + const unrelated = worktree({ worktreeId: 'unrelated' }) + + const rows = [folder, web, api, apiChild, archived, other, unrelated] + expect(getFolderAttachedWorktrees(rows, folder).map((row) => row.worktreeId)).toEqual([ + 'api', + 'web', + 'api-child' + ]) + }) +}) + +describe('findFolderWorkspaceRow', () => { + it("finds the paired desktop's folder, or a relayed server's when the route names it", () => { + const serverFolder = { ...folder, hostId: 'runtime:env-1' as const } + const rows = [serverFolder, folder] + expect(findFolderWorkspaceRow(rows, 'folder:f-1', undefined)).toBe(folder) + expect(findFolderWorkspaceRow(rows, 'folder:f-1', 'runtime:env-1')).toBe(serverFolder) + }) +}) diff --git a/mobile/src/source-control/folder/mobile-folder-attached-worktrees.ts b/mobile/src/source-control/folder/mobile-folder-attached-worktrees.ts new file mode 100644 index 00000000000..5fbae1707b5 --- /dev/null +++ b/mobile/src/source-control/folder/mobile-folder-attached-worktrees.ts @@ -0,0 +1,87 @@ +import type { ExecutionHostId } from '../../../../src/shared/execution-host' +import type { Worktree } from '../../worktree/workspace-list-types' +import { + getMobileWorkspaceLineageChildren, + type MobileLineageRow, + type MobileLineageStores +} from '../../worktree/mobile-workspace-lineage' +import { getWorktreeRowIdentity } from '../../worktree/worktree-host-row-identity' +import { serializeFolderLineage } from './folder-lineage-serialization' + +/** What a folder list row shows of a host row. */ +export type FolderListRow = Pick< + Worktree, + 'worktreeId' | 'hostId' | 'repo' | 'displayName' | 'branch' +> + +type FolderLineageRow = MobileLineageRow & Pick + +// Keyed by row object: the catalog query keeps an unchanged row's identity, so only changed rows are read again. +const lineageKeys = new WeakMap() +const listRows = new WeakMap() + +/** A row's lineage key, serialized once per row object. */ +export function folderLineageKey(row: Worktree): string { + let key = lineageKeys.get(row) + if (key === undefined) { + key = serializeFolderLineage(row) + lineageKeys.set(row, key) + } + return key +} + +export function toFolderListRow(row: Worktree): FolderListRow { + let listRow = listRows.get(row) + if (listRow === undefined) { + listRow = { + worktreeId: row.worktreeId, + hostId: row.hostId, + repo: row.repo, + displayName: row.displayName, + branch: row.branch + } + listRows.set(row, listRow) + } + return listRow +} + +/** The folder workspace row a Source Control route names; a route without a server means the paired desktop's own. */ +export function findFolderWorkspaceRow( + rows: readonly Row[], + folderWorktreeId: string, + executionHost: ExecutionHostId | undefined +): Row | undefined { + return rows.find( + (row) => + row.worktreeId === folderWorktreeId && + row.workspaceKind === 'folder-workspace' && + (executionHost ? row.hostId === executionHost : !row.hostId?.startsWith('runtime:')) + ) +} + +/** Worktrees attached to the folder, as the host list nests them, with their worktree descendants; oldest first, like desktop. */ +export function getFolderAttachedWorktrees( + rows: readonly Row[], + folder: Row, + stores?: MobileLineageStores +): Row[] { + const childrenByParent = getMobileWorkspaceLineageChildren(rows, stores) + const members = new Map() + const queue = [folder] + for (let i = 0; i < queue.length; i++) { + for (const child of childrenByParent.get(getWorktreeRowIdentity(queue[i])) ?? []) { + const identity = getWorktreeRowIdentity(child) + if (child.isArchived || members.has(identity)) { + continue + } + members.set(identity, child) + queue.push(child) + } + } + // Rows carry no attach time; a child is attached when it is created from the folder. + return [...members.values()].sort( + (left, right) => + (left.createdAt ?? 0) - (right.createdAt ?? 0) || + getWorktreeRowIdentity(left).localeCompare(getWorktreeRowIdentity(right)) + ) +} diff --git a/mobile/src/source-control/folder/use-folder-worktree-status.perf.test.ts b/mobile/src/source-control/folder/use-folder-worktree-status.perf.test.ts new file mode 100644 index 00000000000..5cadbf87217 --- /dev/null +++ b/mobile/src/source-control/folder/use-folder-worktree-status.perf.test.ts @@ -0,0 +1,257 @@ +import { createElement, Fragment } from 'react' +import { useQueryClient, type QueryClient } from '@tanstack/react-query' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { ExecutionHostId } from '../../../../src/shared/execution-host' +import type { RuntimeClientEventStreamMessage } from '../../../../src/shared/runtime-client-events' +import { stubRpcClient } from '../../transport/rpc/rpc-client-test-stub' +import type { RpcClient } from '../../transport/rpc/rpc-client-contract' +import { + documentQueryClient, + settleQueryNotifications +} from '../../test-support/rpc-recording/hook-mount' +import { hostQueryKey } from '../../query/host-query-key' +import { + publishGitStatusSummary, + serverGitStatusSummaryQuery, + type GitStatusRead +} from '../mobile-git-status-query' +import { useFolderWorktreeStatus } from './use-folder-worktree-status' + +const STATUS = { branch: 'feature', entries: [] } + +type StatusRead = { worktree: string; includeLineStats?: boolean } + +function isStatusRead(params: unknown): params is StatusRead { + return typeof params === 'object' && params !== null && 'worktree' in params +} + +const runtimeHost = (environmentId: string): ExecutionHostId => `runtime:${environmentId}` +const READY: RuntimeClientEventStreamMessage = { type: 'ready', subscriptionId: 'sub-1' } + +function countingClient() { + const reads: StatusRead[] = [] + let eventStreams = 0 + let emit: (event: RuntimeClientEventStreamMessage) => void = () => {} + const client: RpcClient = stubRpcClient({ + getLastConnectedAt: () => 1, + sendRequest: async (method, params) => { + if (method === 'git.status') { + if (isStatusRead(params)) { + reads.push(params) + } + } + return { id: 'call', ok: true, result: STATUS, _meta: { runtimeId: 'runtime-1' } } + }, + subscribe: (method, _params, onEvent) => { + if (method === 'runtime.clientEvents.subscribe') { + eventStreams += 1 + emit = (event) => onEvent(event) + } + return () => {} + } + }) + return { + client, + reads, + eventStreams: () => eventStreams, + emit: (event: RuntimeClientEventStreamMessage) => emit(event) + } +} + +let renderer: ReactTestRenderer | null = null +const queries = documentQueryClient() + +afterEach(async () => { + act(() => renderer?.unmount()) + renderer = null + await queries.end() + vi.useRealTimers() +}) + +const REFRESHERS = new Set<() => void>() +const shown = new Map() +let queryClient: QueryClient | null = null +const rowKey = (row: RowSpec) => `${row.routeHost ?? 'local'}|${row.worktreeId}` + +function Row(props: { + client: RpcClient + worktreeId: string + routeHost: ExecutionHostId | undefined + subscribed: boolean +}): null { + queryClient = useQueryClient() + const status = useFolderWorktreeStatus({ + hostId: 'host-1', + client: props.client, + routeHost: props.routeHost, + worktreeId: props.worktreeId, + subscribed: props.subscribed, + refreshers: REFRESHERS + }) + shown.set(rowKey(props), { data: status.data, updatedAt: status.dataUpdatedAt }) + return null +} + +type RowSpec = { worktreeId: string; routeHost: ExecutionHostId | undefined } + +/** One folder's attached worktrees: N in repo-a and N in repo-b on the desktop, N spread over S relayed servers. */ +function folderRows(n: number, servers: number): RowSpec[] { + const local = ['repo-a', 'repo-b'].flatMap((repo) => + Array.from({ length: n }, (_, i) => ({ worktreeId: `${repo}::/w${i}`, routeHost: undefined })) + ) + const relayed = Array.from({ length: n }, (_, i) => ({ + worktreeId: `repo-s::/w${i}`, + routeHost: runtimeHost(`env-${i % servers}`) + })) + return [...local, ...relayed] +} + +async function mountFolder(rows: RowSpec[], client: RpcClient) { + const render = (subscribed: boolean) => + queries.wrap( + createElement( + Fragment, + null, + rows.map((row) => createElement(Row, { key: rowKey(row), client, ...row, subscribed })) + ) + ) + await act(async () => { + renderer = create(render(true)) + }) + await settleQueryNotifications() + return async (subscribed: boolean) => { + await act(async () => renderer?.update(render(subscribed))) + await settleQueryNotifications() + } +} + +// Past every read's one-second signal floor, so each signal reads at once. +function passSignalFloor(): void { + vi.setSystemTime(Date.now() + 5_000) +} + +describe.each([ + { n: 10, servers: 3 }, + { n: 100, servers: 30 } +])('folder Source Control rows at N=$n over $servers servers', ({ n, servers }) => { + it('read each status once without line stats, on one desktop event stream', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const host = countingClient() + await mountFolder(folderRows(n, servers), host.client) + host.emit(READY) + await settleQueryNotifications() + + expect(host.reads).toHaveLength(3 * n) + expect(host.reads.every((read) => read.includeLineStats === false)).toBe(true) + // Relayed servers' statuses get no desktop signal, so they open no event stream of their own. + expect(host.eventStreams()).toBe(1) + }) + + it('read once per worktree a signal names, and not at all while hidden', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const host = countingClient() + const setSubscribed = await mountFolder(folderRows(n, servers), host.client) + host.emit(READY) + await settleQueryNotifications() + + host.reads.length = 0 + passSignalFloor() + await act(async () => host.emit({ type: 'gitStatusChanged', repoId: 'repo-a' })) + await settleQueryNotifications() + expect(host.reads).toHaveLength(n) + + host.reads.length = 0 + passSignalFloor() + await act(async () => + host.emit({ type: 'gitStatusChanged', repoId: 'repo-a', worktreeIds: ['repo-a::/w0'] }) + ) + await settleQueryNotifications() + expect(host.reads.map((read) => read.worktree)).toEqual(['id:repo-a::/w0']) + + await setSubscribed(false) + host.reads.length = 0 + passSignalFloor() + await act(async () => host.emit({ type: 'gitStatusChanged', repoId: 'repo-a' })) + await settleQueryNotifications() + expect(host.reads).toHaveLength(0) + }) + + it("shows a child's detailed read on Back with no read of its own", async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const host = countingClient() + // The same worktree id on another server and on the desktop must keep their own summaries. + const opened: RowSpec = { worktreeId: 'repo-s::/w0', routeHost: 'runtime:env-0' } + const rows = [ + ...folderRows(n, servers), + { worktreeId: 'repo-s::/w0', routeHost: runtimeHost('env-x') }, + { worktreeId: 'repo-s::/w0', routeHost: undefined } + ] + const setSubscribed = await mountFolder(rows, host.client) + const before = new Map(shown) + const listed = before.get(rowKey(opened))! + if (listed.data?.kind !== 'ready') { + throw new Error('summary not read') + } + + // The child opens over the list, commits, and its forced reread lands. + await setSubscribed(false) + host.reads.length = 0 + vi.setSystemTime(Date.now() + 1_000) + const after: GitStatusRead = { + kind: 'ready', + status: { ...listed.data.status, branch: 'after' } + } + const target = { exec: opened.routeHost!, worktree: opened.worktreeId } + await act(() => + publishGitStatusSummary(queryClient!, 'host-1', target, after, Date.now(), true) + ) + // A detailed read older than the summary changes nothing. + await act(() => + publishGitStatusSummary( + queryClient!, + 'host-1', + target, + listed.data!, + listed.updatedAt - 1, + true + ) + ) + + // Back within three seconds, then well past them with no focus or signal. + vi.setSystemTime(Date.now() + 1_000) + await setSubscribed(true) + vi.setSystemTime(Date.now() + 10_000) + await setSubscribed(true) + expect(host.reads).toHaveLength(0) + expect(shown.get(rowKey(opened))?.data).toEqual(after) + const changed = rows.filter( + (row) => shown.get(rowKey(row))?.data !== before.get(rowKey(row))?.data + ) + expect(changed).toEqual([opened]) + }) + + it("keeps a summary's newer failure over an older detailed read", async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const host = countingClient() + const opened: RowSpec = { worktreeId: 'repo-s::/w0', routeHost: 'runtime:env-0' } + await mountFolder(folderRows(n, servers), host.client) + const listed = shown.get(rowKey(opened))! + const target = { exec: opened.routeHost!, worktree: opened.worktreeId } + const key = hostQueryKey('host-1', serverGitStatusSummaryQuery.family, target, {}) + const cachedDetailAt = Date.now() + 1_000 + vi.setSystemTime(cachedDetailAt + 1_000) + const failure = new Error('status read failed') + await act(async () => + queryClient! + .getQueryCache() + .find({ queryKey: key, exact: true })! + .setState({ status: 'error', error: failure, errorUpdatedAt: Date.now() }) + ) + + await act(() => + publishGitStatusSummary(queryClient!, 'host-1', target, listed.data!, cachedDetailAt, true) + ) + expect(queryClient!.getQueryState(key)?.error).toBe(failure) + }) +}) diff --git a/mobile/src/source-control/folder/use-folder-worktree-status.ts b/mobile/src/source-control/folder/use-folder-worktree-status.ts new file mode 100644 index 00000000000..c8c8f19673d --- /dev/null +++ b/mobile/src/source-control/folder/use-folder-worktree-status.ts @@ -0,0 +1,38 @@ +import { useEffect } from 'react' +import type { ExecutionHostId } from '../../../../src/shared/execution-host' +import { useHostQuery } from '../../query/host-query' +import type { RpcClient } from '../../transport/rpc/rpc-client-contract' +import { scopeRpcClientToExecutionHost } from '../../worktree/execution-host-scoped-rpc-client' +import { gitStatusSummaryQuery, serverGitStatusSummaryQuery } from '../mobile-git-status-query' + +const NO_INPUT = {} + +/** One attached worktree's status summary, read on its own server when relayed. */ +export function useFolderWorktreeStatus(args: { + hostId: string + /** The paired desktop's client while connected and the row can be read, else null. */ + client: RpcClient | null + routeHost: ExecutionHostId | undefined + worktreeId: string + subscribed: boolean + refreshers: Set<() => void> +}) { + const { hostId, client, routeHost, worktreeId, subscribed, refreshers } = args + const rowClient = client && routeHost ? scopeRpcClientToExecutionHost(client, routeHost) : client + const status = useHostQuery( + routeHost ? serverGitStatusSummaryQuery : gitStatusSummaryQuery, + { hostId, client: rowClient }, + { exec: routeHost ?? 'local', worktree: worktreeId }, + NO_INPUT, + { subscribed } + ) + const refetch = status.refetch + useEffect(() => { + const refresh = () => void refetch() + refreshers.add(refresh) + return () => { + refreshers.delete(refresh) + } + }, [refetch, refreshers]) + return status +} diff --git a/mobile/src/source-control/folder/use-mobile-folder-attached-worktrees.perf.test.ts b/mobile/src/source-control/folder/use-mobile-folder-attached-worktrees.perf.test.ts new file mode 100644 index 00000000000..b24b3c0908a --- /dev/null +++ b/mobile/src/source-control/folder/use-mobile-folder-attached-worktrees.perf.test.ts @@ -0,0 +1,298 @@ +import { createElement, Fragment } from 'react' +import { useQueryClient, type QueryClient } from '@tanstack/react-query' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { RuntimeClientEventStreamMessage } from '../../../../src/shared/runtime-client-events' +import { stubRpcClient } from '../../transport/rpc/rpc-client-test-stub' +import type { RpcClient } from '../../transport/rpc/rpc-client-contract' +import type { Worktree } from '../../worktree/workspace-list-types' +import type * as MobileWorkspaceLineage from '../../worktree/mobile-workspace-lineage' +import type * as FolderLineageSerialization from './folder-lineage-serialization' +import type { MobileRelayHost } from '../../../../src/shared/remote-runtime/relay/mobile-relay-hosts-contract' +import { MOBILE_DESKTOP_RELAY_RUNTIME_CAPABILITY } from '../../../../src/shared/mobile-desktop-relay-contract' +import { HOST_LIST_TARGET, hostServerWorkspacesQuery } from '../../host-screen/host-list-queries' +import { hostQueryKey } from '../../query/host-query-key' +import { + documentQueryClient, + settleQueryNotifications +} from '../../test-support/rpc-recording/hook-mount' +import { + useMobileFolderAttachedWorktrees, + type MobileFolderAttachedWorktrees +} from './use-mobile-folder-attached-worktrees' +import { MobileFolderWorktreeRow } from './MobileFolderWorktreeRow' + +vi.mock('react-native', () => ({ AppState: {} })) +const gates = vi.hoisted(() => { + const hostCapabilities: string[] = [] + return { hostCapabilities } +}) +vi.mock('../../components/host-protocol-gates-context', () => ({ + useOptionalHostProtocolGates: () => gates +})) +const host = vi.hoisted(() => { + const state: { client: unknown } = { client: null } + return state +}) +vi.mock('../../transport/connection/host-client-hooks', () => ({ + useHostClient: () => ({ client: host.client, clientId: 'client-1', state: 'connected' }) +})) +const lineage = vi.hoisted(() => ({ resolutions: 0, serialized: 0, rowCommits: 0 })) +vi.mock('../../worktree/mobile-workspace-lineage', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + getMobileWorkspaceLineageChildren: ( + ...args: Parameters + ) => { + lineage.resolutions += 1 + return actual.getMobileWorkspaceLineageChildren(...args) + } + } +}) +// Runs behind the production key cache, so each call is a row serialized. +vi.mock('./folder-lineage-serialization', async (importOriginal) => { + const actual = await importOriginal() + return { + serializeFolderLineage: (row: Worktree) => { + lineage.serialized += 1 + return actual.serializeFolderLineage(row) + } + } +}) +// Inside the production row's memo boundary: each call is a committed row render. +vi.mock('../../components/list/ListGroup', () => ({ + ListRow: () => { + lineage.rowCommits += 1 + return null + } +})) +vi.mock('./use-folder-worktree-status', () => ({ + useFolderWorktreeStatus: () => NO_STATUS +})) +vi.mock('../../i18n/use-mobile-translation', () => ({ + useMobileTranslation: () => (_key: string, fallback: string) => fallback +})) +const NO_STATUS = vi.hoisted(() => ({ data: undefined, error: null })) +const REFRESHERS = new Set<() => void>() +const NOOP = (): void => {} + +const READY: RuntimeClientEventStreamMessage = { type: 'ready', subscriptionId: 'sub-1' } + +function row(worktreeId: string, overrides: Partial = {}): Worktree { + return { + worktreeId, + repoId: worktreeId.split('::')[0], + repo: 'api', + branch: 'feature', + displayName: worktreeId, + path: `/src/${worktreeId}`, + liveTerminalCount: 0, + hasAttachedPty: false, + unread: false, + isPinned: false, + linkedPR: null, + ...overrides + } +} + +/** H host rows: the folder, N attached worktrees, and unrelated ones. */ +function catalog(h: number, n: number, edit: (rows: Worktree[]) => void = () => {}): Worktree[] { + const rows = [row('folder:f-1', { workspaceKind: 'folder-workspace' })] + for (let i = 0; i < n; i++) { + rows.push( + row(`repo-a::/w${i}`, { + workspaceLineage: { parentWorkspaceKey: 'folder:f-1', parentInstanceId: null } + }) + ) + } + for (let i = rows.length; i < h; i++) { + rows.push(row(`repo-b::/other${i}`)) + } + edit(rows) + return rows +} + +function catalogHost(initial: Worktree[]) { + let rows = initial + let emit: (event: RuntimeClientEventStreamMessage) => void = () => {} + const client: RpcClient = stubRpcClient({ + getLastConnectedAt: () => 1, + sendRequest: async (method) => ({ + id: 'call', + ok: true, + result: method === 'worktree.ps' ? { worktrees: rows } : {}, + _meta: { runtimeId: 'runtime-1' } + }), + subscribe: (method, _params, onEvent) => { + if (method === 'runtime.clientEvents.subscribe') { + emit = (event) => onEvent(event) + } + return () => {} + } + }) + return { + client, + setRows: (next: Worktree[]) => { + rows = next + }, + emit: (event: RuntimeClientEventStreamMessage) => emit(event) + } +} + +let renderer: ReactTestRenderer | null = null +const queries = documentQueryClient() + +afterEach(async () => { + gates.hostCapabilities = [] + act(() => renderer?.unmount()) + renderer = null + await queries.end() + vi.useRealTimers() +}) + +let queryClient: QueryClient | null = null + +async function mount(read: { current: MobileFolderAttachedWorktrees | null }) { + function Harness() { + queryClient = useQueryClient() + const folder = useMobileFolderAttachedWorktrees('host-1', 'folder:f-1', true) + read.current = folder + return createElement( + Fragment, + null, + folder.worktrees.map((worktree) => + createElement(MobileFolderWorktreeRow, { + key: worktree.worktreeId, + hostId: 'host-1', + desktopCapabilities: folder.desktopCapabilities, + worktree, + unreachable: false, + subscribed: true, + refreshers: REFRESHERS, + onOpen: NOOP + }) + ) + ) + } + await act(async () => { + renderer = create(queries.wrap(createElement(Harness))) + }) + await settleQueryNotifications() +} + +async function rowsChanged(fake: ReturnType, next: Worktree[]) { + fake.setRows(next) + // Past the catalog's three-second signal floor. + vi.setSystemTime(Date.now() + 5_000) + await act(async () => fake.emit({ type: 'worktreeRowsChanged' })) + await settleQueryNotifications() +} + +function churn(rows: Worktree[]): void { + const h = rows.length + rows[1] = { ...rows[1], liveTerminalCount: 3, unread: true } + rows[h - 1] = { ...rows[h - 1], status: 'working' } + rows[h - 2] = { ...rows[h - 2], displayName: 'elsewhere', branch: 'other' } +} + +function rename(rows: Worktree[]): void { + rows[2] = { ...rows[2], displayName: 'renamed', branch: 'renamed-branch' } +} + +describe.each([ + { h: 750, n: 30 }, + { h: 7_500, n: 300 } +])('folder membership over H=$h host rows, N=$n attached', ({ h, n }) => { + it('resolves lineage only for lineage changes, serializing and committing only changed rows', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const fake = catalogHost(catalog(h, n)) + host.client = fake.client + const read: { current: MobileFolderAttachedWorktrees | null } = { current: null } + await mount(read) + fake.emit(READY) + await settleQueryNotifications() + expect(read.current?.worktrees).toHaveLength(n) + const members = read.current!.worktrees + lineage.resolutions = 0 + lineage.serialized = 0 + lineage.rowCommits = 0 + + // Agent attention and terminal counts on a member and an unrelated row, and an unrelated rename. + await rowsChanged(fake, catalog(h, n, churn)) + expect(lineage.resolutions).toBe(0) + expect(lineage.serialized).toBe(3) + expect(lineage.rowCommits).toBe(0) + expect(read.current?.worktrees).toBe(members) + + // A member renamed: shown at once, without resolving lineage or touching the other members. + lineage.serialized = 0 + await rowsChanged( + fake, + catalog(h, n, (rows) => { + churn(rows) + rename(rows) + }) + ) + expect(lineage.resolutions).toBe(0) + expect(lineage.serialized).toBe(1) + expect(lineage.rowCommits).toBe(1) + const renamed = read.current!.worktrees + expect(renamed[1]).toMatchObject({ displayName: 'renamed', branch: 'renamed-branch' }) + expect(renamed.filter((member, index) => member !== members[index])).toHaveLength(1) + + // A worktree attached: membership follows. + await rowsChanged( + fake, + catalog(h, n, (rows) => { + churn(rows) + rename(rows) + rows[h - 1] = { + ...rows[h - 1], + workspaceLineage: { parentWorkspaceKey: 'folder:f-1', parentInstanceId: null } + } + }) + ) + expect(lineage.resolutions).toBe(1) + expect(read.current?.worktrees).toHaveLength(n + 1) + }) + + it('resolves lineage again for a server store change, not for its health', async () => { + gates.hostCapabilities = [MOBILE_DESKTOP_RELAY_RUNTIME_CAPABILITY] + const fake = catalogHost(catalog(h, n)) + host.client = fake.client + const read: { current: MobileFolderAttachedWorktrees | null } = { current: null } + await mount(read) + const serversKey = hostQueryKey('host-1', hostServerWorkspacesQuery.family, HOST_LIST_TARGET, { + deltas: false + }) + const servers = (overrides: Partial) => ({ + hosts: Array.from({ length: 30 }, (_, i) => ({ + hostId: `runtime:env-${i}` as const, + label: `env ${i}`, + health: 'available' as const, + relay: 'ready' as const, + installationId: `install-${i}`, + ...(i === 0 ? overrides : {}) + })), + worktrees: [] + }) + const setServers = async (overrides: Partial) => { + await act(async () => { + queryClient!.setQueryData(serversKey, servers(overrides)) + }) + await settleQueryNotifications() + } + await setServers({}) + expect(read.current?.worktrees).toHaveLength(n) + const members = read.current!.worktrees + lineage.resolutions = 0 + + await setServers({ health: 'connecting', relay: 'unavailable' }) + expect(lineage.resolutions).toBe(0) + expect(read.current?.worktrees).toBe(members) + + await setServers({ installationId: 'install-new' }) + expect(lineage.resolutions).toBe(1) + }) +}) diff --git a/mobile/src/source-control/folder/use-mobile-folder-attached-worktrees.ts b/mobile/src/source-control/folder/use-mobile-folder-attached-worktrees.ts new file mode 100644 index 00000000000..027e2836d1a --- /dev/null +++ b/mobile/src/source-control/folder/use-mobile-folder-attached-worktrees.ts @@ -0,0 +1,181 @@ +import { useContext, useMemo, useState } from 'react' +import { replaceEqualDeep } from '@tanstack/react-query' +import { MOBILE_RELAY_HOST_WORKTREE_DELTAS_RUNTIME_CAPABILITY } from '../../../../src/shared/mobile-desktop-relay-contract' +import { useOptionalHostProtocolGates } from '../../components/host-protocol-gates-context' +import { + HOST_LIST_POLL_MS, + HOST_LIST_TARGET, + hostServerWorkspacesQuery, + hostWorktreeCatalogQuery, + NO_HOST_LIST_INPUT +} from '../../host-screen/host-list-queries' +import { useWorkspaceExecutionHost } from '../../navigation/workspace-execution-host' +import { useHostQuery } from '../../query/host-query' +import { useHostClient } from '../../transport/connection/host-client-hooks' +import { relaysToServers } from '../../worktree/execution-host-scoped-rpc-client' +import type { MobileLineageStores } from '../../worktree/mobile-workspace-lineage' +import { WorkspaceServerContext } from '../../worktree/workspace-server-context' +import type { ConnectionState } from '../../transport/connection/connection-state' +import type { MobileRelayHost } from '../../../../src/shared/remote-runtime/relay/mobile-relay-hosts-contract' +import { + findFolderWorkspaceRow, + folderLineageKey, + getFolderAttachedWorktrees, + toFolderListRow, + type FolderListRow +} from './mobile-folder-attached-worktrees' +import type { Worktree } from '../../worktree/workspace-list-types' + +type FolderLineage = { + /** The catalog rows last seen. */ + source: readonly Worktree[] + /** The rows membership was resolved over; same lineage keys as `source`, in the same order. */ + rows: readonly Worktree[] + keys: readonly string[] +} + +const NO_ROWS: FolderListRow[] = [] + +// Reads each row's cached key: only rows the catalog replaced are keyed again. +function sameLineage(held: FolderLineage | null, rows: readonly Worktree[]): held is FolderLineage { + if (!held || held.keys.length !== rows.length) { + return false + } + return rows.every((row, index) => folderLineageKey(row) === held.keys[index]) +} + +const NO_CAPABILITIES: readonly string[] = [] +const NO_SERVER_HOSTS: readonly MobileRelayHost[] = [] + +export type MobileFolderAttachedWorktrees = { + /** Undefined until the host's list is read; null when the list has no such folder. */ + folder: FolderListRow | null | undefined + worktrees: readonly FolderListRow[] + desktopCapabilities: readonly string[] + /** The servers the desktop relays to, for rows it can't open. */ + serverHosts: readonly MobileRelayHost[] + connState: ConnectionState + /** The first catalog read's failure, while nothing is shown. */ + loadError: Error | null + refetch: () => void +} + +/** The folder's attached worktrees from the host list's own reads, so the list and this screen agree. */ +export function useMobileFolderAttachedWorktrees( + hostId: string, + folderWorktreeId: string, + subscribed: boolean +): MobileFolderAttachedWorktrees { + // The desktop lists every row, a relayed server's included, so read through it even on a server route. + const { client, state } = useHostClient(hostId) + const executionHost = useWorkspaceExecutionHost() + const server = useContext(WorkspaceServerContext) + const contextGates = useOptionalHostProtocolGates() + // In a server's scope the gates in context are the server's; the desktop's travel with it. + const desktopGates = server ? (server.desktopGates ?? null) : contextGates + const desktopCapabilities = desktopGates?.hostCapabilities ?? NO_CAPABILITIES + const ownInstallationId = desktopGates?.hostInstallationId + const host = { hostId, client: state === 'connected' ? client : null } + const catalog = useHostQuery( + hostWorktreeCatalogQuery, + host, + HOST_LIST_TARGET, + NO_HOST_LIST_INPUT, + { subscribed } + ) + const relays = client !== null && relaysToServers(client, desktopCapabilities) + const servers = useHostQuery( + hostServerWorkspacesQuery, + host, + HOST_LIST_TARGET, + { deltas: desktopCapabilities.includes(MOBILE_RELAY_HOST_WORKTREE_DELTAS_RUNTIME_CAPABILITY) }, + // Execution hosts' notices are not relayed, so server rows keep the host list's poll. + { enabled: relays, subscribed, refetchInterval: HOST_LIST_POLL_MS } + ) + const ownRows = catalog.data?.worktrees + const serverRows = servers.data?.worktrees + const serverHosts = servers.data?.hosts + const allRows = useMemo( + () => ownRows && (serverRows?.length ? [...ownRows, ...serverRows] : ownRows), + [ownRows, serverRows] + ) + // Agent, terminal and label updates rewrite rows constantly; membership is resolved again only when lineage moves. + const [lineage, setLineage] = useState(null) + let held = lineage + if (allRows && held?.source !== allRows) { + held = sameLineage(held, allRows) + ? { ...held, source: allRows } + : { source: allRows, rows: allRows, keys: allRows.map(folderLineageKey) } + setLineage(held) + } + const lineageRows = held?.rows + const serverRowsRead = serverRows !== undefined + // Health and relay state flip often; the resolver reads only each server's installation. + const storesKey = JSON.stringify( + serverHosts?.map((server) => [server.hostId, server.installationId]) ?? [] + ) + const [heldStores, setHeldStores] = useState<{ key: string; stores: MobileLineageStores } | null>( + null + ) + let stores = heldStores?.stores + if (heldStores?.key !== storesKey || stores?.ownInstallationId !== ownInstallationId) { + stores = { ownInstallationId, servers: serverHosts ?? NO_SERVER_HOSTS } + setHeldStores({ key: storesKey, stores }) + } + const membership = useMemo(() => { + // A server's folder is unknown, not missing, until its rows are read. + if (!lineageRows || (executionHost && relays && !serverRowsRead)) { + return undefined + } + const folder = findFolderWorkspaceRow(lineageRows, folderWorktreeId, executionHost) + if (!folder) { + return null + } + const indexOf = new Map(lineageRows.map((row, index) => [row, index])) + return { + folderIndex: indexOf.get(folder)!, + memberIndexes: getFolderAttachedWorktrees(lineageRows, folder, stores).map((row) => + indexOf.get(row)! + ) + } + }, [lineageRows, serverRowsRead, stores, folderWorktreeId, executionHost, relays]) + // Same lineage means same row order, so the current rows supply the labels shown. + const currentRows = held?.source + const shown = useMemo( + () => + membership && currentRows + ? { + folder: toFolderListRow(currentRows[membership.folderIndex]), + worktrees: membership.memberIndexes.map((index) => toFolderListRow(currentRows[index])) + } + : null, + [membership, currentRows] + ) + const [heldShown, setHeldShown] = useState({ from: shown, value: shown }) + let stableShown = heldShown.value + if (heldShown.from !== shown) { + stableShown = replaceEqualDeep(heldShown.value, shown) + setHeldShown({ from: shown, value: stableShown }) + } + const resolved = + membership === undefined + ? { folder: undefined, worktrees: NO_ROWS } + : stableShown + ? stableShown + : { folder: null, worktrees: NO_ROWS } + const refetchCatalog = catalog.refetch + const refetchServers = servers.refetch + return { + ...resolved, + desktopCapabilities, + serverHosts: serverHosts ?? NO_SERVER_HOSTS, + connState: state, + loadError: ownRows ? null : catalog.error, + refetch: () => { + void refetchCatalog() + if (relays) { + void refetchServers() + } + } + } +} diff --git a/mobile/src/source-control/git-status-reply-schema.ts b/mobile/src/source-control/git-status-reply-schema.ts index 327e9292261..fd7f0592b3a 100644 --- a/mobile/src/source-control/git-status-reply-schema.ts +++ b/mobile/src/source-control/git-status-reply-schema.ts @@ -59,7 +59,9 @@ export const gitStatusHostPayloadSchema = z.looseObject({ conflictOperation: salvagedOptional('conflictOperation', gitConflictOperationSchema), branch: salvagedOptional('branch', z.string()), head: salvagedOptional('head', z.string()), - upstreamStatus: salvagedOptional('upstreamStatus', gitUpstreamStatusSchema) + upstreamStatus: salvagedOptional('upstreamStatus', gitUpstreamStatusSchema), + // The host's own failure reading status, sent with whatever entries it got. + readError: salvagedOptional('readError', z.string()) }) export type MobileGitStatusEntry = z.output diff --git a/mobile/src/source-control/mobile-git-status-query.ts b/mobile/src/source-control/mobile-git-status-query.ts index bc88b070c7a..986a262e7f1 100644 --- a/mobile/src/source-control/mobile-git-status-query.ts +++ b/mobile/src/source-control/mobile-git-status-query.ts @@ -1,15 +1,17 @@ import * as z from 'zod' +import { hashKey, type QueryClient } from '@tanstack/react-query' import { translate } from '../i18n/mobile-i18n' import { LOCAL_EXECUTION_HOST_ID } from '../../../src/shared/execution-host' import { getRepoIdFromWorktreeId, worktreeIdsEqual } from '../../../src/shared/worktree/id' import { defineHostQuery, type HostSignalEvent } from '../query/host-query' -import type { HostQueryTarget } from '../query/host-query-key' +import { hostQueryKey, type HostQueryTarget } from '../query/host-query-key' import type { RpcClient } from '../transport/rpc/rpc-client-contract' import { gitStatusHostPayloadSchema, type MobileGitStatusHostPayload } from './git-status-reply-schema' import { gitStatusHostPayloadRead } from './mobile-git-read-operations' +import { holdsRestoredHostQueryData } from '../query/host-query-persistence' import { isMobileGitTransientRefreshError, isMobileGitUnavailableReply, @@ -28,12 +30,14 @@ export type GitStatusRead = async function readGitStatus( client: RpcClient, worktreeId: string, - revalidating: boolean + revalidating: boolean, + lineStats = true ): Promise { for (let attempt = 0; ; attempt += 1) { // Changes rows show each file's +/- counts, so ask the host for line stats. const reply = await gitStatusHostPayloadRead.request(client, { worktree: `id:${worktreeId}`, + ...(lineStats ? {} : { includeLineStats: false }), // Rows are already shown: reuse counts while HEAD and entries match, and never wake a stopped WSL distro. ...(revalidating && { reuseLineStats: true, admissionTier: 'background' as const }) }) @@ -93,3 +97,70 @@ export const gitStatusQuery = defineHostQuery({ ]) } }) + +const fetchStatusSummary = ( + client: RpcClient, + target: HostQueryTarget, + _input: Record, + previous: GitStatusRead | undefined +) => readGitStatus(client, target.worktree ?? '', previous !== undefined, false) + +/** Branch, sync and change count only, for a list that shows no per-file counts; older hosts ignore the opt-out. */ +export const gitStatusSummaryQuery = defineHostQuery({ + family: 'git.statusSummary', + staleTime: 3_000, + refetchOnWindowFocus: true, + signal: { events: ['gitStatusChanged'], floorMs: 1_000, matches: namesThisStatus }, + fetch: fetchStatusSummary +}) + +// A relayed server's statuses get no desktop signal (namesThisStatus), so its reads hold no event stream. +export const serverGitStatusSummaryQuery = defineHostQuery({ + family: 'git.statusSummary.server', + staleTime: 3_000, + refetchOnWindowFocus: true, + fetch: fetchStatusSummary +}) + +/** Hands a detailed read to the summary a folder list shows for the same worktree, so Back shows what an action just did. */ +export async function publishGitStatusSummary( + queryClient: QueryClient, + hostId: string, + target: HostQueryTarget, + read: GitStatusRead, + readAt: number, + /** A read accepted now; otherwise a cached one, which can't tell whether a summary read out started before it. */ + accepted: boolean +): Promise { + // An earlier launch's copy is unconfirmed; the summary's own read decides. + if ( + holdsRestoredHostQueryData( + queryClient, + hashKey(hostQueryKey(hostId, gitStatusQuery.family, target, {})) + ) + ) { + return + } + const summary = + target.exec === LOCAL_EXECUTION_HOST_ID ? gitStatusSummaryQuery : serverGitStatusSummaryQuery + const queryKey = hostQueryKey(hostId, summary.family, target, {}) + // No list reads this worktree, or its summary, a failed read included, is newer than this read. + const supersedes = () => { + const state = queryClient.getQueryState(queryKey) + return state !== undefined && Math.max(state.dataUpdatedAt, state.errorUpdatedAt) < readAt + } + if (!supersedes()) { + return + } + if (queryClient.getQueryState(queryKey)?.fetchStatus !== 'idle') { + // A cached read leaves a summary read out to answer for itself. + if (!accepted) { + return + } + // A summary read out started before this answer; landing later, it would undo it. + await queryClient.cancelQueries({ queryKey, exact: true }, { silent: true }) + } + if (supersedes()) { + queryClient.setQueryData(queryKey, read, { updatedAt: readAt }) + } +} diff --git a/mobile/src/source-control/review/mobile-diff-lines.test.ts b/mobile/src/source-control/review/mobile-diff-lines.test.ts deleted file mode 100644 index 287d9eddfb4..00000000000 --- a/mobile/src/source-control/review/mobile-diff-lines.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { buildMobileDiffLines } from './mobile-diff-lines' - -describe('buildMobileDiffLines', () => { - it('marks added, deleted, and unchanged lines', () => { - const result = buildMobileDiffLines('one\ntwo\nthree\n', 'one\nTWO\nthree\nfour\n') - - expect(result.truncated).toBe(false) - expect(result.lines).toEqual([ - { kind: 'context', text: 'one', oldLineNumber: 1, newLineNumber: 1 }, - { kind: 'delete', text: 'two', oldLineNumber: 2 }, - { kind: 'add', text: 'TWO', newLineNumber: 2 }, - { kind: 'context', text: 'three', oldLineNumber: 3, newLineNumber: 3 }, - { kind: 'add', text: 'four', newLineNumber: 4 } - ]) - }) - - it('hides a re-indent unless whitespace is shown, like desktop', () => { - const original = 'if (a) {\n run()\n}\n' - const modified = 'if (a) {\n run()\n}\n' - const kinds = (lines: { kind: string }[]) => lines.map((line) => line.kind) - expect( - kinds(buildMobileDiffLines(original, modified, { ignoreTrimWhitespace: true }).lines) - ).toEqual(['context', 'context', 'context']) - expect(kinds(buildMobileDiffLines(original, modified).lines)).toEqual([ - 'context', - 'delete', - 'add', - 'context' - ]) - }) -}) diff --git a/mobile/src/source-control/review/mobile-diff-review-branch-compare-cache.ts b/mobile/src/source-control/review/mobile-diff-review-branch-compare-cache.ts new file mode 100644 index 00000000000..1a85fde8f6e --- /dev/null +++ b/mobile/src/source-control/review/mobile-diff-review-branch-compare-cache.ts @@ -0,0 +1,53 @@ +import type { QueryClient } from '@tanstack/react-query' +import { defineHostQuery, fetchHostQuery } from '../../query/host-query' +import { hostQueryKey, type HostQueryTarget } from '../../query/host-query-key' +import type { RpcClient } from '../../transport/rpc/rpc-client-contract' +import { gitStatusQuery } from '../mobile-git-status-query' +import type { BranchCompareLoadResult } from './mobile-diff-review-loaders' + +export type ReviewBranchCompareKey = { baseRef: string; head: string } + +// Read by Review with the base ref it resolved. A desktop git change can move the base and leave status as it was, +// so the change that re-reads status also marks these stale. +const reviewBranchCompareQuery = defineHostQuery({ + family: 'git.branchCompare', + signal: gitStatusQuery.signal +}) + +export async function readCachedReviewBranchCompare( + queryClient: QueryClient, + host: { hostId: string; client: RpcClient }, + target: HostQueryTarget, + key: ReviewBranchCompareKey, + read: () => Promise +): Promise { + const loaded = await fetchHostQuery( + queryClient, + reviewBranchCompareQuery, + host, + target, + key, + read + ) + // Only a compare that landed for this head is worth reusing; cached status can trail a commit. + if (loaded.result?.summary.headOid !== key.head) { + queryClient.removeQueries({ + queryKey: hostQueryKey(host.hostId, reviewBranchCompareQuery.family, target, key), + exact: true + }) + } + return loaded +} + +// Marked by a git change and not being read again, so only a new build brings the current compare. +export function reviewBranchCompareNeedsRead( + queryClient: QueryClient, + hostId: string, + target: HostQueryTarget, + key: ReviewBranchCompareKey +): boolean { + const state = queryClient.getQueryState( + hostQueryKey(hostId, reviewBranchCompareQuery.family, target, key) + ) + return state?.isInvalidated === true && state.fetchStatus === 'idle' +} diff --git a/mobile/src/source-control/review/mobile-diff-review-github.test.ts b/mobile/src/source-control/review/mobile-diff-review-github.test.ts index ccb0f79cc87..d9562349ab7 100644 --- a/mobile/src/source-control/review/mobile-diff-review-github.test.ts +++ b/mobile/src/source-control/review/mobile-diff-review-github.test.ts @@ -2,11 +2,7 @@ import { describe, expect, it } from 'vitest' import type { PRComment } from '../../../../src/shared/github/comment-types' import type { GitHubWorkItemDetails } from '../../../../src/shared/github/work-item-types' import { buildMobileDiffReviewQueue } from './mobile-diff-review-queue' -import { - applyMobileDiffReviewGitHubViewed, - buildMobileDiffReviewGitHub, - canCommentOnGitHub -} from './mobile-diff-review-github' +import { buildMobileDiffReviewGitHub, canCommentOnGitHub } from './mobile-diff-review-github' function comment(overrides: Partial): PRComment { return { @@ -79,35 +75,6 @@ describe('the diff screen’s GitHub pull request', () => { expect(threads?.get(12)?.[0]?.replies.map((reply) => reply.id)).toEqual([2]) }) - it('takes viewed state for the PR’s files from GitHub', () => { - const github = buildMobileDiffReviewGitHub({ - prNumber: 1, - prRepo: null, - localHeadOid: 'head', - details: details({}) - }) - expect(applyMobileDiffReviewGitHubViewed(branchItem, github)[0]).toMatchObject({ - isReviewed: false, - changedSinceReview: true - }) - }) - - it('leaves viewed state on the phone when GitHub sent none for the file', () => { - const github = buildMobileDiffReviewGitHub({ - prNumber: 1, - prRepo: null, - localHeadOid: 'head', - details: details({ - pullRequestId: undefined, - files: [ - { path: 'src/a.ts', status: 'modified', additions: 2, deletions: 1, isBinary: false } - ] - }) - }) - const viewedLocally = branchItem.map((item) => ({ ...item, isReviewed: true })) - expect(applyMobileDiffReviewGitHubViewed(viewedLocally, github)[0]?.isReviewed).toBe(true) - }) - it('offers Comment on GitHub only on commentable lines while the branch is at the PR head', () => { const atHead = buildMobileDiffReviewGitHub({ prNumber: 1, diff --git a/mobile/src/source-control/review/mobile-diff-review-queue.test.ts b/mobile/src/source-control/review/mobile-diff-review-queue.test.ts index cc00ff62d6f..3eec3dc9e1d 100644 --- a/mobile/src/source-control/review/mobile-diff-review-queue.test.ts +++ b/mobile/src/source-control/review/mobile-diff-review-queue.test.ts @@ -39,23 +39,6 @@ function comment(overrides: Partial & Pick): Dif } describe('mobile diff review queue', () => { - it('leaves out a status entry whose staging area it does not know', () => { - const queue = buildMobileDiffReviewQueue({ - worktreeId: 'wt-1', - statusEntries: [ - statusEntry({ path: 'placed.ts', area: 'unstaged' }), - statusEntry({ path: 'placeless.ts', area: undefined }) - ], - branchEntries: [], - branchHeadOid: 'head', - branchMergeBase: 'base', - comments: [], - reviewState: emptyReviewState - }) - - expect(queue.map((item) => item.filePath)).toEqual(['placed.ts']) - }) - it('keeps scope, rename, and source matching when notes share a path', () => { const queue = buildMobileDiffReviewQueue({ worktreeId: 'wt-1', diff --git a/mobile/src/source-control/review/mobile-diff-review-selection.test.ts b/mobile/src/source-control/review/mobile-diff-review-selection.test.ts deleted file mode 100644 index 0ebb1fba205..00000000000 --- a/mobile/src/source-control/review/mobile-diff-review-selection.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - moveMobileDiffReviewSelection, - resolveMobileDiffReviewSelection, - selectMobileDiffReviewIndex -} from './mobile-diff-review-selection' - -const queue = (...keys: string[]) => keys.map((key) => ({ key })) - -describe('mobile diff review selection', () => { - it('follows the open file when files before it leave the queue', () => { - const selection = selectMobileDiffReviewIndex(queue('a', 'b', 'c', 'd'), 1) - expect(resolveMobileDiffReviewSelection(queue('b', 'c', 'd'), selection)).toBe(0) - }) - - it('lands on the file that took its place when the open file leaves', () => { - const selection = selectMobileDiffReviewIndex(queue('a', 'b', 'c'), 1) - expect(resolveMobileDiffReviewSelection(queue('a', 'c'), selection)).toBe(1) - const last = selectMobileDiffReviewIndex(queue('a', 'b', 'c'), 2) - expect(resolveMobileDiffReviewSelection(queue('a', 'b'), last)).toBe(1) - }) - - it('wraps next and previous', () => { - const files = queue('a', 'b', 'c') - const last = selectMobileDiffReviewIndex(files, 2) - expect(moveMobileDiffReviewSelection(files, last, 'next').key).toBe('a') - expect( - moveMobileDiffReviewSelection(files, selectMobileDiffReviewIndex(files, 0), 'previous').key - ).toBe('c') - }) -}) diff --git a/mobile/src/source-control/review/mobile-diff-review-state.test.ts b/mobile/src/source-control/review/mobile-diff-review-state.test.ts index e5a4fbdd4a3..20e73ecedc3 100644 --- a/mobile/src/source-control/review/mobile-diff-review-state.test.ts +++ b/mobile/src/source-control/review/mobile-diff-review-state.test.ts @@ -31,14 +31,4 @@ describe('mobile diff review state', () => { expect(merged.completedAt).toBeUndefined() }) - - it('keeps completion when refreshed identities are unchanged', () => { - const reviewed = markMobileDiffReviewFileReviewed(createMobileDiffReviewState(1), descriptor, 5) - const completed = completeMobileDiffReviewState(reviewed, 6) - - const merged = mergeMobileDiffReviewState(completed, [descriptor], 8) - - expect(merged.completedAt).toBe(6) - expect(merged.files[descriptor.key]?.reviewedAt).toBe(5) - }) }) diff --git a/mobile/src/source-control/review/optimistic-write-sequence.test.ts b/mobile/src/source-control/review/optimistic-write-sequence.test.ts deleted file mode 100644 index 68e619cf5ad..00000000000 --- a/mobile/src/source-control/review/optimistic-write-sequence.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createOptimisticField } from './optimistic-write-sequence' - -describe('OptimisticField — last-intent-wins', () => { - it('reverts only the latest write on failure', () => { - const field = createOptimisticField() - const seqA = field.begin(true) - const seqB = field.begin(false) - expect(field.resolve(false)).toBe(false) - - expect(field.settleFailure(seqA)).toBe(false) - expect(field.resolve(false)).toBe(false) - - expect(field.settleFailure(seqB)).toBe(true) - expect(field.resolve(true)).toBe(true) - }) - - it('a stale failure does not clear a newer optimistic value', () => { - const field = createOptimisticField() - const seqOld = field.begin('old') - field.begin('new') - expect(field.resolve('auth')).toBe('new') - expect(field.settleFailure(seqOld)).toBe(false) - expect(field.resolve('auth')).toBe('new') - }) -}) diff --git a/mobile/src/source-control/review/pr-title-edit.test.ts b/mobile/src/source-control/review/pr-title-edit.test.ts deleted file mode 100644 index 5b5f4bc3c4d..00000000000 --- a/mobile/src/source-control/review/pr-title-edit.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - buildUpdatePRTitleParams, - canEditPRTitle, - createPrTextEditOwnership -} from './pr-title-edit' - -describe('canEditPRTitle', () => { - it('allows editing on open and draft PRs', () => { - expect(canEditPRTitle('open')).toBe(true) - expect(canEditPRTitle('draft')).toBe(true) - }) - it('disallows editing on closed/merged/unknown', () => { - expect(canEditPRTitle('closed')).toBe(false) - expect(canEditPRTitle('merged')).toBe(false) - expect(canEditPRTitle(null)).toBe(false) - expect(canEditPRTitle(undefined)).toBe(false) - }) -}) - -describe('buildUpdatePRTitleParams', () => { - it('returns null for empty/unchanged drafts (no host round-trip)', () => { - expect(buildUpdatePRTitleParams(7, '', 'Current')).toBeNull() - expect(buildUpdatePRTitleParams(7, ' ', 'Current')).toBeNull() - expect(buildUpdatePRTitleParams(7, ' Current ', 'Current')).toBeNull() - }) - it('trims the draft and carries the PR number', () => { - expect(buildUpdatePRTitleParams(7, ' New title ', 'Current')).toEqual({ - prNumber: 7, - title: 'New title' - }) - }) -}) - -describe('createPrTextEditOwnership', () => { - it('keeps a newer edit open when an older Save succeeds after its deferred reread', async () => { - const ownership = createPrTextEditOwnership() - // First Save's write succeeded; its reread is still pending, so Save has not resolved. - const firstReread = Promise.withResolvers() - const first = ownership.save(() => firstReread.promise) - // The user edits again and the newer Save fails. - ownership.touch() - await expect(ownership.save(async () => false)).resolves.toBe(false) - firstReread.resolve(true) - await expect(first).resolves.toBe(false) - // With no newer edit, a successful Save still closes the editor. - await expect(ownership.save(async () => true)).resolves.toBe(true) - }) -}) diff --git a/mobile/src/source-control/review/use-mobile-diff-review-snapshot.test.ts b/mobile/src/source-control/review/use-mobile-diff-review-snapshot.test.ts new file mode 100644 index 00000000000..0ea1695e085 --- /dev/null +++ b/mobile/src/source-control/review/use-mobile-diff-review-snapshot.test.ts @@ -0,0 +1,89 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, expect, it, vi } from 'vitest' +import { documentQueryClient } from '../../test-support/rpc-recording/hook-mount' +import { stubRpcClient } from '../../transport/rpc/rpc-client-test-stub' +import type { RpcResponse } from '../../transport/rpc/rpc-wire-types' +import { useMobileDiffReviewSnapshot } from './use-mobile-diff-review-snapshot' + +vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) + +const WORKTREE = 'repo-m::/r/wt' +let renderer: ReactTestRenderer | undefined +const queries = documentQueryClient() + +afterEach(async () => { + act(() => renderer?.unmount()) + renderer = undefined + await queries.end() +}) + +it('re-reads the branch compare when a desktop git change moves the base but not status', async () => { + let branchFiles = ['a.ts', 'b.ts'] + let emit: (event: unknown) => void = () => {} + const results: Record = { + 'git.status': { + entries: [], + conflictOperation: 'unknown', + head: 'h1', + branch: 'refs/heads/wt' + }, + 'worktree.show': { worktree: { baseRef: 'main', branch: 'refs/heads/wt', head: 'h1' } }, + 'repo.list': { repos: [] }, + 'settings.get': { settings: {} } + } + const client = stubRpcClient({ + getLastConnectedAt: () => 1, + onStateChange: () => () => {}, + subscribe: (_method, _params, onData) => { + emit = onData + return () => {} + }, + sendRequest: async (method): Promise => ({ + id: 'r', + ok: true, + result: + method === 'git.branchCompare' + ? { + summary: { + baseRef: 'main', + compareRef: 'HEAD', + changedFiles: branchFiles.length, + status: 'ready', + headOid: 'h1', + mergeBase: branchFiles.length === 2 ? 'm1' : 'm2' + }, + entries: branchFiles.map((path) => ({ path, status: 'modified' })) + } + : results[method] + }) + }) + let shown: string[] | undefined + function Review(): null { + const { screenState } = useMobileDiffReviewSnapshot({ + client, + connState: 'connected', + hostId: 'h', + worktreeId: WORKTREE, + commitOid: null, + filter: 'all', + setActionError: () => {} + }) + shown = + screenState.kind === 'ready' + ? screenState.branchCompare?.entries?.map((entry) => entry.path) + : undefined + return null + } + await act(async () => { + renderer = create(queries.wrap(createElement(Review))) + }) + act(() => emit({ type: 'ready', subscriptionId: 's' })) + await vi.waitFor(() => expect(shown).toEqual(['a.ts', 'b.ts'])) + + // a.ts was merged into main from another checkout; this worktree's status is unchanged. + branchFiles = ['b.ts'] + act(() => emit({ type: 'gitStatusChanged', repoId: 'repo-m' })) + + await vi.waitFor(() => expect(shown).toEqual(['b.ts']), { timeout: 3_000 }) +}) diff --git a/mobile/src/source-control/review/use-mobile-diff-review-snapshot.ts b/mobile/src/source-control/review/use-mobile-diff-review-snapshot.ts index 1a724609276..10fe03182a0 100644 --- a/mobile/src/source-control/review/use-mobile-diff-review-snapshot.ts +++ b/mobile/src/source-control/review/use-mobile-diff-review-snapshot.ts @@ -10,6 +10,11 @@ import type { RpcClient } from '../../transport/rpc/rpc-client-contract' import type { ConnectionState } from '../../transport/connection/connection-state' import { loadMobileDiffReviewCommitSnapshot } from './mobile-diff-review-commit-loader' import type { MobileBranchCompareCache } from './mobile-diff-review-loaders' +import { + readCachedReviewBranchCompare, + reviewBranchCompareNeedsRead, + type ReviewBranchCompareKey +} from './mobile-diff-review-branch-compare-cache' import type { MobileDiffReviewQueueFilter } from './mobile-diff-review-queue' import type { ReviewScreenState } from './mobile-diff-review-screen-model' import { @@ -59,11 +64,17 @@ export function useMobileDiffReviewSnapshot(input: SnapshotInput) { ) // The same git.status entry Changes shows, so Review opened from it starts from those rows. const worktreeReview = worktreeId !== '' && commitOid === null && filter !== 'commit' - const { data: statusRead } = useHostQuery(gitStatusQuery, { hostId, client }, target, NO_INPUT, { - enabled: worktreeReview - }) + const { data: statusRead, dataUpdatedAt: statusReadAt } = useHostQuery( + gitStatusQuery, + { hostId, client }, + target, + NO_INPUT, + { enabled: worktreeReview } + ) // The status read the shown snapshot was built from; AWAITING while a build waits for its first read. const builtFromRef = useRef(undefined) + // The compare the current build read, so a git change that marked it stale rebuilds even when status held. + const builtCompareRef = useRef(null) // Reloads after a write wait for the rebuild they cause, so the screen's buttons match the new files. const buildWaitersRef = useRef<(() => void)[]>([]) const settleWaiters = () => { @@ -72,23 +83,12 @@ export function useMobileDiffReviewSnapshot(input: SnapshotInput) { } } - const cacheBranchCompare = useCallback( - async (key, read) => { - const queryKey = hostQueryKey(hostId, 'git.branchCompare', target, key) - const loaded = await queryClient.fetchQuery({ queryKey, queryFn: read }) - // Only a compare that landed for this head is worth reusing; cached status can trail a commit. - if (loaded.result?.summary.headOid !== key.head) { - queryClient.removeQueries({ queryKey, exact: true }) - } - return loaded - }, - [hostId, queryClient, target] - ) - - const buildSnapshot = useEffectEvent(async (status: GitStatusRead | undefined) => { + // `sameStatus`: only the compare moved, so worktree diffs keyed to the shown status read still hold. + const buildSnapshot = useEffectEvent(async (status?: GitStatusRead, sameStatus = false) => { const generation = loadGenerationRef.current + 1 loadGenerationRef.current = generation const isCurrent = () => generation === loadGenerationRef.current + builtCompareRef.current = null try { if (!worktreeId) { setScreenState({ @@ -170,6 +170,14 @@ export function useMobileDiffReviewSnapshot(input: SnapshotInput) { throw err } ) + const cacheBranchCompare: MobileBranchCompareCache = async (key, read) => { + // A superseded build's compare is never shown. + if (!isCurrent()) { + return { result: null } + } + builtCompareRef.current = key + return readCachedReviewBranchCompare(queryClient, { hostId, client }, target, key, read) + } const { snapshot, branch } = startMobileDiffReviewSnapshot(client, worktreeId, { status: statusInput, compareAgainstUpstream, @@ -183,7 +191,9 @@ export function useMobileDiffReviewSnapshot(input: SnapshotInput) { if (!isCurrent()) { return } - setStatusRevision(queryClient.getQueryState(statusKey)?.dataUpdatedAt ?? 0) + if (!sameStatus) { + setStatusRevision(queryClient.getQueryState(statusKey)?.dataUpdatedAt ?? 0) + } if (loaded) { setScreenState(withMobileDiffReviewBranch(state, loaded, worktreeId)) setActionError(loaded.error ?? null) @@ -224,12 +234,27 @@ export function useMobileDiffReviewSnapshot(input: SnapshotInput) { }, [client, commitOid, connState, queryClient, reloadNonce, statusKey, worktreeReview]) // A status read that changed what Changes shows rebuilds the snapshot; one in flight already brings its own. - useEffect(() => { + // A read that lands unchanged rebuilds too once a git change marked the shown compare stale; a compare + // still out is read again by its own build when it lands marked. + const rebuildOnStatusRead = useEffectEvent((read: GitStatusRead) => { const built = builtFromRef.current - if (worktreeReview && statusRead !== undefined && built !== AWAITING && statusRead !== built) { - void buildSnapshot(statusRead) + if (built === AWAITING) { + return } - }, [statusRead, worktreeReview]) + const compare = builtCompareRef.current + const compareMarked = + compare !== null && reviewBranchCompareNeedsRead(queryClient, hostId, target, compare) + if (read !== built) { + void buildSnapshot(read) + } else if (compareMarked) { + void buildSnapshot(read, true) + } + }) + useEffect(() => { + if (worktreeReview && statusRead !== undefined) { + rebuildOnStatusRead(statusRead) + } + }, [statusRead, statusReadAt, worktreeReview]) // The compare base is read when a snapshot is built; a later setting change rebuilds without re-reading status. const shownCompareSettingRef = useRef(compareAgainstUpstream) diff --git a/mobile/src/source-control/use-mobile-source-control-loaders.test.ts b/mobile/src/source-control/use-mobile-source-control-loaders.test.ts index 652a7baa978..be243eb6934 100644 --- a/mobile/src/source-control/use-mobile-source-control-loaders.test.ts +++ b/mobile/src/source-control/use-mobile-source-control-loaders.test.ts @@ -1,4 +1,5 @@ import { createElement } from 'react' +import { hashKey, QueryClientProvider, type QueryClient } from '@tanstack/react-query' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -7,6 +8,18 @@ import type { RpcClient } from '../transport/rpc/rpc-client-contract' import type { RpcResponse } from '../transport/rpc/rpc-wire-types' import { useMobileSourceControlLoaders } from './use-mobile-source-control-loaders' import { stubRpcClient } from '../transport/rpc/rpc-client-test-stub' +import { prefetchHostQuery } from '../query/host-query' +import { hostQueryKey } from '../query/host-query-key' +import { + gitStatusQuery, + gitStatusSummaryQuery, + serverGitStatusSummaryQuery, + type GitStatusRead +} from './mobile-git-status-query' +import { gitStatusHostPayloadSchema } from './git-status-reply-schema' +import { createOrcaQueryClient } from '../query/orca-query-client' +import { createHostQueryPersistence } from '../query/host-query-persistence' +import type { OrcaQueryStoreBackend } from '../device-store/query-storage' import { documentQueryClient, @@ -178,3 +191,300 @@ describe('useMobileSourceControlLoaders branch compare', () => { expect(read.loaders?.branchCompareState.kind).toBe('ready') }) }) + +describe('useMobileSourceControlLoaders status summary', () => { + let renderer: ReactTestRenderer | null = null + let queryClient: QueryClient | null = null + + afterEach(async () => { + act(() => renderer?.unmount()) + renderer = null + await queryClient?.cancelQueries() + queryClient?.clear() + queryClient = null + vi.useRealTimers() + }) + + const local = { exec: 'local' as const, worktree: WORKTREE } + const summaryKey = hostQueryKey('host-1', gitStatusSummaryQuery.family, local, {}) + const detailKey = hostQueryKey('host-1', gitStatusQuery.family, local, {}) + + function statusReply(branch: string): RpcResponse { + return success({ branch, head: `${branch}-oid`, entries: [] }) + } + + function readOf(branch: string): GitStatusRead { + return { + kind: 'ready', + status: gitStatusHostPayloadSchema.parse({ branch, head: `${branch}-oid`, entries: [] }) + } + } + + // Summary reads skip line stats; the screen's own read asks for them. + function isSummaryRead(params: unknown): boolean { + return ( + typeof params === 'object' && + params !== null && + 'includeLineStats' in params && + params.includeLineStats === false + ) + } + + function takeRead(calls: PendingCall[], summary: boolean): PendingCall { + const index = calls.findIndex( + (call) => call.method === 'git.status' && isSummaryRead(call.params) === summary + ) + if (index === -1) { + throw new Error(`The schedule expected a pending ${summary ? 'summary' : 'status'} read`) + } + return calls.splice(index, 1)[0] + } + + function setup(calls: PendingCall[]) { + const client = fakeClient(calls) + const documentClient = createOrcaQueryClient() + queryClient = documentClient + // Successful writes to each summary entry: its own reads and publications. + const summaryWrites = new Map() + documentClient.getQueryCache().subscribe((event) => { + const family = event.query.queryKey[2] + if ( + event.type === 'updated' && + event.action.type === 'success' && + typeof family === 'string' && + family.startsWith('git.statusSummary') + ) { + summaryWrites.set( + event.query.queryHash, + (summaryWrites.get(event.query.queryHash) ?? 0) + 1 + ) + } + }) + const read: { loaders: ReturnType | null } = { + loaders: null + } + function Harness(): null { + read.loaders = useMobileSourceControlLoaders({ + hostId: 'host-1', + client, + connState: 'connected', + statusIdentityKey: IDENTITY, + worktreeId: WORKTREE, + setActionError: IGNORE_ACTION_ERROR + }) + return null + } + return { + client, + queryClient: documentClient, + read, + writesTo: (key: readonly unknown[]) => summaryWrites.get(hashKey(key)) ?? 0, + clearWrites: () => summaryWrites.clear(), + readSummary: () => + void prefetchHostQuery( + documentClient, + gitStatusSummaryQuery, + { hostId: 'host-1', client }, + local, + {} + ), + mount: async () => { + await act(async () => { + renderer = create( + createElement(QueryClientProvider, { client: documentClient }, createElement(Harness)) + ) + }) + } + } + } + + it('hands each accepted status read to the matching summary once, over an earlier summary read', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const calls: PendingCall[] = [] + const child = setup(calls) + // The same worktree id on a relayed server keeps its own summary. + const elsewhereKey = hostQueryKey( + 'host-1', + serverGitStatusSummaryQuery.family, + { exec: 'runtime:env-1', worktree: WORKTREE }, + {} + ) + const elsewhereData = { kind: 'unavailable' as const } + child.queryClient.setQueryData(elsewhereKey, elsewhereData) + child.clearWrites() + await child.mount() + child.readSummary() + const stale = takeRead(calls, true) + const screenRead = takeRead(calls, false) + + // Landing just after the screen's read, the earlier summary read must not undo it. + await act(async () => { + screenRead.settle(statusReply('opened')) + for (let i = 0; i < 20; i++) { + await Promise.resolve() + } + vi.setSystemTime(Date.now() + 1) + stale.settle(statusReply('before')) + }) + await settleQueryNotifications() + expect(child.queryClient.getQueryData(summaryKey)).toMatchObject({ + status: { branch: 'opened' } + }) + expect(child.writesTo(summaryKey)).toBe(1) + + // An action's forced reread. + const reread = child.read.loaders!.loadStatus({ force: true }) + await settleQueryNotifications() + await act(async () => takeRead(calls, false).settle(statusReply('after'))) + await act(async () => { + await reread + }) + await settleQueryNotifications() + expect(child.queryClient.getQueryData(summaryKey)).toMatchObject({ + status: { branch: 'after' } + }) + expect(child.writesTo(summaryKey)).toBe(2) + expect(child.queryClient.getQueryData(elsewhereKey)).toBe(elsewhereData) + expect(child.writesTo(elsewhereKey)).toBe(0) + expect(calls.filter((call) => call.method === 'git.status')).toHaveLength(0) + }) + + // Summary read at 100, detail cached at 200, child opened at 400. + async function cachedDetailOpened(refreshAt300: boolean) { + vi.useFakeTimers({ toFake: ['Date'], now: 100 }) + const calls: PendingCall[] = [] + const child = setup(calls) + child.queryClient.setQueryData(summaryKey, readOf('first'), { updatedAt: 100 }) + vi.setSystemTime(200) + child.queryClient.setQueryData(detailKey, readOf('cached'), { updatedAt: 200 }) + vi.setSystemTime(300) + if (refreshAt300) { + await child.queryClient.invalidateQueries({ queryKey: summaryKey }, { cancelRefetch: false }) + child.readSummary() + } + child.clearWrites() + vi.setSystemTime(400) + await child.mount() + await settleQueryNotifications() + return { calls, child } + } + + it('leaves a summary read out to answer when the child opens over an older cached read', async () => { + const { calls, child } = await cachedDetailOpened(true) + expect(child.writesTo(summaryKey)).toBe(0) + await act(async () => takeRead(calls, true).settle(statusReply('refresh'))) + await settleQueryNotifications() + expect(child.queryClient.getQueryData(summaryKey)).toMatchObject({ + status: { branch: 'refresh' } + }) + }) + + it('catches an idle older summary up to the cached read once, keeping its time', async () => { + const { calls, child } = await cachedDetailOpened(false) + expect(child.writesTo(summaryKey)).toBe(1) + expect(child.queryClient.getQueryData(summaryKey)).toEqual(readOf('cached')) + expect(child.queryClient.getQueryState(summaryKey)?.dataUpdatedAt).toBe(200) + expect(calls.filter((call) => call.method === 'git.status')).toHaveLength(0) + }) + + it("never hands an earlier launch's status to the summary, nor cancels its live read", async () => { + const store = memoryStore() + const earlier = createOrcaQueryClient() + const earlierPersistence = createHostQueryPersistence(earlier, store.backend) + earlier.getQueryCache().build(earlier, { + queryKey: detailKey, + meta: { persist: gitStatusQuery.persist } + }) + earlier.setQueryData(detailKey, readOf('saved'), { updatedAt: Date.now() - 86_400_000 }) + await settleQueryNotifications() + await earlierPersistence.flush() + expect(store.rows.size).toBe(1) + earlier.clear() + + const calls: PendingCall[] = [] + const child = setup(calls) + createHostQueryPersistence(child.queryClient, store.backend) + child.readSummary() + const release = store.holdReads() + await child.mount() + release() + await settleQueryNotifications() + expect(child.queryClient.getQueryData(detailKey)).toEqual(readOf('saved')) + expect(child.writesTo(summaryKey)).toBe(0) + + await act(async () => takeRead(calls, true).settle(statusReply('live'))) + await settleQueryNotifications() + expect(child.queryClient.getQueryData(summaryKey)).toMatchObject({ status: { branch: 'live' } }) + + await act(async () => takeRead(calls, false).settle(statusReply('newer'))) + await settleQueryNotifications() + expect(child.queryClient.getQueryData(summaryKey)).toMatchObject({ + status: { branch: 'newer' } + }) + expect(child.writesTo(summaryKey)).toBe(2) + }) + + it.each([10, 100])('touches one summary of N=%i listed beside it', async (n) => { + vi.useFakeTimers({ toFake: ['Date'] }) + const calls: PendingCall[] = [] + const child = setup(calls) + const others = Array.from({ length: n }, (_, i) => [ + hostQueryKey( + 'host-1', + gitStatusSummaryQuery.family, + { exec: 'local', worktree: `repo42::/o${i}` }, + {} + ), + hostQueryKey( + 'host-1', + serverGitStatusSummaryQuery.family, + { exec: `runtime:env-${i}`, worktree: WORKTREE }, + {} + ) + ]).flat() + for (const key of [summaryKey, ...others]) { + child.queryClient.setQueryData(key, readOf('first')) + } + child.clearWrites() + vi.setSystemTime(Date.now() + 1) + await child.mount() + await act(async () => takeRead(calls, false).settle(statusReply('opened'))) + await settleQueryNotifications() + expect(child.writesTo(summaryKey)).toBe(1) + expect(others.filter((key) => child.writesTo(key) > 0)).toHaveLength(0) + expect(calls.filter((call) => call.method === 'git.status')).toHaveLength(0) + }) +}) + +function memoryStore() { + const rows = new Map() + let readGate: Promise = Promise.resolve() + const backend: OrcaQueryStoreBackend = { + hostId: 'host-1', + read: async (keys) => { + await readGate + return { status: 'ok', values: keys.map((storeKey) => rows.get(storeKey) ?? null) } + }, + write: async (ops) => { + for (const op of ops) { + if (op.value === null) { + rows.delete(op.key) + } else { + rows.set(op.key, op.value) + } + } + return { written: true } + } + } + return { + backend, + rows, + holdReads: () => { + let release = (): void => {} + readGate = new Promise((resolve) => { + release = resolve + }) + return release + } + } +} diff --git a/mobile/src/source-control/use-mobile-source-control-loaders.ts b/mobile/src/source-control/use-mobile-source-control-loaders.ts index 26dca818647..48a36a09c1b 100644 --- a/mobile/src/source-control/use-mobile-source-control-loaders.ts +++ b/mobile/src/source-control/use-mobile-source-control-loaders.ts @@ -1,5 +1,5 @@ -import { useCallback, useMemo, useRef, useState, type MutableRefObject } from 'react' -import { useQueryClient } from '@tanstack/react-query' +import { useCallback, useEffect, useMemo, useRef, useState, type MutableRefObject } from 'react' +import { hashKey, useQueryClient } from '@tanstack/react-query' import { useMobileTranslation } from '../i18n/use-mobile-translation' import type { MobileSourceControlSettings } from './mobile-source-control-settings-operations' import { useMobileSourceControlSettings } from './mobile-source-control-settings' @@ -16,7 +16,12 @@ import { readBranchCompareOutcome, type BranchCompareAttempt } from './mobile-branch-compare-outcome' -import { gitStatusQuery } from './mobile-git-status-query' +import { + gitStatusQuery, + publishGitStatusSummary, + type GitStatusRead +} from './mobile-git-status-query' +import { hostQueryKey } from '../query/host-query-key' import type { LoadStatusOptions, MobileBranchCompareState, @@ -103,6 +108,34 @@ export function useMobileSourceControlLoaders(params: Params): MobileSourceContr enabled: statusEnabled, subscribed: focused }) + // Published as each read is accepted: a summary read answering just after would otherwise look newer. + useEffect(() => { + const statusKey = hostQueryKey(hostId, gitStatusQuery.family, target, NO_INPUT) + const statusHash = hashKey(statusKey) + const publish = (accepted: boolean) => { + const state = queryClient.getQueryState(statusKey) + if (state?.data) { + void publishGitStatusSummary( + queryClient, + hostId, + target, + state.data, + state.dataUpdatedAt, + accepted + ) + } + } + publish(false) + return queryClient.getQueryCache().subscribe((event) => { + if ( + event.type === 'updated' && + event.action.type === 'success' && + event.query.queryHash === statusHash + ) { + publish(true) + } + }) + }, [hostId, queryClient, target]) const mountedRef = useRef(true) const setRootRef = useCallback((node: View | null): void => { // Invalidate route-detached RPC writes without waiting for passive cleanup. diff --git a/mobile/src/stats/home-stats-total.test.ts b/mobile/src/stats/home-stats-total.test.ts deleted file mode 100644 index daff818e1fa..00000000000 --- a/mobile/src/stats/home-stats-total.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { totalHomeStats } from './home-stats-total' - -describe('totalHomeStats', () => { - it('sums every desktop instead of letting the last reply win', () => { - const total = totalHomeStats( - { - 'host-1': { totalAgentsSpawned: 10, totalPRsCreated: 2, totalAgentTimeMs: 60_000 }, - 'host-2': { totalAgentsSpawned: 5, totalPRsCreated: 1, totalAgentTimeMs: 30_000 } - }, - ['host-1', 'host-2'] - ) - expect(total).toEqual({ totalAgentsSpawned: 15, totalPRsCreated: 3, totalAgentTimeMs: 90_000 }) - }) - - it('leaves out a desktop that is no longer paired', () => { - const byHost = { - 'host-1': { totalAgentsSpawned: 10, totalPRsCreated: 2, totalAgentTimeMs: 60_000 }, - 'host-2': { totalAgentsSpawned: 5, totalPRsCreated: 1, totalAgentTimeMs: 30_000 } - } - expect(totalHomeStats(byHost, ['host-1'])?.totalAgentsSpawned).toBe(10) - expect(totalHomeStats(byHost, [])).toBeNull() - }) - - it('has no stats until a desktop sends a number', () => { - expect(totalHomeStats({}, ['host-1'])).toBeNull() - // A desktop without stats answers `{}`; that is not a row of zeros. - expect(totalHomeStats({ 'host-1': {} }, ['host-1'])).toBeNull() - }) - - it('skips a malformed reply and keeps the other desktops', () => { - const total = totalHomeStats( - { - 'host-1': { totalAgentsSpawned: 10, totalPRsCreated: 2, totalAgentTimeMs: 60_000 }, - 'host-2': null, - 'host-3': { totalAgentsSpawned: 'lots' }, - 'host-4': { totalAgentsSpawned: Number.NaN, totalPRsCreated: 1 } - }, - ['host-1', 'host-2', 'host-3', 'host-4'] - ) - expect(total).toEqual({ totalAgentsSpawned: 10, totalPRsCreated: 3, totalAgentTimeMs: 60_000 }) - }) -}) diff --git a/mobile/src/tasks/github-pr-file-diff.test.ts b/mobile/src/tasks/github-pr-file-diff.test.ts index 99e1f0ac6c4..5120187262b 100644 --- a/mobile/src/tasks/github-pr-file-diff.test.ts +++ b/mobile/src/tasks/github-pr-file-diff.test.ts @@ -3,44 +3,6 @@ import { describe, expect, it } from 'vitest' import { buildGitHubPrFileDiffLines, buildGitHubPrFileDiffPreview } from './github-pr-file-diff' describe('buildGitHubPrFileDiffLines', () => { - it('preserves context and marks added and removed lines', () => { - expect(buildGitHubPrFileDiffLines('one\ntwo\nthree\n', 'one\ntoo\nthree\n')).toEqual([ - { - key: '0:context:1:1', - kind: 'context', - oldLineNumber: 1, - newLineNumber: 1, - text: 'one' - }, - { - key: '1:removed:2', - kind: 'removed', - oldLineNumber: 2, - text: 'two' - }, - { - key: '2:added:2', - kind: 'added', - newLineNumber: 2, - text: 'too' - }, - { - key: '3:context:3:3', - kind: 'context', - oldLineNumber: 3, - newLineNumber: 3, - text: 'three' - } - ]) - }) - - it('shows added files without a fake empty original line', () => { - expect(buildGitHubPrFileDiffLines('', 'first\nsecond')).toEqual([ - { key: '0:added:1', kind: 'added', newLineNumber: 1, text: 'first' }, - { key: '1:added:2', kind: 'added', newLineNumber: 2, text: 'second' } - ]) - }) - it('keeps all lines for large files without exact diff truncation', () => { const original = Array.from({ length: 500 }, (_, index) => `old-${index}`).join('\n') const modified = Array.from({ length: 500 }, (_, index) => `new-${index}`).join('\n') diff --git a/mobile/src/tasks/jira-mobile-connection.test.ts b/mobile/src/tasks/jira-mobile-connection.test.ts deleted file mode 100644 index d6674d69455..00000000000 --- a/mobile/src/tasks/jira-mobile-connection.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { extractJiraConnection, reconcileJiraConnection } from './jira-mobile-connection' - -const siteA = { - id: 'site-a', - siteUrl: 'https://a.atlassian.net', - email: 'me@example.com', - displayName: 'Site A', - accountId: 'acc-1' -} -const siteB = { ...siteA, id: 'site-b', siteUrl: 'https://b.atlassian.net', displayName: 'Site B' } - -describe('Jira connection compatibility', () => { - it('keeps the phone selection when desktop status is refreshed', () => { - const next = extractJiraConnection({ - connected: true, - sites: [siteA, siteB], - selectedSiteId: 'site-a' - }) - expect(reconcileJiraConnection({ ...next, selection: 'site-b' }, next).selection).toBe('site-b') - expect(reconcileJiraConnection({ ...next, selection: 'all' }, next).selection).toBe('all') - expect(reconcileJiraConnection({ ...next, selection: 'gone' }, next).selection).toBe('site-a') - }) -}) diff --git a/mobile/src/tasks/mobile-jira-task-source.test.ts b/mobile/src/tasks/mobile-jira-task-source.test.ts index 80d09b629f6..7056fbe0009 100644 --- a/mobile/src/tasks/mobile-jira-task-source.test.ts +++ b/mobile/src/tasks/mobile-jira-task-source.test.ts @@ -40,19 +40,4 @@ describe('mobile Jira task requests', () => { ).resolves.toEqual({ issue, comments: [] }) } }) - - it('surfaces issue failures even when comments can be read', async () => { - const sendRequest = vi.fn(async (method: string) => - method === 'jira.getIssue' - ? { - id: 'jira-test', - ok: false as const, - error: { code: 'UNAVAILABLE', message: 'Issue permission denied' } - } - : { id: 'jira-test', ok: true as const, result: [] } - ) - await expect(fetchJiraIssueDetail({ sendRequest }, { key: issue.key })).rejects.toThrow( - 'Issue permission denied' - ) - }) }) diff --git a/mobile/src/tasks/setup-hook-trust.test.ts b/mobile/src/tasks/setup-hook-trust.test.ts deleted file mode 100644 index 326cd96862b..00000000000 --- a/mobile/src/tasks/setup-hook-trust.test.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { isSetupHookTrusted } from './setup-hook-trust' -import type { PersistedTrustedOrcaHooks } from '../../../src/shared/orca-yaml-hook-types' - -describe('setup hook trust', () => { - it('trusts a setup script only when the approved hash matches', () => { - const trust: PersistedTrustedOrcaHooks = { - 'repo-1': { setup: { contentHash: 'hash-1', approvedAt: 1000 } } - } - - expect(isSetupHookTrusted(trust, [{ id: 'repo-1' }], 'repo-1', 'hash-1')).toBe(true) - expect(isSetupHookTrusted(trust, [{ id: 'repo-1' }], 'repo-1', 'hash-2')).toBe(false) - }) -}) diff --git a/mobile/src/tasks/smart-source-paste-intent.test.ts b/mobile/src/tasks/smart-source-paste-intent.test.ts deleted file mode 100644 index 39c53a499b7..00000000000 --- a/mobile/src/tasks/smart-source-paste-intent.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { deriveRepoSlug, resolvePasteIntent } from './smart-source-paste-intent' - -describe('resolvePasteIntent', () => { - it('rejects oversized paste intents before any exact lookup', () => { - expect( - resolvePasteIntent(`https://github.com/acme/widgets/issues/12/${'x'.repeat(2048)}`) - ).toBeNull() - }) -}) - -describe('deriveRepoSlug', () => { - it('preserves an Enterprise upstream host', () => { - expect( - deriveRepoSlug({ - upstream: { owner: 'up', repo: 'stream', host: 'github.corp.example' } - }) - ).toEqual({ owner: 'up', repo: 'stream', host: 'github.corp.example' }) - }) -}) diff --git a/mobile/src/tasks/worktree-create-retry.test.ts b/mobile/src/tasks/worktree-create-retry.test.ts deleted file mode 100644 index ab2cb0702af..00000000000 --- a/mobile/src/tasks/worktree-create-retry.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' - -import { createWorktreeWithNameRetry } from './worktree-create-retry' - -type Attempt = { method: string; params: unknown } - -function scriptedClient( - outcomes: ({ id: string; displayName?: string; warning?: string } | { errorMessage: string })[], - attempts: Attempt[] -): RpcClient { - let call = 0 - const client = new FakeSession('connected') - client.sendRequest.mockImplementation(async (method: string, params?: unknown) => { - attempts.push({ method, params: params ?? {} }) - const outcome = outcomes[Math.min(call, outcomes.length - 1)]! - call += 1 - if ('errorMessage' in outcome) { - return { - id: '1', - ok: false, - error: { code: 'x', message: outcome.errorMessage }, - _meta: { runtimeId: 'r' } - } - } - return { - id: '1', - ok: true, - result: { - worktree: { - id: outcome.id, - ...(outcome.displayName !== undefined ? { displayName: outcome.displayName } : {}) - }, - ...(outcome.warning !== undefined ? { warning: outcome.warning } : {}) - }, - _meta: { runtimeId: 'r' } - } - }) - return client -} - -describe('createWorktreeWithNameRetry', () => { - it('falls back to the client candidate when an older host omits displayName', async () => { - const attempts: Attempt[] = [] - const client = scriptedClient( - [{ errorMessage: 'already exists locally' }, { id: 'wt-legacy' }], - attempts - ) - - await expect( - createWorktreeWithNameRetry({ - client, - baseName: 'topic', - buildParams: (name) => ({ repo: 'id:r', name }), - worktreeCreateIdempotency: false - }) - ).resolves.toEqual({ worktreeId: 'wt-legacy', name: 'topic-2' }) - }) -}) diff --git a/mobile/src/terminal/mobile-terminal-query-reply.test.ts b/mobile/src/terminal/mobile-terminal-query-reply.test.ts deleted file mode 100644 index 2bda14d11d5..00000000000 --- a/mobile/src/terminal/mobile-terminal-query-reply.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' - -import { PROGRAM_STATUS_QUERY_REPLY } from '../../../src/shared/program-status/protocol' -import { sendMobileTerminalQueryReply } from './mobile-terminal-query-reply' - -function createClient() { - return { - sendRequest: vi.fn().mockResolvedValue({ - id: '1', - ok: true, - result: { send: { accepted: true, bytesWritten: 6 } }, - _meta: { runtimeId: 'runtime-1' } - }), - subscribe: () => () => {}, - updateTerminalSubscriptionViewport: () => {}, - getState: () => 'connected', - getReconnectAttempt: () => 0, - getLastConnectedAt: () => null, - onStateChange: () => () => {}, - notifyForeground: () => {}, - close: () => {} - } satisfies RpcClient -} - -describe('sendMobileTerminalQueryReply', () => { - it.each([ - ['disconnected', false, new Set(['terminal-1']), '\x1b[3;4R', 'terminal-1'], - ['unsubscribed', true, new Set(), '\x1b[3;4R', 'terminal-1'], - ['stale handle', true, new Set(['terminal-2']), '\x1b[3;4R', 'terminal-1'], - ['ordinary input', true, new Set(['terminal-1']), 'a', 'terminal-1'] - ])('does not send %s data', async (_case, connected, subscribedTerminals, bytes, handle) => { - const client = createClient() - - await expect( - sendMobileTerminalQueryReply({ - bytes, - client, - clientId: 'mobile-1', - connected, - handle, - hostSupportsQueryReplyInput: true, - hostSupportsProgramStatus: true, - subscribedTerminals - }) - ).resolves.toBe(false) - expect(client.sendRequest).not.toHaveBeenCalled() - }) - - // Older hosts strip inputKind and would treat query replies as floor-taking user input. - it('does not send to a host that has not advertised query-reply input support', async () => { - const client = createClient() - - await expect( - sendMobileTerminalQueryReply({ - bytes: '\x1b[3;4R', - client, - clientId: 'mobile-1', - connected: true, - handle: 'terminal-1', - hostSupportsQueryReplyInput: false, - hostSupportsProgramStatus: true, - subscribedTerminals: new Set(['terminal-1']) - }) - ).resolves.toBe(false) - expect(client.sendRequest).not.toHaveBeenCalled() - }) - - it('does not answer program status for a host that cannot read its reports', async () => { - const client = createClient() - - await expect( - sendMobileTerminalQueryReply({ - bytes: PROGRAM_STATUS_QUERY_REPLY, - client, - clientId: 'mobile-1', - connected: true, - handle: 'terminal-1', - hostSupportsQueryReplyInput: true, - hostSupportsProgramStatus: false, - subscribedTerminals: new Set(['terminal-1']) - }) - ).resolves.toBe(false) - expect(client.sendRequest).not.toHaveBeenCalled() - }) -}) diff --git a/mobile/src/terminal/session/mobile-terminal-inventory-request.test.ts b/mobile/src/terminal/session/mobile-terminal-inventory-request.test.ts index 63611774fef..9b22756d32f 100644 --- a/mobile/src/terminal/session/mobile-terminal-inventory-request.test.ts +++ b/mobile/src/terminal/session/mobile-terminal-inventory-request.test.ts @@ -6,19 +6,6 @@ describe('MobileTerminalInventoryRequest', () => { vi.restoreAllMocks() }) - it('starts fresh after the shared request settles or rejects', async () => { - const requests = new MobileTerminalInventoryRequest() - const failure = new Error('transport lost') - - await expect( - requests.run(true, async () => { - throw failure - }) - ).rejects.toBe(failure) - await expect(requests.run(true, async () => true)).resolves.toBe(true) - await expect(requests.run(true, async () => false)).resolves.toBe(false) - }) - it('fences a response after its route activation is replaced', async () => { const oldResponse = Promise.withResolvers() const applied: string[] = [] diff --git a/mobile/src/terminal/session/mobile-terminal-pane-layout.test.ts b/mobile/src/terminal/session/mobile-terminal-pane-layout.test.ts deleted file mode 100644 index 7a51d127ba6..00000000000 --- a/mobile/src/terminal/session/mobile-terminal-pane-layout.test.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { resolveTerminalPaneHandles, terminalPaneViewport } from './mobile-terminal-pane-layout' - -describe('mobile terminal split selection', () => { - it('keeps pane order when focus moves and collapses a closed companion', () => { - expect(resolveTerminalPaneHandles('b', ['a', 'b'], ['a', 'b', 'c'])).toEqual(['a', 'b']) - expect(resolveTerminalPaneHandles('a', ['a', 'b'], ['a', 'c'])).toEqual(['a']) - expect(resolveTerminalPaneHandles('c', ['a', 'b'], ['a', 'b', 'c'])).toEqual(['c', 'a']) - expect(resolveTerminalPaneHandles(null, ['a', 'b'], ['a', 'b'])).toEqual([]) - }) - it('never shares geometry ownership across terminal handles', () => { - const states = new Map() - const a = terminalPaneViewport(states, 'a') - const b = terminalPaneViewport(states, 'b') - a.viewportRef.current = { cols: 40, rows: 30 } - expect(b.viewportRef.current).toBeNull() - expect(terminalPaneViewport(states, 'a')).toBe(a) - }) -}) diff --git a/mobile/src/test-support/spare-document-node.ts b/mobile/src/test-support/spare-document-node.ts new file mode 100644 index 00000000000..13723e207eb --- /dev/null +++ b/mobile/src/test-support/spare-document-node.ts @@ -0,0 +1,4 @@ +// Alias the native spare pool for Vitest: no spare is ever parked, so every entry boots its own page. +export const prepareSpareDocument = (): Promise => Promise.resolve(false) +export const claimSpareDocument = (): Promise => Promise.resolve(null) +export const discardSpareDocument = (): Promise => Promise.resolve() diff --git a/mobile/src/transport/connection/mobile-endpoint-supervisor-relay-race.test.ts b/mobile/src/transport/connection/mobile-endpoint-supervisor-relay-race.test.ts new file mode 100644 index 00000000000..81ac5496981 --- /dev/null +++ b/mobile/src/transport/connection/mobile-endpoint-supervisor-relay-race.test.ts @@ -0,0 +1,128 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + dependencies, + FakeLogicalClient, + FakeRelaySession, + FakeSession, + host, + relay +} from './mobile-endpoint-supervisor-test-fakes' +import { MobileEndpointSupervisor } from './mobile-endpoint-supervisor' +import { createStableLogicalRpcClient } from './stable-logical-rpc-client' + +vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) +vi.mock('expo-secure-store', () => ({ WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'when-unlocked' })) +vi.mock('expo-crypto', () => ({ getRandomBytes: (length: number) => new Uint8Array(length) })) + +// A network-change nudge abandons the stale LAN dial and redials at once. +function redialDirect(logical: FakeLogicalClient): void { + logical.publishState('reconnecting') + logical.publishState('connecting') +} + +async function startOnLan(openRelay = vi.fn(() => new FakeRelaySession('connected'))) { + const logical = new FakeLogicalClient('connected', 'lan') + // Full-width jitter so the shared cooldown runs at its real cadence. + const deps = dependencies({ openRelay, randomBytes: () => new Uint8Array([255, 255]) }) + const supervisor = new MobileEndpointSupervisor(logical, host.id, relay, deps) + await supervisor.start() + await vi.advanceTimersByTimeAsync(0) + return { logical, openRelay, supervisor } +} + +describe('mobile endpoint supervisor relay race after a mid-session LAN loss', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-11-08T12:00:00Z')) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('moves to relay while network-change redials keep the LAN dial connecting', async () => { + const { logical, openRelay, supervisor } = await startOnLan() + + // Nudges every second never let the dial age out of connecting; the race fires 2.5 s into the outage. + for (let i = 0; i < 3; i++) { + redialDirect(logical) + await vi.advanceTimersByTimeAsync(1_000) + } + + expect(openRelay).toHaveBeenCalledOnce() + expect(logical.getActivePath()).toBe('relay') + expect(logical.getState()).toBe('connected') + supervisor.stop() + }) + + it('paces relay dials by the shared cooldown while relay is also unreachable', async () => { + // A relay socket that never authenticates fails its migration. + const { logical, openRelay, supervisor } = await startOnLan( + vi.fn(() => new FakeRelaySession('connecting')) + ) + + for (let i = 0; i < 60; i++) { + redialDirect(logical) + await vi.advanceTimersByTimeAsync(2_000) + } + + // 60 redials in 2 min; each attempt is a cell dial plus a director-resolved retry. + // Racing every redial would open 120 sockets; the 0.5 s→30 s backoff keeps it under 20. + expect(openRelay.mock.calls.length).toBeGreaterThan(0) + expect(openRelay.mock.calls.length).toBeLessThanOrEqual(20) + supervisor.stop() + }) + + it('races each slow LAN blip once and closes the relay socket the LAN beat', async () => { + // The real logical client owns the lost-race close: it aborts after relay authentication. + const direct = new FakeSession('connected') + const logical = createStableLogicalRpcClient(direct, 'lan') + const relaySessions: FakeRelaySession[] = [] + const openRelay = vi.fn(() => { + const session = new FakeRelaySession('connecting') + relaySessions.push(session) + return session + }) + const supervisor = new MobileEndpointSupervisor( + logical, + host.id, + relay, + dependencies({ openRelay, randomBytes: () => new Uint8Array([255, 255]) }) + ) + await supervisor.start() + + for (let flap = 0; flap < 10; flap++) { + direct.publishState('reconnecting') + direct.publishState('connecting') + await vi.advanceTimersByTimeAsync(3_000) + direct.publishState('connected') + relaySessions.at(-1)?.publishState('connected') + await vi.advanceTimersByTimeAsync(10_000) + } + + // Accepted cost: one relay dial per blip past the 2.5 s head start, each closed once it loses. + expect(openRelay).toHaveBeenCalledTimes(10) + expect(relaySessions.every((session) => session.close.mock.calls.length > 0)).toBe(true) + expect(logical.getActivePath()).toBe('lan') + supervisor.stop() + }) + + it('drops a race deferred by cooldown once the LAN comes back', async () => { + const { logical, openRelay, supervisor } = await startOnLan( + vi.fn(() => new FakeRelaySession('connecting')) + ) + for (let i = 0; i < 15; i++) { + redialDirect(logical) + await vi.advanceTimersByTimeAsync(2_000) + } + const dialsDuringOutage = openRelay.mock.calls.length + + logical.publishState('connected') + supervisor.nudge('network-change') + await vi.advanceTimersByTimeAsync(60_000) + + expect(logical.getActivePath()).toBe('lan') + expect(openRelay).toHaveBeenCalledTimes(dialsDuringOutage) + supervisor.stop() + }) +}) diff --git a/mobile/src/transport/connection/mobile-endpoint-supervisor.ts b/mobile/src/transport/connection/mobile-endpoint-supervisor.ts index 6da950ca9e4..afaaf820b14 100644 --- a/mobile/src/transport/connection/mobile-endpoint-supervisor.ts +++ b/mobile/src/transport/connection/mobile-endpoint-supervisor.ts @@ -148,6 +148,8 @@ export class MobileEndpointSupervisor { if (state === 'connected') { this.directGrace.onConnected() if (this.logical.getActivePath() !== 'relay') { + // A direct win answers any race intent deferred by cooldown; replaying it would replace a healthy LAN. + this.pendingReplace = false void this.rotateCredentialIfNeeded(this.relayReconnect.resetForDirectConnection()) } this.directProbe.schedule() @@ -159,6 +161,10 @@ export class MobileEndpointSupervisor { recoveryPresentation.onActiveFailure(this.logical, this.relayReconnect, state, this.bundle) const relayFailure = this.relayReconnect.handleStateFailure(this.logical, state) logRelayDialFailure(this.logRelay, relayFailure, 'active-session') + // Redials keep direct in connecting, which unforced recovery waits out; one timer per outage races them. + if (this.logical.getActivePath() !== 'relay') { + this.directGrace.arm() + } } }) void this.directGrace.loadLastGoodPath() diff --git a/mobile/src/transport/relay/mobile-relay-reconnect-controller.test.ts b/mobile/src/transport/relay/mobile-relay-reconnect-controller.test.ts deleted file mode 100644 index 96370e8bfbc..00000000000 --- a/mobile/src/transport/relay/mobile-relay-reconnect-controller.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { RelayReconnectController } from './mobile-relay-reconnect-controller' - -vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) -vi.mock('expo-crypto', () => ({ - getRandomBytes: (length: number) => new Uint8Array(length) -})) - -describe('relay reconnect controller', () => { - beforeEach(() => { - vi.useFakeTimers() - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('lifts the fresh-credential gate when a durable bundle carries a new version', () => { - const onRetry = vi.fn() - const reconnect = createController(onRetry) - - reconnect.recordRejectedCredential(2) - reconnect.armCredentialReprobe() - expect(reconnect.shouldDefer()).toBe(true) - - reconnect.acceptFreshCredential(2) - expect(reconnect.shouldDefer()).toBe(true) - - reconnect.acceptFreshCredential(3) - expect(reconnect.shouldDefer()).toBe(false) - expect( - reconnect.eligibleCredentials( - { token: 'fresh', version: 3, expiresAt: Number.MAX_SAFE_INTEGER }, - null - ) - ).toHaveLength(1) - }) -}) - -function createController( - onRetry: () => void, - reportFailureCount: (count: number) => void = () => {}, - reportPairingRejected: (rejected: boolean) => void = () => {} -): RelayReconnectController { - const controller = new RelayReconnectController( - { - now: Date.now, - randomBytes: () => new Uint8Array([128, 0]), - setTimer: (handler, ms) => setTimeout(handler, ms), - clearTimer: (handle) => clearTimeout(handle) - }, - onRetry - ) - controller.reportRecoveryTo({ - setRecoveryAttempt: reportFailureCount, - setPairingRejected: reportPairingRejected, - setRelayHostReachability: () => {} - }) - return controller -} diff --git a/mobile/src/transport/relay/relay-host-reachability-latch.test.ts b/mobile/src/transport/relay/relay-host-reachability-latch.test.ts deleted file mode 100644 index c7122e64a94..00000000000 --- a/mobile/src/transport/relay/relay-host-reachability-latch.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -vi.mock('../encryption/mobile-e2ee-v2-client-session', () => ({ - MobileE2EEV2ClientSession: { create: () => ({}) } -})) - -vi.mock('../encryption/mobile-e2ee-v2-physical-channel', () => ({ - MobileE2EEAuthenticationError: class extends Error {}, - MobileE2EEV2PhysicalChannel: class {} -})) - -import { MOBILE_RELAY_CLOSE_CODE } from '../../../../src/shared/remote-runtime/relay/mobile-relay-close-codes' -import { RelayOuterError } from '../encryption/mobile-relay-e2ee-link' -import { RelayHostReachabilityLatch } from './relay-host-reachability-latch' - -const closed = (code: number) => new RelayOuterError(code) -const OFFLINE = MOBILE_RELAY_CLOSE_CODE.HOST_OFFLINE - -describe('RelayHostReachabilityLatch', () => { - // A 4408 between two 4404s is not evidence the desktop came back. - - it('reports an asserted verdict immediately and pins it against later failures', () => { - const latch = new RelayHostReachabilityLatch() - const reporter = vi.fn() - latch.reportTo(reporter) - - latch.assert('signed-out') - expect(latch.current()).toBe('signed-out') - - latch.record(closed(OFFLINE)) - latch.record(closed(OFFLINE)) - expect(latch.current()).toBe('signed-out') - expect(reporter.mock.calls.map(([value]) => value)).toEqual(['connecting', 'signed-out']) - }) -}) diff --git a/mobile/src/worktree/mobile-workspace-lineage.ts b/mobile/src/worktree/mobile-workspace-lineage.ts index 2973036ccc3..9b500882848 100644 --- a/mobile/src/worktree/mobile-workspace-lineage.ts +++ b/mobile/src/worktree/mobile-workspace-lineage.ts @@ -29,7 +29,23 @@ export function getMobileWorkspaceLineageGroupKey(worktree: WorktreeLineageIdent return `workspace-lineage:${encodeURIComponent(getWorktreeRowIdentity(worktree))}` } -function hasValidLineageParent(worktree: Worktree, parent: Worktree): boolean { +/** The row fields lineage reads; a caller may resolve over a projection of its rows. */ +export type MobileLineageRow = Pick< + Worktree, + | 'worktreeId' + | 'hostId' + | 'repoId' + | 'workspaceKind' + | 'isArchived' + | 'parentWorktreeId' + | 'worktreeInstanceId' + | 'lineageWorktreeInstanceId' + | 'parentWorktreeInstanceId' + | 'crossStoreParent' + | 'workspaceLineage' +> + +function hasValidLineageParent(worktree: MobileLineageRow, parent: MobileLineageRow): boolean { if ( worktree.lineageWorktreeInstanceId === undefined && worktree.parentWorktreeInstanceId === undefined @@ -50,15 +66,17 @@ export type MobileLineageStores = { servers: readonly Pick[] } -type ResolutionRow = { - worktree: Worktree +type ResolutionRow = { + worktree: Row id: string hostId: ExecutionHostId instanceId: string | undefined isArchived: boolean } -function getResolutionRows(worktrees: readonly Worktree[]): Map { +function getResolutionRows( + worktrees: readonly Row[] +): Map> { return new Map( worktrees.map((worktree) => [ getWorktreeRowIdentity(worktree), @@ -75,7 +93,7 @@ function getResolutionRows(worktrees: readonly Worktree[]): Map